SQLAlchemy 1.1 Documentation
Selectables, Tables, FROM objects¶
The term “selectable” refers to any object that rows can be selected from;
in SQLAlchemy, these objects descend from FromClause and their
distinguishing feature is their FromClause.c attribute, which is
a namespace of all the columns contained within the FROM clause (these
elements are themselves ColumnElement subclasses).
-
sqlalchemy.sql.expression.alias(selectable, name=None, flat=False)¶ Return an
Aliasobject.An
Aliasrepresents anyFromClausewith an alternate name assigned within SQL, typically using theASclause when generated, e.g.SELECT * FROM table AS aliasname.Similar functionality is available via the
alias()method available on allFromClausesubclasses.When an
Aliasis created from aTableobject, this has the effect of the table being rendered astablename AS aliasnamein a SELECT statement.For
select()objects, the effect is that of creating a named subquery, i.e.(select ...) AS aliasname.The
nameparameter is optional, and provides the name to use in the rendered SQL. If blank, an “anonymous” name will be deterministically generated at compile time. Deterministic means the name is guaranteed to be unique against other constructs used in the same statement, and will also be the same name for each successive compilation of the same statement object.매개 변수: - selectable¶ – any
FromClausesubclass, such as a table, select statement, etc. - name¶ – string name to be assigned as the alias.
If
None, a name will be deterministically generated at compile time. - flat¶ –
Will be passed through to if the given selectable is an instance of
Join- seeJoin.alias()for details.버전 0.9.0에 추가.
- selectable¶ – any
-
sqlalchemy.sql.expression.except_(*selects, **kwargs)¶ Return an
EXCEPTof multiple selectables.The returned object is an instance of
CompoundSelect.
-
sqlalchemy.sql.expression.except_all(*selects, **kwargs)¶ Return an
EXCEPT ALLof multiple selectables.The returned object is an instance of
CompoundSelect.
-
sqlalchemy.sql.expression.exists(*args, **kwargs)¶ Construct a new
Existsagainst an existingSelectobject.Calling styles are of the following forms:
# use on an existing select() s = select([table.c.col1]).where(table.c.col2==5) s = exists(s) # construct a select() at once exists(['*'], **select_arguments).where(criterion) # columns argument is optional, generates "EXISTS (SELECT *)" # by default. exists().where(table.c.col2==5)
-
sqlalchemy.sql.expression.intersect(*selects, **kwargs)¶ Return an
INTERSECTof multiple selectables.The returned object is an instance of
CompoundSelect.
-
sqlalchemy.sql.expression.intersect_all(*selects, **kwargs)¶ Return an
INTERSECT ALLof multiple selectables.The returned object is an instance of
CompoundSelect.
-
sqlalchemy.sql.expression.join(left, right, onclause=None, isouter=False, full=False)¶ Produce a
Joinobject, given twoFromClauseexpressions.E.g.:
j = join(user_table, address_table, user_table.c.id == address_table.c.user_id) stmt = select([user_table]).select_from(j)
would emit SQL along the lines of:
SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id
Similar functionality is available given any
FromClauseobject (e.g. such as aTable) using theFromClause.join()method.매개 변수: - left¶ – The left side of the join.
- right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - isouter¶ – if True, render a LEFT OUTER JOIN, instead of JOIN.
- full¶ –
if True, render a FULL OUTER JOIN, instead of JOIN.
버전 1.1에 추가.
-
sqlalchemy.sql.expression.lateral(selectable, name=None)¶ Return a
Lateralobject.Lateralis anAliassubclass that represents a subquery with the LATERAL keyword applied to it.The special behavior of a LATERAL subquery is that it appears in the FROM clause of an enclosing SELECT, but may correlate to other FROM clauses of that SELECT. It is a special case of subquery only supported by a small number of backends, currently more recent Postgresql versions.
버전 1.1에 추가.
더 보기
LATERAL correlation - overview of usage.
-
sqlalchemy.sql.expression.outerjoin(left, right, onclause=None, full=False)¶ Return an
OUTER JOINclause element.The returned object is an instance of
Join.Similar functionality is also available via the
outerjoin()method on anyFromClause.매개 변수: To chain joins together, use the
FromClause.join()orFromClause.outerjoin()methods on the resultingJoinobject.
-
sqlalchemy.sql.expression.select(columns=None, whereclause=None, from_obj=None, distinct=False, having=None, correlate=True, prefixes=None, suffixes=None, **kwargs)¶ Construct a new
Select.Similar functionality is also available via the
FromClause.select()method on anyFromClause.All arguments which accept
ClauseElementarguments also accept string arguments, which will be converted as appropriate into eithertext()orliteral_column()constructs.매개 변수: - columns¶ –
A list of
ColumnElementorFromClauseobjects which will form the columns clause of the resulting statement. For those objects that are instances ofFromClause(typicallyTableorAliasobjects), theFromClause.ccollection is extracted to form a collection ofColumnElementobjects.This parameter will also accept
Textconstructs as given, as well as ORM-mapped classes.주석
The
select.columnsparameter is not available in the method form ofselect(), e.g.FromClause.select(). - whereclause¶ –
A
ClauseElementexpression which will be used to form theWHEREclause. It is typically preferable to add WHERE criterion to an existingSelectusing method chaining withSelect.where().더 보기
- from_obj¶ –
A list of
ClauseElementobjects which will be added to theFROMclause of the resulting statement. This is equivalent to callingSelect.select_from()using method chaining on an existingSelectobject.더 보기
Select.select_from()- full description of explicit FROM clause specification. - autocommit¶ –
Deprecated. Use
.execution_options(autocommit=<True|False>)to set the autocommit option. - bind=None¶ – an
EngineorConnectioninstance to which the resultingSelectobject will be bound. TheSelectobject will otherwise automatically bind to whateverConnectableinstances can be located within its containedClauseElementmembers. - correlate=True¶ –
indicates that this
Selectobject should have its containedFromClauseelements “correlated” to an enclosingSelectobject. It is typically preferable to specify correlations on an existingSelectconstruct usingSelect.correlate().더 보기
Select.correlate()- full description of correlation. - distinct=False¶ –
when
True, applies aDISTINCTqualifier to the columns clause of the resulting statement.The boolean argument may also be a column expression or list of column expressions - this is a special calling form which is understood by the Postgresql dialect to render the
DISTINCT ON (<columns>)syntax.distinctis also available on an existingSelectobject via thedistinct()method.더 보기
- for_update=False¶ – when
True, appliesFOR UPDATEto the end of the resulting statement.버전 0.9.0 폐지: - use
Select.with_for_update()to specify the structure of theFOR UPDATEclause.for_updateaccepts various string values interpreted by specific backends, including:"read"- on MySQL, translates toLOCK IN SHARE MODE; on Postgresql, translates toFOR SHARE."nowait"- on Postgresql and Oracle, translates toFOR UPDATE NOWAIT."read_nowait"- on Postgresql, translates toFOR SHARE NOWAIT.
더 보기
Select.with_for_update()- improved API for specifying theFOR UPDATEclause. - group_by¶ –
a list of
ClauseElementobjects which will comprise theGROUP BYclause of the resulting select. This parameter is typically specified more naturally using theSelect.group_by()method on an existingSelect.더 보기
- having¶ –
a
ClauseElementthat will comprise theHAVINGclause of the resulting select whenGROUP BYis used. This parameter is typically specified more naturally using theSelect.having()method on an existingSelect.더 보기
- limit=None¶ –
a numerical value which usually renders as a
LIMITexpression in the resulting select. Backends that don’t supportLIMITwill attempt to provide similar functionality. This parameter is typically specified more naturally using theSelect.limit()method on an existingSelect.더 보기
- offset=None¶ –
a numeric value which usually renders as an
OFFSETexpression in the resulting select. Backends that don’t supportOFFSETwill attempt to provide similar functionality. This parameter is typically specified more naturally using theSelect.offset()method on an existingSelect.더 보기
- order_by¶ –
a scalar or list of
ClauseElementobjects which will comprise theORDER BYclause of the resulting select. This parameter is typically specified more naturally using theSelect.order_by()method on an existingSelect.더 보기
- use_labels=False¶ –
when
True, the statement will be generated using labels for each column in the columns clause, which qualify each column with its parent table’s (or aliases) name so that name conflicts between columns in different tables don’t occur. The format of the label is <tablename>_<column>. The “c” collection of the resultingSelectobject will use these names as well for targeting column members.This parameter can also be specified on an existing
Selectobject using theSelect.apply_labels()method.
- columns¶ –
-
sqlalchemy.sql.expression.subquery(alias, *args, **kwargs)¶ Return an
Aliasobject derived from aSelect.- name
- alias name
*args, **kwargs
all other arguments are delivered to theselect()function.
-
sqlalchemy.sql.expression.table(name, *columns)¶ Produce a new
TableClause.The object returned is an instance of
TableClause, which represents the “syntactical” portion of the schema-levelTableobject. It may be used to construct lightweight table constructs.버전 1.0.0으로 변경:
expression.table()can now be imported from the plainsqlalchemynamespace like any other SQL element.매개 변수: - name¶ – Name of the table.
- columns¶ – A collection of
expression.column()constructs.
-
sqlalchemy.sql.expression.union(*selects, **kwargs)¶ Return a
UNIONof multiple selectables.The returned object is an instance of
CompoundSelect.A similar
union()method is available on allFromClausesubclasses.
-
sqlalchemy.sql.expression.union_all(*selects, **kwargs)¶ Return a
UNION ALLof multiple selectables.The returned object is an instance of
CompoundSelect.A similar
union_all()method is available on allFromClausesubclasses.
-
class
sqlalchemy.sql.expression.Alias(selectable, name=None)¶ Bases:
sqlalchemy.sql.expression.FromClauseRepresents an table or selectable alias (AS).
Represents an alias, as typically applied to any table or sub-select within a SQL statement using the
ASkeyword (or without the keyword on certain databases such as Oracle).This object is constructed from the
alias()module level function as well as theFromClause.alias()method available on allFromClausesubclasses.-
alias(name=None, flat=False)¶ - inherited from the
alias()method ofFromClausereturn an alias of this
FromClause.This is shorthand for calling:
from sqlalchemy import alias a = alias(self, name=name)
See
alias()for details.
-
c¶ - inherited from the
cattribute ofFromClauseAn alias for the
columnsattribute.
-
columns¶ - inherited from the
columnsattribute ofFromClauseA named-based collection of
ColumnElementobjects maintained by thisFromClause.The
columns, orccollection, is the gateway to the construction of SQL expressions using table-bound or other selectable-bound columns:select([mytable]).where(mytable.c.somecolumn == 5)
-
compare(other, **kw)¶ - inherited from the
compare()method ofClauseElementCompare this ClauseElement to the given ClauseElement.
Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass compare() methods and may be used to modify the criteria for comparison. (see
ColumnElement)
-
compile(bind=None, dialect=None, **kw)¶ - inherited from the
compile()method ofClauseElementCompile this SQL expression.
The return value is a
Compiledobject. Callingstr()orunicode()on the returned value will yield a string representation of the result. TheCompiledobject also can return a dictionary of bind parameter names and values using theparamsaccessor.매개 변수: - bind¶ – An
EngineorConnectionfrom which aCompiledwill be acquired. This argument takes precedence over thisClauseElement‘s bound engine, if any. - column_keys¶ – Used for INSERT and UPDATE statements, a list of
column names which should be present in the VALUES clause of the
compiled statement. If
None, all columns from the target table object are rendered. - dialect¶ – A
Dialectinstance from which aCompiledwill be acquired. This argument takes precedence over the bind argument as well as thisClauseElement‘s bound engine, if any. - inline¶ – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
- compile_kwargs¶ –
optional dictionary of additional parameters that will be passed through to the compiler within all “visit” methods. This allows any custom flag to be passed through to a custom compilation construct, for example. It is also used for the case of passing the
literal_bindsflag through:from sqlalchemy.sql import table, column, select t = table('t', column('x')) s = select([t]).where(t.c.x == 5) print s.compile(compile_kwargs={"literal_binds": True})
버전 0.9.0에 추가.
- bind¶ – An
-
correspond_on_equivalents(column, equivalents)¶ - inherited from the
correspond_on_equivalents()method ofFromClauseReturn corresponding_column for the given column, or if None search for a match in the given dictionary.
-
corresponding_column(column, require_embedded=False)¶ - inherited from the
corresponding_column()method ofFromClauseGiven a
ColumnElement, return the exportedColumnElementobject from thisSelectablewhich corresponds to that originalColumnvia a common ancestor column.매개 변수: - column¶ – the target
ColumnElementto be matched - require_embedded¶ – only return corresponding columns for
the given
ColumnElement, if the givenColumnElementis actually present within a sub-element of thisFromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of thisFromClause.
- column¶ – the target
-
count(whereclause=None, **params)¶ - inherited from the
count()method ofFromClausereturn a SELECT COUNT generated against this
FromClause.
-
foreign_keys¶ - inherited from the
foreign_keysattribute ofFromClauseReturn the collection of ForeignKey objects which this FromClause references.
-
join(right, onclause=None, isouter=False, full=False)¶ - inherited from the
join()method ofFromClauseReturn a
Joinfrom thisFromClauseto anotherFromClause.E.g.:
from sqlalchemy import join j = user_table.join(address_table, user_table.c.id == address_table.c.user_id) stmt = select([user_table]).select_from(j)
would emit SQL along the lines of:
SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - isouter¶ – if True, render a LEFT OUTER JOIN, instead of JOIN.
- full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. Implies
FromClause.join.isouter.버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
lateral(name=None)¶ - inherited from the
lateral()method ofFromClauseReturn a LATERAL alias of this
FromClause.The return value is the
Lateralconstruct also provided by the top-levellateral()function.버전 1.1에 추가.
더 보기
LATERAL correlation - overview of usage.
-
outerjoin(right, onclause=None, full=False)¶ - inherited from the
outerjoin()method ofFromClauseReturn a
Joinfrom thisFromClauseto anotherFromClause, with the “isouter” flag set to True.E.g.:
from sqlalchemy import outerjoin j = user_table.outerjoin(address_table, user_table.c.id == address_table.c.user_id)
The above is equivalent to:
j = user_table.join( address_table, user_table.c.id == address_table.c.user_id, isouter=True)
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN.
버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
params(*optionaldict, **kwargs)¶ - inherited from the
params()method ofClauseElementReturn a copy with
bindparam()elements replaced.Returns a copy of this ClauseElement with
bindparam()elements replaced with values taken from the given dictionary:>>> clause = column('x') + bindparam('foo') >>> print clause.compile().params {'foo':None} >>> print clause.params({'foo':7}).compile().params {'foo':7}
-
primary_key¶ - inherited from the
primary_keyattribute ofFromClauseReturn the collection of Column objects which comprise the primary key of this FromClause.
-
replace_selectable(old, alias)¶ - inherited from the
replace_selectable()method ofFromClausereplace all occurrences of FromClause ‘old’ with the given Alias object, returning a copy of this
FromClause.
-
select(whereclause=None, **params)¶ - inherited from the
select()method ofFromClausereturn a SELECT of this
FromClause.더 보기
select()- general purpose method which allows for arbitrary column lists.
-
unique_params(*optionaldict, **kwargs)¶ - inherited from the
unique_params()method ofClauseElementReturn a copy with
bindparam()elements replaced.Same functionality as
params(), except adds unique=True to affected bind parameters so that multiple statements can be used.
-
-
class
sqlalchemy.sql.expression.CompoundSelect(keyword, *selects, **kwargs)¶ Bases:
sqlalchemy.sql.expression.GenerativeSelect- Forms the basis of
UNION,UNION ALL, and other - SELECT-based set operations.
-
alias(name=None, flat=False)¶ - inherited from the
alias()method ofFromClausereturn an alias of this
FromClause.This is shorthand for calling:
from sqlalchemy import alias a = alias(self, name=name)
See
alias()for details.
-
append_group_by(*clauses)¶ - inherited from the
append_group_by()method ofGenerativeSelectAppend the given GROUP BY criterion applied to this selectable.
The criterion will be appended to any pre-existing GROUP BY criterion.
This is an in-place mutation method; the
group_by()method is preferred, as it provides standard method chaining.
-
append_order_by(*clauses)¶ - inherited from the
append_order_by()method ofGenerativeSelectAppend the given ORDER BY criterion applied to this selectable.
The criterion will be appended to any pre-existing ORDER BY criterion.
This is an in-place mutation method; the
order_by()method is preferred, as it provides standard method chaining.
-
apply_labels()¶ - inherited from the
apply_labels()method ofGenerativeSelectreturn a new selectable with the ‘use_labels’ flag set to True.
This will result in column expressions being generated using labels against their table name, such as “SELECT somecolumn AS tablename_somecolumn”. This allows selectables which contain multiple FROM clauses to produce a unique set of column names regardless of name conflicts among the individual FROM clauses.
-
as_scalar()¶ - inherited from the
as_scalar()method ofSelectBasereturn a ‘scalar’ representation of this selectable, which can be used as a column expression.
Typically, a select statement which has only one column in its columns clause is eligible to be used as a scalar expression.
The returned object is an instance of
ScalarSelect.
-
autocommit()¶ - inherited from the
autocommit()method ofSelectBasereturn a new selectable with the ‘autocommit’ flag set to True.
버전 0.6 폐지:
autocommit()is deprecated. UseExecutable.execution_options()with the ‘autocommit’ flag.
-
c¶ - inherited from the
cattribute ofFromClauseAn alias for the
columnsattribute.
-
columns¶ - inherited from the
columnsattribute ofFromClauseA named-based collection of
ColumnElementobjects maintained by thisFromClause.The
columns, orccollection, is the gateway to the construction of SQL expressions using table-bound or other selectable-bound columns:select([mytable]).where(mytable.c.somecolumn == 5)
-
compare(other, **kw)¶ - inherited from the
compare()method ofClauseElementCompare this ClauseElement to the given ClauseElement.
Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass compare() methods and may be used to modify the criteria for comparison. (see
ColumnElement)
-
compile(bind=None, dialect=None, **kw)¶ - inherited from the
compile()method ofClauseElementCompile this SQL expression.
The return value is a
Compiledobject. Callingstr()orunicode()on the returned value will yield a string representation of the result. TheCompiledobject also can return a dictionary of bind parameter names and values using theparamsaccessor.매개 변수: - bind¶ – An
EngineorConnectionfrom which aCompiledwill be acquired. This argument takes precedence over thisClauseElement‘s bound engine, if any. - column_keys¶ – Used for INSERT and UPDATE statements, a list of
column names which should be present in the VALUES clause of the
compiled statement. If
None, all columns from the target table object are rendered. - dialect¶ – A
Dialectinstance from which aCompiledwill be acquired. This argument takes precedence over the bind argument as well as thisClauseElement‘s bound engine, if any. - inline¶ – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
- compile_kwargs¶ –
optional dictionary of additional parameters that will be passed through to the compiler within all “visit” methods. This allows any custom flag to be passed through to a custom compilation construct, for example. It is also used for the case of passing the
literal_bindsflag through:from sqlalchemy.sql import table, column, select t = table('t', column('x')) s = select([t]).where(t.c.x == 5) print s.compile(compile_kwargs={"literal_binds": True})
버전 0.9.0에 추가.
- bind¶ – An
-
correspond_on_equivalents(column, equivalents)¶ - inherited from the
correspond_on_equivalents()method ofFromClauseReturn corresponding_column for the given column, or if None search for a match in the given dictionary.
-
corresponding_column(column, require_embedded=False)¶ - inherited from the
corresponding_column()method ofFromClauseGiven a
ColumnElement, return the exportedColumnElementobject from thisSelectablewhich corresponds to that originalColumnvia a common ancestor column.매개 변수: - column¶ – the target
ColumnElementto be matched - require_embedded¶ – only return corresponding columns for
the given
ColumnElement, if the givenColumnElementis actually present within a sub-element of thisFromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of thisFromClause.
- column¶ – the target
-
count(whereclause=None, **params)¶ - inherited from the
count()method ofFromClausereturn a SELECT COUNT generated against this
FromClause.
-
cte(name=None, recursive=False)¶ -
Return a new
CTE, or Common Table Expression instance.Common table expressions are a SQL standard whereby SELECT statements can draw upon secondary statements specified along with the primary statement, using a clause called “WITH”. Special semantics regarding UNION can also be employed to allow “recursive” queries, where a SELECT statement can draw upon the set of rows that have previously been selected.
CTEs can also be applied to DML constructs UPDATE, INSERT and DELETE on some databases, both as a source of CTE rows when combined with RETURNING, as well as a consumer of CTE rows.
SQLAlchemy detects
CTEobjects, which are treated similarly toAliasobjects, as special elements to be delivered to the FROM clause of the statement as well as to a WITH clause at the top of the statement.버전 1.1으로 변경: Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE.
매개 변수: - name¶ – name given to the common table expression. Like
_FromClause.alias(), the name can be left asNonein which case an anonymous symbol will be used at query compile time. - recursive¶ – if
True, will renderWITH RECURSIVE. A recursive common table expression is intended to be used in conjunction with UNION ALL in order to derive rows from those already selected.
The following examples include two from Postgresql’s documentation at http://www.postgresql.org/docs/current/static/queries-with.html, as well as additional examples.
Example 1, non recursive:
from sqlalchemy import (Table, Column, String, Integer, MetaData, select, func) metadata = MetaData() orders = Table('orders', metadata, Column('region', String), Column('amount', Integer), Column('product', String), Column('quantity', Integer) ) regional_sales = select([ orders.c.region, func.sum(orders.c.amount).label('total_sales') ]).group_by(orders.c.region).cte("regional_sales") top_regions = select([regional_sales.c.region]).\ where( regional_sales.c.total_sales > select([ func.sum(regional_sales.c.total_sales)/10 ]) ).cte("top_regions") statement = select([ orders.c.region, orders.c.product, func.sum(orders.c.quantity).label("product_units"), func.sum(orders.c.amount).label("product_sales") ]).where(orders.c.region.in_( select([top_regions.c.region]) )).group_by(orders.c.region, orders.c.product) result = conn.execute(statement).fetchall()
Example 2, WITH RECURSIVE:
from sqlalchemy import (Table, Column, String, Integer, MetaData, select, func) metadata = MetaData() parts = Table('parts', metadata, Column('part', String), Column('sub_part', String), Column('quantity', Integer), ) included_parts = select([ parts.c.sub_part, parts.c.part, parts.c.quantity]).\ where(parts.c.part=='our part').\ cte(recursive=True) incl_alias = included_parts.alias() parts_alias = parts.alias() included_parts = included_parts.union_all( select([ parts_alias.c.sub_part, parts_alias.c.part, parts_alias.c.quantity ]). where(parts_alias.c.part==incl_alias.c.sub_part) ) statement = select([ included_parts.c.sub_part, func.sum(included_parts.c.quantity). label('total_quantity') ]).\ group_by(included_parts.c.sub_part) result = conn.execute(statement).fetchall()
Example 3, an upsert using UPDATE and INSERT with CTEs:
orders = table( 'orders', column('region'), column('amount'), column('product'), column('quantity') ) upsert = ( orders.update() .where(orders.c.region == 'Region1') .values(amount=1.0, product='Product1', quantity=1) .returning(*(orders.c._all_columns)).cte('upsert')) insert = orders.insert().from_select( orders.c.keys(), select([ literal('Region1'), literal(1.0), literal('Product1'), literal(1) ).where(exists(upsert.select())) ) connection.execute(insert)더 보기
orm.query.Query.cte()- ORM version ofHasCTE.cte(). - name¶ – name given to the common table expression. Like
-
description¶ - inherited from the
descriptionattribute ofFromClausea brief description of this FromClause.
Used primarily for error message formatting.
-
execute(*multiparams, **params)¶ - inherited from the
execute()method ofExecutableCompile and execute this
Executable.
-
execution_options(**kw)¶ - inherited from the
execution_options()method ofExecutableSet non-SQL options for the statement which take effect during execution.
Execution options can be set on a per-statement or per
Connectionbasis. Additionally, theEngineand ORMQueryobjects provide access to execution options which they in turn configure upon connections.The
execution_options()method is generative. A new instance of this statement is returned that contains the options:statement = select([table.c.x, table.c.y]) statement = statement.execution_options(autocommit=True)
Note that only a subset of possible execution options can be applied to a statement - these include “autocommit” and “stream_results”, but not “isolation_level” or “compiled_cache”. See
Connection.execution_options()for a full list of possible options.
-
for_update¶ - inherited from the
for_updateattribute ofGenerativeSelectProvide legacy dialect support for the
for_updateattribute.
-
foreign_keys¶ - inherited from the
foreign_keysattribute ofFromClauseReturn the collection of ForeignKey objects which this FromClause references.
-
group_by(*clauses)¶ - inherited from the
group_by()method ofGenerativeSelectreturn a new selectable with the given list of GROUP BY criterion applied.
The criterion will be appended to any pre-existing GROUP BY criterion.
-
join(right, onclause=None, isouter=False, full=False)¶ - inherited from the
join()method ofFromClauseReturn a
Joinfrom thisFromClauseto anotherFromClause.E.g.:
from sqlalchemy import join j = user_table.join(address_table, user_table.c.id == address_table.c.user_id) stmt = select([user_table]).select_from(j)
would emit SQL along the lines of:
SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - isouter¶ – if True, render a LEFT OUTER JOIN, instead of JOIN.
- full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. Implies
FromClause.join.isouter.버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
label(name)¶ - inherited from the
label()method ofSelectBasereturn a ‘scalar’ representation of this selectable, embedded as a subquery with a label.
더 보기
-
lateral(name=None)¶ - inherited from the
lateral()method ofFromClauseReturn a LATERAL alias of this
FromClause.The return value is the
Lateralconstruct also provided by the top-levellateral()function.버전 1.1에 추가.
더 보기
LATERAL correlation - overview of usage.
-
limit(limit)¶ - inherited from the
limit()method ofGenerativeSelectreturn a new selectable with the given LIMIT criterion applied.
This is a numerical value which usually renders as a
LIMITexpression in the resulting select. Backends that don’t supportLIMITwill attempt to provide similar functionality.버전 1.0.0으로 변경: -
Select.limit()can now accept arbitrary SQL expressions as well as integer values.매개 변수: limit¶ – an integer LIMIT parameter, or a SQL expression that provides an integer result.
-
offset(offset)¶ - inherited from the
offset()method ofGenerativeSelectreturn a new selectable with the given OFFSET criterion applied.
This is a numeric value which usually renders as an
OFFSETexpression in the resulting select. Backends that don’t supportOFFSETwill attempt to provide similar functionality.버전 1.0.0으로 변경: -
Select.offset()can now accept arbitrary SQL expressions as well as integer values.매개 변수: offset¶ – an integer OFFSET parameter, or a SQL expression that provides an integer result.
-
order_by(*clauses)¶ - inherited from the
order_by()method ofGenerativeSelectreturn a new selectable with the given list of ORDER BY criterion applied.
The criterion will be appended to any pre-existing ORDER BY criterion.
-
outerjoin(right, onclause=None, full=False)¶ - inherited from the
outerjoin()method ofFromClauseReturn a
Joinfrom thisFromClauseto anotherFromClause, with the “isouter” flag set to True.E.g.:
from sqlalchemy import outerjoin j = user_table.outerjoin(address_table, user_table.c.id == address_table.c.user_id)
The above is equivalent to:
j = user_table.join( address_table, user_table.c.id == address_table.c.user_id, isouter=True)
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN.
버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
params(*optionaldict, **kwargs)¶ - inherited from the
params()method ofClauseElementReturn a copy with
bindparam()elements replaced.Returns a copy of this ClauseElement with
bindparam()elements replaced with values taken from the given dictionary:>>> clause = column('x') + bindparam('foo') >>> print clause.compile().params {'foo':None} >>> print clause.params({'foo':7}).compile().params {'foo':7}
-
primary_key¶ - inherited from the
primary_keyattribute ofFromClauseReturn the collection of Column objects which comprise the primary key of this FromClause.
-
replace_selectable(old, alias)¶ - inherited from the
replace_selectable()method ofFromClausereplace all occurrences of FromClause ‘old’ with the given Alias object, returning a copy of this
FromClause.
-
scalar(*multiparams, **params)¶ - inherited from the
scalar()method ofExecutableCompile and execute this
Executable, returning the result’s scalar representation.
-
select(whereclause=None, **params)¶ - inherited from the
select()method ofFromClausereturn a SELECT of this
FromClause.더 보기
select()- general purpose method which allows for arbitrary column lists.
-
unique_params(*optionaldict, **kwargs)¶ - inherited from the
unique_params()method ofClauseElementReturn a copy with
bindparam()elements replaced.Same functionality as
params(), except adds unique=True to affected bind parameters so that multiple statements can be used.
-
with_for_update(nowait=False, read=False, of=None)¶ - inherited from the
with_for_update()method ofGenerativeSelectSpecify a
FOR UPDATEclause for thisGenerativeSelect.E.g.:
stmt = select([table]).with_for_update(nowait=True)
On a database like Postgresql or Oracle, the above would render a statement like:
SELECT table.a, table.b FROM table FOR UPDATE NOWAIT
on other backends, the
nowaitoption is ignored and instead would produce:SELECT table.a, table.b FROM table FOR UPDATE
When called with no arguments, the statement will render with the suffix
FOR UPDATE. Additional arguments can then be provided which allow for common database-specific variants.매개 변수: - nowait¶ – boolean; will render
FOR UPDATE NOWAITon Oracle and Postgresql dialects. - read¶ – boolean; will render
LOCK IN SHARE MODEon MySQL,FOR SHAREon Postgresql. On Postgresql, when combined withnowait, will renderFOR SHARE NOWAIT. - of¶ – SQL expression or list of SQL expression elements
(typically
Columnobjects or a compatible expression) which will render into aFOR UPDATE OFclause; supported by PostgreSQL and Oracle. May render as a table or as a column depending on backend.
버전 0.9.0에 추가.
- nowait¶ – boolean; will render
- Forms the basis of
-
class
sqlalchemy.sql.expression.CTE(selectable, name=None, recursive=False, _cte_alias=None, _restates=frozenset([]), _suffixes=None)¶ Bases:
sqlalchemy.sql.expression.Generative,sqlalchemy.sql.expression.HasSuffixes,sqlalchemy.sql.expression.AliasRepresent a Common Table Expression.
The
CTEobject is obtained using theSelectBase.cte()method from any selectable. See that method for complete examples.버전 0.7.6에 추가.
-
c¶ - inherited from the
cattribute ofFromClauseAn alias for the
columnsattribute.
-
columns¶ - inherited from the
columnsattribute ofFromClauseA named-based collection of
ColumnElementobjects maintained by thisFromClause.The
columns, orccollection, is the gateway to the construction of SQL expressions using table-bound or other selectable-bound columns:select([mytable]).where(mytable.c.somecolumn == 5)
-
compare(other, **kw)¶ - inherited from the
compare()method ofClauseElementCompare this ClauseElement to the given ClauseElement.
Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass compare() methods and may be used to modify the criteria for comparison. (see
ColumnElement)
-
compile(bind=None, dialect=None, **kw)¶ - inherited from the
compile()method ofClauseElementCompile this SQL expression.
The return value is a
Compiledobject. Callingstr()orunicode()on the returned value will yield a string representation of the result. TheCompiledobject also can return a dictionary of bind parameter names and values using theparamsaccessor.매개 변수: - bind¶ – An
EngineorConnectionfrom which aCompiledwill be acquired. This argument takes precedence over thisClauseElement‘s bound engine, if any. - column_keys¶ – Used for INSERT and UPDATE statements, a list of
column names which should be present in the VALUES clause of the
compiled statement. If
None, all columns from the target table object are rendered. - dialect¶ – A
Dialectinstance from which aCompiledwill be acquired. This argument takes precedence over the bind argument as well as thisClauseElement‘s bound engine, if any. - inline¶ – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
- compile_kwargs¶ –
optional dictionary of additional parameters that will be passed through to the compiler within all “visit” methods. This allows any custom flag to be passed through to a custom compilation construct, for example. It is also used for the case of passing the
literal_bindsflag through:from sqlalchemy.sql import table, column, select t = table('t', column('x')) s = select([t]).where(t.c.x == 5) print s.compile(compile_kwargs={"literal_binds": True})
버전 0.9.0에 추가.
- bind¶ – An
-
correspond_on_equivalents(column, equivalents)¶ - inherited from the
correspond_on_equivalents()method ofFromClauseReturn corresponding_column for the given column, or if None search for a match in the given dictionary.
-
corresponding_column(column, require_embedded=False)¶ - inherited from the
corresponding_column()method ofFromClauseGiven a
ColumnElement, return the exportedColumnElementobject from thisSelectablewhich corresponds to that originalColumnvia a common ancestor column.매개 변수: - column¶ – the target
ColumnElementto be matched - require_embedded¶ – only return corresponding columns for
the given
ColumnElement, if the givenColumnElementis actually present within a sub-element of thisFromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of thisFromClause.
- column¶ – the target
-
count(whereclause=None, **params)¶ - inherited from the
count()method ofFromClausereturn a SELECT COUNT generated against this
FromClause.
-
foreign_keys¶ - inherited from the
foreign_keysattribute ofFromClauseReturn the collection of ForeignKey objects which this FromClause references.
-
join(right, onclause=None, isouter=False, full=False)¶ - inherited from the
join()method ofFromClauseReturn a
Joinfrom thisFromClauseto anotherFromClause.E.g.:
from sqlalchemy import join j = user_table.join(address_table, user_table.c.id == address_table.c.user_id) stmt = select([user_table]).select_from(j)
would emit SQL along the lines of:
SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - isouter¶ – if True, render a LEFT OUTER JOIN, instead of JOIN.
- full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. Implies
FromClause.join.isouter.버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
lateral(name=None)¶ - inherited from the
lateral()method ofFromClauseReturn a LATERAL alias of this
FromClause.The return value is the
Lateralconstruct also provided by the top-levellateral()function.버전 1.1에 추가.
더 보기
LATERAL correlation - overview of usage.
-
outerjoin(right, onclause=None, full=False)¶ - inherited from the
outerjoin()method ofFromClauseReturn a
Joinfrom thisFromClauseto anotherFromClause, with the “isouter” flag set to True.E.g.:
from sqlalchemy import outerjoin j = user_table.outerjoin(address_table, user_table.c.id == address_table.c.user_id)
The above is equivalent to:
j = user_table.join( address_table, user_table.c.id == address_table.c.user_id, isouter=True)
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN.
버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
params(*optionaldict, **kwargs)¶ - inherited from the
params()method ofClauseElementReturn a copy with
bindparam()elements replaced.Returns a copy of this ClauseElement with
bindparam()elements replaced with values taken from the given dictionary:>>> clause = column('x') + bindparam('foo') >>> print clause.compile().params {'foo':None} >>> print clause.params({'foo':7}).compile().params {'foo':7}
-
primary_key¶ - inherited from the
primary_keyattribute ofFromClauseReturn the collection of Column objects which comprise the primary key of this FromClause.
-
replace_selectable(old, alias)¶ - inherited from the
replace_selectable()method ofFromClausereplace all occurrences of FromClause ‘old’ with the given Alias object, returning a copy of this
FromClause.
-
select(whereclause=None, **params)¶ - inherited from the
select()method ofFromClausereturn a SELECT of this
FromClause.더 보기
select()- general purpose method which allows for arbitrary column lists.
-
suffix_with(*expr, **kw)¶ - inherited from the
suffix_with()method ofHasSuffixesAdd one or more expressions following the statement as a whole.
This is used to support backend-specific suffix keywords on certain constructs.
E.g.:
stmt = select([col1, col2]).cte().suffix_with( "cycle empno set y_cycle to 1 default 0", dialect="oracle")
Multiple suffixes can be specified by multiple calls to
suffix_with().매개 변수: - *expr¶ – textual or
ClauseElementconstruct which will be rendered following the target clause. - **kw¶ – A single keyword ‘dialect’ is accepted. This is an optional string dialect name which will limit rendering of this suffix to only that dialect.
- *expr¶ – textual or
-
unique_params(*optionaldict, **kwargs)¶ - inherited from the
unique_params()method ofClauseElementReturn a copy with
bindparam()elements replaced.Same functionality as
params(), except adds unique=True to affected bind parameters so that multiple statements can be used.
-
-
class
sqlalchemy.sql.expression.Executable¶ Bases:
sqlalchemy.sql.expression.GenerativeMark a ClauseElement as supporting execution.
Executableis a superclass for all “statement” types of objects, includingselect(),delete(),update(),insert(),text().-
bind¶ Returns the
EngineorConnectionto which thisExecutableis bound, or None if none found.This is a traversal which checks locally, then checks among the “from” clauses of associated objects until a bound engine or connection is found.
-
execute(*multiparams, **params)¶ Compile and execute this
Executable.
-
execution_options(**kw)¶ Set non-SQL options for the statement which take effect during execution.
Execution options can be set on a per-statement or per
Connectionbasis. Additionally, theEngineand ORMQueryobjects provide access to execution options which they in turn configure upon connections.The
execution_options()method is generative. A new instance of this statement is returned that contains the options:statement = select([table.c.x, table.c.y]) statement = statement.execution_options(autocommit=True)
Note that only a subset of possible execution options can be applied to a statement - these include “autocommit” and “stream_results”, but not “isolation_level” or “compiled_cache”. See
Connection.execution_options()for a full list of possible options.
-
scalar(*multiparams, **params)¶ Compile and execute this
Executable, returning the result’s scalar representation.
-
-
class
sqlalchemy.sql.expression.FromClause¶ Bases:
sqlalchemy.sql.expression.SelectableRepresent an element that can be used within the
FROMclause of aSELECTstatement.The most common forms of
FromClauseare theTableand theselect()constructs. Key features common to allFromClauseobjects include:- a
ccollection, which provides per-name access to a collection ofColumnElementobjects. - a
primary_keyattribute, which is a collection of all thoseColumnElementobjects that indicate theprimary_keyflag. - Methods to generate various derivations of a “from” clause, including
FromClause.alias(),FromClause.join(),FromClause.select().
-
alias(name=None, flat=False)¶ return an alias of this
FromClause.This is shorthand for calling:
from sqlalchemy import alias a = alias(self, name=name)
See
alias()for details.
-
columns¶ A named-based collection of
ColumnElementobjects maintained by thisFromClause.The
columns, orccollection, is the gateway to the construction of SQL expressions using table-bound or other selectable-bound columns:select([mytable]).where(mytable.c.somecolumn == 5)
-
correspond_on_equivalents(column, equivalents)¶ Return corresponding_column for the given column, or if None search for a match in the given dictionary.
-
corresponding_column(column, require_embedded=False)¶ Given a
ColumnElement, return the exportedColumnElementobject from thisSelectablewhich corresponds to that originalColumnvia a common ancestor column.매개 변수: - column¶ – the target
ColumnElementto be matched - require_embedded¶ – only return corresponding columns for
the given
ColumnElement, if the givenColumnElementis actually present within a sub-element of thisFromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of thisFromClause.
- column¶ – the target
-
count(whereclause=None, **params)¶ return a SELECT COUNT generated against this
FromClause.
-
description¶ a brief description of this FromClause.
Used primarily for error message formatting.
-
foreign_keys¶ Return the collection of ForeignKey objects which this FromClause references.
-
is_derived_from(fromclause)¶ Return True if this FromClause is ‘derived’ from the given FromClause.
An example would be an Alias of a Table is derived from that Table.
-
join(right, onclause=None, isouter=False, full=False)¶ Return a
Joinfrom thisFromClauseto anotherFromClause.E.g.:
from sqlalchemy import join j = user_table.join(address_table, user_table.c.id == address_table.c.user_id) stmt = select([user_table]).select_from(j)
would emit SQL along the lines of:
SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - isouter¶ – if True, render a LEFT OUTER JOIN, instead of JOIN.
- full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. Implies
FromClause.join.isouter.버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
lateral(name=None)¶ Return a LATERAL alias of this
FromClause.The return value is the
Lateralconstruct also provided by the top-levellateral()function.버전 1.1에 추가.
더 보기
LATERAL correlation - overview of usage.
-
outerjoin(right, onclause=None, full=False)¶ Return a
Joinfrom thisFromClauseto anotherFromClause, with the “isouter” flag set to True.E.g.:
from sqlalchemy import outerjoin j = user_table.outerjoin(address_table, user_table.c.id == address_table.c.user_id)
The above is equivalent to:
j = user_table.join( address_table, user_table.c.id == address_table.c.user_id, isouter=True)
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN.
버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
primary_key¶ Return the collection of Column objects which comprise the primary key of this FromClause.
-
replace_selectable(old, alias)¶ replace all occurrences of FromClause ‘old’ with the given Alias object, returning a copy of this
FromClause.
-
schema= None¶ Define the ‘schema’ attribute for this
FromClause.This is typically
Nonefor most objects except that ofTable, where it is taken as the value of theTable.schemaargument.
-
select(whereclause=None, **params)¶ return a SELECT of this
FromClause.더 보기
select()- general purpose method which allows for arbitrary column lists.
- a
-
class
sqlalchemy.sql.expression.GenerativeSelect(use_labels=False, for_update=False, limit=None, offset=None, order_by=None, group_by=None, bind=None, autocommit=None)¶ Bases:
sqlalchemy.sql.expression.SelectBaseBase class for SELECT statements where additional elements can be added.
This serves as the base for
SelectandCompoundSelectwhere elements such as ORDER BY, GROUP BY can be added and column rendering can be controlled. Compare toTextAsFrom, which, while it subclassesSelectBaseand is also a SELECT construct, represents a fixed textual string which cannot be altered at this level, only wrapped as a subquery.버전 0.9.0에 추가:
GenerativeSelectwas added to provide functionality specific toSelectandCompoundSelectwhile allowingSelectBaseto be used for other SELECT-like objects, e.g.TextAsFrom.-
alias(name=None, flat=False)¶ - inherited from the
alias()method ofFromClausereturn an alias of this
FromClause.This is shorthand for calling:
from sqlalchemy import alias a = alias(self, name=name)
See
alias()for details.
-
append_group_by(*clauses)¶ Append the given GROUP BY criterion applied to this selectable.
The criterion will be appended to any pre-existing GROUP BY criterion.
This is an in-place mutation method; the
group_by()method is preferred, as it provides standard method chaining.
-
append_order_by(*clauses)¶ Append the given ORDER BY criterion applied to this selectable.
The criterion will be appended to any pre-existing ORDER BY criterion.
This is an in-place mutation method; the
order_by()method is preferred, as it provides standard method chaining.
-
apply_labels()¶ return a new selectable with the ‘use_labels’ flag set to True.
This will result in column expressions being generated using labels against their table name, such as “SELECT somecolumn AS tablename_somecolumn”. This allows selectables which contain multiple FROM clauses to produce a unique set of column names regardless of name conflicts among the individual FROM clauses.
-
as_scalar()¶ - inherited from the
as_scalar()method ofSelectBasereturn a ‘scalar’ representation of this selectable, which can be used as a column expression.
Typically, a select statement which has only one column in its columns clause is eligible to be used as a scalar expression.
The returned object is an instance of
ScalarSelect.
-
autocommit()¶ - inherited from the
autocommit()method ofSelectBasereturn a new selectable with the ‘autocommit’ flag set to True.
버전 0.6 폐지:
autocommit()is deprecated. UseExecutable.execution_options()with the ‘autocommit’ flag.
-
bind¶ - inherited from the
bindattribute ofExecutableReturns the
EngineorConnectionto which thisExecutableis bound, or None if none found.This is a traversal which checks locally, then checks among the “from” clauses of associated objects until a bound engine or connection is found.
-
c¶ - inherited from the
cattribute ofFromClauseAn alias for the
columnsattribute.
-
columns¶ - inherited from the
columnsattribute ofFromClauseA named-based collection of
ColumnElementobjects maintained by thisFromClause.The
columns, orccollection, is the gateway to the construction of SQL expressions using table-bound or other selectable-bound columns:select([mytable]).where(mytable.c.somecolumn == 5)
-
compare(other, **kw)¶ - inherited from the
compare()method ofClauseElementCompare this ClauseElement to the given ClauseElement.
Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass compare() methods and may be used to modify the criteria for comparison. (see
ColumnElement)
-
compile(bind=None, dialect=None, **kw)¶ - inherited from the
compile()method ofClauseElementCompile this SQL expression.
The return value is a
Compiledobject. Callingstr()orunicode()on the returned value will yield a string representation of the result. TheCompiledobject also can return a dictionary of bind parameter names and values using theparamsaccessor.매개 변수: - bind¶ – An
EngineorConnectionfrom which aCompiledwill be acquired. This argument takes precedence over thisClauseElement‘s bound engine, if any. - column_keys¶ – Used for INSERT and UPDATE statements, a list of
column names which should be present in the VALUES clause of the
compiled statement. If
None, all columns from the target table object are rendered. - dialect¶ – A
Dialectinstance from which aCompiledwill be acquired. This argument takes precedence over the bind argument as well as thisClauseElement‘s bound engine, if any. - inline¶ – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
- compile_kwargs¶ –
optional dictionary of additional parameters that will be passed through to the compiler within all “visit” methods. This allows any custom flag to be passed through to a custom compilation construct, for example. It is also used for the case of passing the
literal_bindsflag through:from sqlalchemy.sql import table, column, select t = table('t', column('x')) s = select([t]).where(t.c.x == 5) print s.compile(compile_kwargs={"literal_binds": True})
버전 0.9.0에 추가.
- bind¶ – An
-
correspond_on_equivalents(column, equivalents)¶ - inherited from the
correspond_on_equivalents()method ofFromClauseReturn corresponding_column for the given column, or if None search for a match in the given dictionary.
-
corresponding_column(column, require_embedded=False)¶ - inherited from the
corresponding_column()method ofFromClauseGiven a
ColumnElement, return the exportedColumnElementobject from thisSelectablewhich corresponds to that originalColumnvia a common ancestor column.매개 변수: - column¶ – the target
ColumnElementto be matched - require_embedded¶ – only return corresponding columns for
the given
ColumnElement, if the givenColumnElementis actually present within a sub-element of thisFromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of thisFromClause.
- column¶ – the target
-
count(whereclause=None, **params)¶ - inherited from the
count()method ofFromClausereturn a SELECT COUNT generated against this
FromClause.
-
cte(name=None, recursive=False)¶ -
Return a new
CTE, or Common Table Expression instance.Common table expressions are a SQL standard whereby SELECT statements can draw upon secondary statements specified along with the primary statement, using a clause called “WITH”. Special semantics regarding UNION can also be employed to allow “recursive” queries, where a SELECT statement can draw upon the set of rows that have previously been selected.
CTEs can also be applied to DML constructs UPDATE, INSERT and DELETE on some databases, both as a source of CTE rows when combined with RETURNING, as well as a consumer of CTE rows.
SQLAlchemy detects
CTEobjects, which are treated similarly toAliasobjects, as special elements to be delivered to the FROM clause of the statement as well as to a WITH clause at the top of the statement.버전 1.1으로 변경: Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE.
매개 변수: - name¶ – name given to the common table expression. Like
_FromClause.alias(), the name can be left asNonein which case an anonymous symbol will be used at query compile time. - recursive¶ – if
True, will renderWITH RECURSIVE. A recursive common table expression is intended to be used in conjunction with UNION ALL in order to derive rows from those already selected.
The following examples include two from Postgresql’s documentation at http://www.postgresql.org/docs/current/static/queries-with.html, as well as additional examples.
Example 1, non recursive:
from sqlalchemy import (Table, Column, String, Integer, MetaData, select, func) metadata = MetaData() orders = Table('orders', metadata, Column('region', String), Column('amount', Integer), Column('product', String), Column('quantity', Integer) ) regional_sales = select([ orders.c.region, func.sum(orders.c.amount).label('total_sales') ]).group_by(orders.c.region).cte("regional_sales") top_regions = select([regional_sales.c.region]).\ where( regional_sales.c.total_sales > select([ func.sum(regional_sales.c.total_sales)/10 ]) ).cte("top_regions") statement = select([ orders.c.region, orders.c.product, func.sum(orders.c.quantity).label("product_units"), func.sum(orders.c.amount).label("product_sales") ]).where(orders.c.region.in_( select([top_regions.c.region]) )).group_by(orders.c.region, orders.c.product) result = conn.execute(statement).fetchall()
Example 2, WITH RECURSIVE:
from sqlalchemy import (Table, Column, String, Integer, MetaData, select, func) metadata = MetaData() parts = Table('parts', metadata, Column('part', String), Column('sub_part', String), Column('quantity', Integer), ) included_parts = select([ parts.c.sub_part, parts.c.part, parts.c.quantity]).\ where(parts.c.part=='our part').\ cte(recursive=True) incl_alias = included_parts.alias() parts_alias = parts.alias() included_parts = included_parts.union_all( select([ parts_alias.c.sub_part, parts_alias.c.part, parts_alias.c.quantity ]). where(parts_alias.c.part==incl_alias.c.sub_part) ) statement = select([ included_parts.c.sub_part, func.sum(included_parts.c.quantity). label('total_quantity') ]).\ group_by(included_parts.c.sub_part) result = conn.execute(statement).fetchall()
Example 3, an upsert using UPDATE and INSERT with CTEs:
orders = table( 'orders', column('region'), column('amount'), column('product'), column('quantity') ) upsert = ( orders.update() .where(orders.c.region == 'Region1') .values(amount=1.0, product='Product1', quantity=1) .returning(*(orders.c._all_columns)).cte('upsert')) insert = orders.insert().from_select( orders.c.keys(), select([ literal('Region1'), literal(1.0), literal('Product1'), literal(1) ).where(exists(upsert.select())) ) connection.execute(insert)더 보기
orm.query.Query.cte()- ORM version ofHasCTE.cte(). - name¶ – name given to the common table expression. Like
-
description¶ - inherited from the
descriptionattribute ofFromClausea brief description of this FromClause.
Used primarily for error message formatting.
-
execute(*multiparams, **params)¶ - inherited from the
execute()method ofExecutableCompile and execute this
Executable.
-
execution_options(**kw)¶ - inherited from the
execution_options()method ofExecutableSet non-SQL options for the statement which take effect during execution.
Execution options can be set on a per-statement or per
Connectionbasis. Additionally, theEngineand ORMQueryobjects provide access to execution options which they in turn configure upon connections.The
execution_options()method is generative. A new instance of this statement is returned that contains the options:statement = select([table.c.x, table.c.y]) statement = statement.execution_options(autocommit=True)
Note that only a subset of possible execution options can be applied to a statement - these include “autocommit” and “stream_results”, but not “isolation_level” or “compiled_cache”. See
Connection.execution_options()for a full list of possible options.
-
for_update¶ Provide legacy dialect support for the
for_updateattribute.
-
foreign_keys¶ - inherited from the
foreign_keysattribute ofFromClauseReturn the collection of ForeignKey objects which this FromClause references.
-
get_children(**kwargs)¶ - inherited from the
get_children()method ofClauseElementReturn immediate child elements of this
ClauseElement.This is used for visit traversal.
**kwargs may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level).
-
group_by(*clauses)¶ return a new selectable with the given list of GROUP BY criterion applied.
The criterion will be appended to any pre-existing GROUP BY criterion.
-
is_derived_from(fromclause)¶ - inherited from the
is_derived_from()method ofFromClauseReturn True if this FromClause is ‘derived’ from the given FromClause.
An example would be an Alias of a Table is derived from that Table.
-
join(right, onclause=None, isouter=False, full=False)¶ - inherited from the
join()method ofFromClauseReturn a
Joinfrom thisFromClauseto anotherFromClause.E.g.:
from sqlalchemy import join j = user_table.join(address_table, user_table.c.id == address_table.c.user_id) stmt = select([user_table]).select_from(j)
would emit SQL along the lines of:
SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - isouter¶ – if True, render a LEFT OUTER JOIN, instead of JOIN.
- full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. Implies
FromClause.join.isouter.버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
label(name)¶ - inherited from the
label()method ofSelectBasereturn a ‘scalar’ representation of this selectable, embedded as a subquery with a label.
더 보기
-
lateral(name=None)¶ - inherited from the
lateral()method ofFromClauseReturn a LATERAL alias of this
FromClause.The return value is the
Lateralconstruct also provided by the top-levellateral()function.버전 1.1에 추가.
더 보기
LATERAL correlation - overview of usage.
-
limit(limit)¶ return a new selectable with the given LIMIT criterion applied.
This is a numerical value which usually renders as a
LIMITexpression in the resulting select. Backends that don’t supportLIMITwill attempt to provide similar functionality.버전 1.0.0으로 변경: -
Select.limit()can now accept arbitrary SQL expressions as well as integer values.매개 변수: limit¶ – an integer LIMIT parameter, or a SQL expression that provides an integer result.
-
offset(offset)¶ return a new selectable with the given OFFSET criterion applied.
This is a numeric value which usually renders as an
OFFSETexpression in the resulting select. Backends that don’t supportOFFSETwill attempt to provide similar functionality.버전 1.0.0으로 변경: -
Select.offset()can now accept arbitrary SQL expressions as well as integer values.매개 변수: offset¶ – an integer OFFSET parameter, or a SQL expression that provides an integer result.
-
order_by(*clauses)¶ return a new selectable with the given list of ORDER BY criterion applied.
The criterion will be appended to any pre-existing ORDER BY criterion.
-
outerjoin(right, onclause=None, full=False)¶ - inherited from the
outerjoin()method ofFromClauseReturn a
Joinfrom thisFromClauseto anotherFromClause, with the “isouter” flag set to True.E.g.:
from sqlalchemy import outerjoin j = user_table.outerjoin(address_table, user_table.c.id == address_table.c.user_id)
The above is equivalent to:
j = user_table.join( address_table, user_table.c.id == address_table.c.user_id, isouter=True)
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN.
버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
params(*optionaldict, **kwargs)¶ - inherited from the
params()method ofClauseElementReturn a copy with
bindparam()elements replaced.Returns a copy of this ClauseElement with
bindparam()elements replaced with values taken from the given dictionary:>>> clause = column('x') + bindparam('foo') >>> print clause.compile().params {'foo':None} >>> print clause.params({'foo':7}).compile().params {'foo':7}
-
primary_key¶ - inherited from the
primary_keyattribute ofFromClauseReturn the collection of Column objects which comprise the primary key of this FromClause.
-
replace_selectable(old, alias)¶ - inherited from the
replace_selectable()method ofFromClausereplace all occurrences of FromClause ‘old’ with the given Alias object, returning a copy of this
FromClause.
-
scalar(*multiparams, **params)¶ - inherited from the
scalar()method ofExecutableCompile and execute this
Executable, returning the result’s scalar representation.
-
select(whereclause=None, **params)¶ - inherited from the
select()method ofFromClausereturn a SELECT of this
FromClause.더 보기
select()- general purpose method which allows for arbitrary column lists.
-
self_group(against=None)¶ - inherited from the
self_group()method ofClauseElementApply a ‘grouping’ to this
ClauseElement.This method is overridden by subclasses to return a “grouping” construct, i.e. parenthesis. In particular it’s used by “binary” expressions to provide a grouping around themselves when placed into a larger expression, as well as by
select()constructs when placed into the FROM clause of anotherselect(). (Note that subqueries should be normally created using theSelect.alias()method, as many platforms require nested SELECT statements to be named).As expressions are composed together, the application of
self_group()is automatic - end-user code should never need to use this method directly. Note that SQLAlchemy’s clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression likex OR (y AND z)- AND takes precedence over OR.The base
self_group()method ofClauseElementjust returns self.
-
unique_params(*optionaldict, **kwargs)¶ - inherited from the
unique_params()method ofClauseElementReturn a copy with
bindparam()elements replaced.Same functionality as
params(), except adds unique=True to affected bind parameters so that multiple statements can be used.
-
with_for_update(nowait=False, read=False, of=None)¶ Specify a
FOR UPDATEclause for thisGenerativeSelect.E.g.:
stmt = select([table]).with_for_update(nowait=True)
On a database like Postgresql or Oracle, the above would render a statement like:
SELECT table.a, table.b FROM table FOR UPDATE NOWAIT
on other backends, the
nowaitoption is ignored and instead would produce:SELECT table.a, table.b FROM table FOR UPDATE
When called with no arguments, the statement will render with the suffix
FOR UPDATE. Additional arguments can then be provided which allow for common database-specific variants.매개 변수: - nowait¶ – boolean; will render
FOR UPDATE NOWAITon Oracle and Postgresql dialects. - read¶ – boolean; will render
LOCK IN SHARE MODEon MySQL,FOR SHAREon Postgresql. On Postgresql, when combined withnowait, will renderFOR SHARE NOWAIT. - of¶ – SQL expression or list of SQL expression elements
(typically
Columnobjects or a compatible expression) which will render into aFOR UPDATE OFclause; supported by PostgreSQL and Oracle. May render as a table or as a column depending on backend.
버전 0.9.0에 추가.
- nowait¶ – boolean; will render
-
-
class
sqlalchemy.sql.expression.HasCTE¶ Mixin that declares a class to include CTE support.
버전 1.1에 추가.
-
cte(name=None, recursive=False)¶ Return a new
CTE, or Common Table Expression instance.Common table expressions are a SQL standard whereby SELECT statements can draw upon secondary statements specified along with the primary statement, using a clause called “WITH”. Special semantics regarding UNION can also be employed to allow “recursive” queries, where a SELECT statement can draw upon the set of rows that have previously been selected.
CTEs can also be applied to DML constructs UPDATE, INSERT and DELETE on some databases, both as a source of CTE rows when combined with RETURNING, as well as a consumer of CTE rows.
SQLAlchemy detects
CTEobjects, which are treated similarly toAliasobjects, as special elements to be delivered to the FROM clause of the statement as well as to a WITH clause at the top of the statement.버전 1.1으로 변경: Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE.
매개 변수: - name¶ – name given to the common table expression. Like
_FromClause.alias(), the name can be left asNonein which case an anonymous symbol will be used at query compile time. - recursive¶ – if
True, will renderWITH RECURSIVE. A recursive common table expression is intended to be used in conjunction with UNION ALL in order to derive rows from those already selected.
The following examples include two from Postgresql’s documentation at http://www.postgresql.org/docs/current/static/queries-with.html, as well as additional examples.
Example 1, non recursive:
from sqlalchemy import (Table, Column, String, Integer, MetaData, select, func) metadata = MetaData() orders = Table('orders', metadata, Column('region', String), Column('amount', Integer), Column('product', String), Column('quantity', Integer) ) regional_sales = select([ orders.c.region, func.sum(orders.c.amount).label('total_sales') ]).group_by(orders.c.region).cte("regional_sales") top_regions = select([regional_sales.c.region]).\ where( regional_sales.c.total_sales > select([ func.sum(regional_sales.c.total_sales)/10 ]) ).cte("top_regions") statement = select([ orders.c.region, orders.c.product, func.sum(orders.c.quantity).label("product_units"), func.sum(orders.c.amount).label("product_sales") ]).where(orders.c.region.in_( select([top_regions.c.region]) )).group_by(orders.c.region, orders.c.product) result = conn.execute(statement).fetchall()
Example 2, WITH RECURSIVE:
from sqlalchemy import (Table, Column, String, Integer, MetaData, select, func) metadata = MetaData() parts = Table('parts', metadata, Column('part', String), Column('sub_part', String), Column('quantity', Integer), ) included_parts = select([ parts.c.sub_part, parts.c.part, parts.c.quantity]).\ where(parts.c.part=='our part').\ cte(recursive=True) incl_alias = included_parts.alias() parts_alias = parts.alias() included_parts = included_parts.union_all( select([ parts_alias.c.sub_part, parts_alias.c.part, parts_alias.c.quantity ]). where(parts_alias.c.part==incl_alias.c.sub_part) ) statement = select([ included_parts.c.sub_part, func.sum(included_parts.c.quantity). label('total_quantity') ]).\ group_by(included_parts.c.sub_part) result = conn.execute(statement).fetchall()
Example 3, an upsert using UPDATE and INSERT with CTEs:
orders = table( 'orders', column('region'), column('amount'), column('product'), column('quantity') ) upsert = ( orders.update() .where(orders.c.region == 'Region1') .values(amount=1.0, product='Product1', quantity=1) .returning(*(orders.c._all_columns)).cte('upsert')) insert = orders.insert().from_select( orders.c.keys(), select([ literal('Region1'), literal(1.0), literal('Product1'), literal(1) ).where(exists(upsert.select())) ) connection.execute(insert)더 보기
orm.query.Query.cte()- ORM version ofHasCTE.cte().- name¶ – name given to the common table expression. Like
-
-
class
sqlalchemy.sql.expression.HasPrefixes¶ -
prefix_with(*expr, **kw)¶ Add one or more expressions following the statement keyword, i.e. SELECT, INSERT, UPDATE, or DELETE. Generative.
This is used to support backend-specific prefix keywords such as those provided by MySQL.
E.g.:
stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")
Multiple prefixes can be specified by multiple calls to
prefix_with().매개 변수: - *expr¶ – textual or
ClauseElementconstruct which will be rendered following the INSERT, UPDATE, or DELETE keyword. - **kw¶ – A single keyword ‘dialect’ is accepted. This is an optional string dialect name which will limit rendering of this prefix to only that dialect.
- *expr¶ – textual or
-
-
class
sqlalchemy.sql.expression.HasSuffixes¶ -
suffix_with(*expr, **kw)¶ Add one or more expressions following the statement as a whole.
This is used to support backend-specific suffix keywords on certain constructs.
E.g.:
stmt = select([col1, col2]).cte().suffix_with( "cycle empno set y_cycle to 1 default 0", dialect="oracle")
Multiple suffixes can be specified by multiple calls to
suffix_with().매개 변수: - *expr¶ – textual or
ClauseElementconstruct which will be rendered following the target clause. - **kw¶ – A single keyword ‘dialect’ is accepted. This is an optional string dialect name which will limit rendering of this suffix to only that dialect.
- *expr¶ – textual or
-
-
class
sqlalchemy.sql.expression.Join(left, right, onclause=None, isouter=False, full=False)¶ Bases:
sqlalchemy.sql.expression.FromClauserepresent a
JOINconstruct between twoFromClauseelements.The public constructor function for
Joinis the module-leveljoin()function, as well as theFromClause.join()method of anyFromClause(e.g. such asTable).-
__init__(left, right, onclause=None, isouter=False, full=False)¶ Construct a new
Join.The usual entrypoint here is the
join()function or theFromClause.join()method of anyFromClauseobject.
-
alias(name=None, flat=False)¶ return an alias of this
Join.The default behavior here is to first produce a SELECT construct from this
Join, then to produce anAliasfrom that. So given a join of the form:j = table_a.join(table_b, table_a.c.id == table_b.c.a_id)
The JOIN by itself would look like:
table_a JOIN table_b ON table_a.id = table_b.a_id
Whereas the alias of the above,
j.alias(), would in a SELECT context look like:(SELECT table_a.id AS table_a_id, table_b.id AS table_b_id, table_b.a_id AS table_b_a_id FROM table_a JOIN table_b ON table_a.id = table_b.a_id) AS anon_1The equivalent long-hand form, given a
Joinobjectj, is:from sqlalchemy import select, alias j = alias( select([j.left, j.right]).\ select_from(j).\ with_labels(True).\ correlate(False), name=name )
The selectable produced by
Join.alias()features the same columns as that of the two individual selectables presented under a single name - the individual columns are “auto-labeled”, meaning the.c.collection of the resultingAliasrepresents the names of the individual columns using a<tablename>_<columname>scheme:j.c.table_a_id j.c.table_b_a_id
Join.alias()also features an alternate option for aliasing joins which produces no enclosing SELECT and does not normally apply labels to the column names. Theflat=Trueoption will callFromClause.alias()against the left and right sides individually. Using this option, no newSELECTis produced; we instead, from a construct as below:j = table_a.join(table_b, table_a.c.id == table_b.c.a_id) j = j.alias(flat=True)
we get a result like this:
table_a AS table_a_1 JOIN table_b AS table_b_1 ON table_a_1.id = table_b_1.a_id
The
flat=Trueargument is also propagated to the contained selectables, so that a composite join such as:j = table_a.join( table_b.join(table_c, table_b.c.id == table_c.c.b_id), table_b.c.a_id == table_a.c.id ).alias(flat=True)
Will produce an expression like:
table_a AS table_a_1 JOIN ( table_b AS table_b_1 JOIN table_c AS table_c_1 ON table_b_1.id = table_c_1.b_id ) ON table_a_1.id = table_b_1.a_idThe standalone
alias()function as well as the baseFromClause.alias()method also support theflat=Trueargument as a no-op, so that the argument can be passed to thealias()method of any selectable.버전 0.9.0에 추가: Added the
flat=Trueoption to create “aliases” of joins without enclosing inside of a SELECT subquery.매개 변수: 더 보기
-
c¶ - inherited from the
cattribute ofFromClauseAn alias for the
columnsattribute.
-
columns¶ - inherited from the
columnsattribute ofFromClauseA named-based collection of
ColumnElementobjects maintained by thisFromClause.The
columns, orccollection, is the gateway to the construction of SQL expressions using table-bound or other selectable-bound columns:select([mytable]).where(mytable.c.somecolumn == 5)
-
compare(other, **kw)¶ - inherited from the
compare()method ofClauseElementCompare this ClauseElement to the given ClauseElement.
Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass compare() methods and may be used to modify the criteria for comparison. (see
ColumnElement)
-
compile(bind=None, dialect=None, **kw)¶ - inherited from the
compile()method ofClauseElementCompile this SQL expression.
The return value is a
Compiledobject. Callingstr()orunicode()on the returned value will yield a string representation of the result. TheCompiledobject also can return a dictionary of bind parameter names and values using theparamsaccessor.매개 변수: - bind¶ – An
EngineorConnectionfrom which aCompiledwill be acquired. This argument takes precedence over thisClauseElement‘s bound engine, if any. - column_keys¶ – Used for INSERT and UPDATE statements, a list of
column names which should be present in the VALUES clause of the
compiled statement. If
None, all columns from the target table object are rendered. - dialect¶ – A
Dialectinstance from which aCompiledwill be acquired. This argument takes precedence over the bind argument as well as thisClauseElement‘s bound engine, if any. - inline¶ – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
- compile_kwargs¶ –
optional dictionary of additional parameters that will be passed through to the compiler within all “visit” methods. This allows any custom flag to be passed through to a custom compilation construct, for example. It is also used for the case of passing the
literal_bindsflag through:from sqlalchemy.sql import table, column, select t = table('t', column('x')) s = select([t]).where(t.c.x == 5) print s.compile(compile_kwargs={"literal_binds": True})
버전 0.9.0에 추가.
- bind¶ – An
-
correspond_on_equivalents(column, equivalents)¶ - inherited from the
correspond_on_equivalents()method ofFromClauseReturn corresponding_column for the given column, or if None search for a match in the given dictionary.
-
corresponding_column(column, require_embedded=False)¶ - inherited from the
corresponding_column()method ofFromClauseGiven a
ColumnElement, return the exportedColumnElementobject from thisSelectablewhich corresponds to that originalColumnvia a common ancestor column.매개 변수: - column¶ – the target
ColumnElementto be matched - require_embedded¶ – only return corresponding columns for
the given
ColumnElement, if the givenColumnElementis actually present within a sub-element of thisFromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of thisFromClause.
- column¶ – the target
-
count(whereclause=None, **params)¶ - inherited from the
count()method ofFromClausereturn a SELECT COUNT generated against this
FromClause.
-
foreign_keys¶ - inherited from the
foreign_keysattribute ofFromClauseReturn the collection of ForeignKey objects which this FromClause references.
-
join(right, onclause=None, isouter=False, full=False)¶ - inherited from the
join()method ofFromClauseReturn a
Joinfrom thisFromClauseto anotherFromClause.E.g.:
from sqlalchemy import join j = user_table.join(address_table, user_table.c.id == address_table.c.user_id) stmt = select([user_table]).select_from(j)
would emit SQL along the lines of:
SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - isouter¶ – if True, render a LEFT OUTER JOIN, instead of JOIN.
- full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. Implies
FromClause.join.isouter.버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
lateral(name=None)¶ - inherited from the
lateral()method ofFromClauseReturn a LATERAL alias of this
FromClause.The return value is the
Lateralconstruct also provided by the top-levellateral()function.버전 1.1에 추가.
더 보기
LATERAL correlation - overview of usage.
-
outerjoin(right, onclause=None, full=False)¶ - inherited from the
outerjoin()method ofFromClauseReturn a
Joinfrom thisFromClauseto anotherFromClause, with the “isouter” flag set to True.E.g.:
from sqlalchemy import outerjoin j = user_table.outerjoin(address_table, user_table.c.id == address_table.c.user_id)
The above is equivalent to:
j = user_table.join( address_table, user_table.c.id == address_table.c.user_id, isouter=True)
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN.
버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
params(*optionaldict, **kwargs)¶ - inherited from the
params()method ofClauseElementReturn a copy with
bindparam()elements replaced.Returns a copy of this ClauseElement with
bindparam()elements replaced with values taken from the given dictionary:>>> clause = column('x') + bindparam('foo') >>> print clause.compile().params {'foo':None} >>> print clause.params({'foo':7}).compile().params {'foo':7}
-
primary_key¶ - inherited from the
primary_keyattribute ofFromClauseReturn the collection of Column objects which comprise the primary key of this FromClause.
-
replace_selectable(old, alias)¶ - inherited from the
replace_selectable()method ofFromClausereplace all occurrences of FromClause ‘old’ with the given Alias object, returning a copy of this
FromClause.
-
select(whereclause=None, **kwargs)¶ Create a
Selectfrom thisJoin.The equivalent long-hand form, given a
Joinobjectj, is:from sqlalchemy import select j = select([j.left, j.right], **kw).\ where(whereclause).\ select_from(j)
매개 변수:
-
unique_params(*optionaldict, **kwargs)¶ - inherited from the
unique_params()method ofClauseElementReturn a copy with
bindparam()elements replaced.Same functionality as
params(), except adds unique=True to affected bind parameters so that multiple statements can be used.
-
-
class
sqlalchemy.sql.expression.Lateral(selectable, name=None)¶ Bases:
sqlalchemy.sql.expression.AliasRepresent a LATERAL subquery.
This object is constructed from the
lateral()module level function as well as theFromClause.lateral()method available on allFromClausesubclasses.While LATERAL is part of the SQL standard, curently only more recent Postgresql versions provide support for this keyword.
버전 1.1에 추가.
더 보기
LATERAL correlation - overview of usage.
-
class
sqlalchemy.sql.expression.ScalarSelect(element)¶ Bases:
sqlalchemy.sql.expression.Generative,sqlalchemy.sql.expression.Grouping-
where(crit)¶ Apply a WHERE clause to the SELECT statement referred to by this
ScalarSelect.
-
-
class
sqlalchemy.sql.expression.Select(columns=None, whereclause=None, from_obj=None, distinct=False, having=None, correlate=True, prefixes=None, suffixes=None, **kwargs)¶ Bases:
sqlalchemy.sql.expression.HasPrefixes,sqlalchemy.sql.expression.HasSuffixes,sqlalchemy.sql.expression.GenerativeSelectRepresents a
SELECTstatement.-
__init__(columns=None, whereclause=None, from_obj=None, distinct=False, having=None, correlate=True, prefixes=None, suffixes=None, **kwargs)¶ Construct a new
Selectobject.This constructor is mirrored as a public API function; see
select()for a full usage and argument description.
-
alias(name=None, flat=False)¶ - inherited from the
alias()method ofFromClausereturn an alias of this
FromClause.This is shorthand for calling:
from sqlalchemy import alias a = alias(self, name=name)
See
alias()for details.
-
append_column(column)¶ append the given column expression to the columns clause of this select() construct.
This is an in-place mutation method; the
column()method is preferred, as it provides standard method chaining.
-
append_correlation(fromclause)¶ append the given correlation expression to this select() construct.
This is an in-place mutation method; the
correlate()method is preferred, as it provides standard method chaining.
-
append_from(fromclause)¶ append the given FromClause expression to this select() construct’s FROM clause.
This is an in-place mutation method; the
select_from()method is preferred, as it provides standard method chaining.
-
append_group_by(*clauses)¶ - inherited from the
append_group_by()method ofGenerativeSelectAppend the given GROUP BY criterion applied to this selectable.
The criterion will be appended to any pre-existing GROUP BY criterion.
This is an in-place mutation method; the
group_by()method is preferred, as it provides standard method chaining.
-
append_having(having)¶ append the given expression to this select() construct’s HAVING criterion.
The expression will be joined to existing HAVING criterion via AND.
This is an in-place mutation method; the
having()method is preferred, as it provides standard method chaining.
-
append_order_by(*clauses)¶ - inherited from the
append_order_by()method ofGenerativeSelectAppend the given ORDER BY criterion applied to this selectable.
The criterion will be appended to any pre-existing ORDER BY criterion.
This is an in-place mutation method; the
order_by()method is preferred, as it provides standard method chaining.
-
append_prefix(clause)¶ append the given columns clause prefix expression to this select() construct.
This is an in-place mutation method; the
prefix_with()method is preferred, as it provides standard method chaining.
-
append_whereclause(whereclause)¶ append the given expression to this select() construct’s WHERE criterion.
The expression will be joined to existing WHERE criterion via AND.
This is an in-place mutation method; the
where()method is preferred, as it provides standard method chaining.
-
apply_labels()¶ - inherited from the
apply_labels()method ofGenerativeSelectreturn a new selectable with the ‘use_labels’ flag set to True.
This will result in column expressions being generated using labels against their table name, such as “SELECT somecolumn AS tablename_somecolumn”. This allows selectables which contain multiple FROM clauses to produce a unique set of column names regardless of name conflicts among the individual FROM clauses.
-
as_scalar()¶ - inherited from the
as_scalar()method ofSelectBasereturn a ‘scalar’ representation of this selectable, which can be used as a column expression.
Typically, a select statement which has only one column in its columns clause is eligible to be used as a scalar expression.
The returned object is an instance of
ScalarSelect.
-
autocommit()¶ - inherited from the
autocommit()method ofSelectBasereturn a new selectable with the ‘autocommit’ flag set to True.
버전 0.6 폐지:
autocommit()is deprecated. UseExecutable.execution_options()with the ‘autocommit’ flag.
-
c¶ - inherited from the
cattribute ofFromClauseAn alias for the
columnsattribute.
-
column(column)¶ return a new select() construct with the given column expression added to its columns clause.
-
columns¶ - inherited from the
columnsattribute ofFromClauseA named-based collection of
ColumnElementobjects maintained by thisFromClause.The
columns, orccollection, is the gateway to the construction of SQL expressions using table-bound or other selectable-bound columns:select([mytable]).where(mytable.c.somecolumn == 5)
-
compare(other, **kw)¶ - inherited from the
compare()method ofClauseElementCompare this ClauseElement to the given ClauseElement.
Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass compare() methods and may be used to modify the criteria for comparison. (see
ColumnElement)
-
compile(bind=None, dialect=None, **kw)¶ - inherited from the
compile()method ofClauseElementCompile this SQL expression.
The return value is a
Compiledobject. Callingstr()orunicode()on the returned value will yield a string representation of the result. TheCompiledobject also can return a dictionary of bind parameter names and values using theparamsaccessor.매개 변수: - bind¶ – An
EngineorConnectionfrom which aCompiledwill be acquired. This argument takes precedence over thisClauseElement‘s bound engine, if any. - column_keys¶ – Used for INSERT and UPDATE statements, a list of
column names which should be present in the VALUES clause of the
compiled statement. If
None, all columns from the target table object are rendered. - dialect¶ – A
Dialectinstance from which aCompiledwill be acquired. This argument takes precedence over the bind argument as well as thisClauseElement‘s bound engine, if any. - inline¶ – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
- compile_kwargs¶ –
optional dictionary of additional parameters that will be passed through to the compiler within all “visit” methods. This allows any custom flag to be passed through to a custom compilation construct, for example. It is also used for the case of passing the
literal_bindsflag through:from sqlalchemy.sql import table, column, select t = table('t', column('x')) s = select([t]).where(t.c.x == 5) print s.compile(compile_kwargs={"literal_binds": True})
버전 0.9.0에 추가.
- bind¶ – An
-
correlate(*fromclauses)¶ return a new
Selectwhich will correlate the given FROM clauses to that of an enclosingSelect.Calling this method turns off the
Selectobject’s default behavior of “auto-correlation”. Normally, FROM elements which appear in aSelectthat encloses this one via its WHERE clause, ORDER BY, HAVING or columns clause will be omitted from thisSelectobject’s FROM clause. Setting an explicit correlation collection using theSelect.correlate()method provides a fixed list of FROM objects that can potentially take place in this process.When
Select.correlate()is used to apply specific FROM clauses for correlation, the FROM elements become candidates for correlation regardless of how deeply nested thisSelectobject is, relative to an enclosingSelectwhich refers to the same FROM object. This is in contrast to the behavior of “auto-correlation” which only correlates to an immediate enclosingSelect. Multi-level correlation ensures that the link between enclosed and enclosingSelectis always via at least one WHERE/ORDER BY/HAVING/columns clause in order for correlation to take place.If
Noneis passed, theSelectobject will correlate none of its FROM entries, and all will render unconditionally in the local FROM clause.매개 변수: *fromclauses¶ – a list of one or more
FromClauseconstructs, or other compatible constructs (i.e. ORM-mapped classes) to become part of the correlate collection.버전 0.8.0으로 변경: ORM-mapped classes are accepted by
Select.correlate().버전 0.8.0으로 변경: The
Select.correlate()method no longer unconditionally removes entries from the FROM clause; instead, the candidate FROM entries must also be matched by a FROM entry located in an enclosingSelect, which ultimately encloses this one as present in the WHERE clause, ORDER BY clause, HAVING clause, or columns clause of an enclosingSelect().
-
correlate_except(*fromclauses)¶ return a new
Selectwhich will omit the given FROM clauses from the auto-correlation process.Calling
Select.correlate_except()turns off theSelectobject’s default behavior of “auto-correlation” for the given FROM elements. An element specified here will unconditionally appear in the FROM list, while all other FROM elements remain subject to normal auto-correlation behaviors.버전 0.8.2으로 변경: The
Select.correlate_except()method was improved to fully prevent FROM clauses specified here from being omitted from the immediate FROM clause of thisSelect.If
Noneis passed, theSelectobject will correlate all of its FROM entries.버전 0.8.2으로 변경: calling
correlate_except(None)will correctly auto-correlate all FROM clauses.매개 변수: *fromclauses¶ – a list of one or more FromClauseconstructs, or other compatible constructs (i.e. ORM-mapped classes) to become part of the correlate-exception collection.
-
correspond_on_equivalents(column, equivalents)¶ - inherited from the
correspond_on_equivalents()method ofFromClauseReturn corresponding_column for the given column, or if None search for a match in the given dictionary.
-
corresponding_column(column, require_embedded=False)¶ - inherited from the
corresponding_column()method ofFromClauseGiven a
ColumnElement, return the exportedColumnElementobject from thisSelectablewhich corresponds to that originalColumnvia a common ancestor column.매개 변수: - column¶ – the target
ColumnElementto be matched - require_embedded¶ – only return corresponding columns for
the given
ColumnElement, if the givenColumnElementis actually present within a sub-element of thisFromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of thisFromClause.
- column¶ – the target
-
count(whereclause=None, **params)¶ - inherited from the
count()method ofFromClausereturn a SELECT COUNT generated against this
FromClause.
-
cte(name=None, recursive=False)¶ -
Return a new
CTE, or Common Table Expression instance.Common table expressions are a SQL standard whereby SELECT statements can draw upon secondary statements specified along with the primary statement, using a clause called “WITH”. Special semantics regarding UNION can also be employed to allow “recursive” queries, where a SELECT statement can draw upon the set of rows that have previously been selected.
CTEs can also be applied to DML constructs UPDATE, INSERT and DELETE on some databases, both as a source of CTE rows when combined with RETURNING, as well as a consumer of CTE rows.
SQLAlchemy detects
CTEobjects, which are treated similarly toAliasobjects, as special elements to be delivered to the FROM clause of the statement as well as to a WITH clause at the top of the statement.버전 1.1으로 변경: Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE.
매개 변수: - name¶ – name given to the common table expression. Like
_FromClause.alias(), the name can be left asNonein which case an anonymous symbol will be used at query compile time. - recursive¶ – if
True, will renderWITH RECURSIVE. A recursive common table expression is intended to be used in conjunction with UNION ALL in order to derive rows from those already selected.
The following examples include two from Postgresql’s documentation at http://www.postgresql.org/docs/current/static/queries-with.html, as well as additional examples.
Example 1, non recursive:
from sqlalchemy import (Table, Column, String, Integer, MetaData, select, func) metadata = MetaData() orders = Table('orders', metadata, Column('region', String), Column('amount', Integer), Column('product', String), Column('quantity', Integer) ) regional_sales = select([ orders.c.region, func.sum(orders.c.amount).label('total_sales') ]).group_by(orders.c.region).cte("regional_sales") top_regions = select([regional_sales.c.region]).\ where( regional_sales.c.total_sales > select([ func.sum(regional_sales.c.total_sales)/10 ]) ).cte("top_regions") statement = select([ orders.c.region, orders.c.product, func.sum(orders.c.quantity).label("product_units"), func.sum(orders.c.amount).label("product_sales") ]).where(orders.c.region.in_( select([top_regions.c.region]) )).group_by(orders.c.region, orders.c.product) result = conn.execute(statement).fetchall()
Example 2, WITH RECURSIVE:
from sqlalchemy import (Table, Column, String, Integer, MetaData, select, func) metadata = MetaData() parts = Table('parts', metadata, Column('part', String), Column('sub_part', String), Column('quantity', Integer), ) included_parts = select([ parts.c.sub_part, parts.c.part, parts.c.quantity]).\ where(parts.c.part=='our part').\ cte(recursive=True) incl_alias = included_parts.alias() parts_alias = parts.alias() included_parts = included_parts.union_all( select([ parts_alias.c.sub_part, parts_alias.c.part, parts_alias.c.quantity ]). where(parts_alias.c.part==incl_alias.c.sub_part) ) statement = select([ included_parts.c.sub_part, func.sum(included_parts.c.quantity). label('total_quantity') ]).\ group_by(included_parts.c.sub_part) result = conn.execute(statement).fetchall()
Example 3, an upsert using UPDATE and INSERT with CTEs:
orders = table( 'orders', column('region'), column('amount'), column('product'), column('quantity') ) upsert = ( orders.update() .where(orders.c.region == 'Region1') .values(amount=1.0, product='Product1', quantity=1) .returning(*(orders.c._all_columns)).cte('upsert')) insert = orders.insert().from_select( orders.c.keys(), select([ literal('Region1'), literal(1.0), literal('Product1'), literal(1) ).where(exists(upsert.select())) ) connection.execute(insert)더 보기
orm.query.Query.cte()- ORM version ofHasCTE.cte(). - name¶ – name given to the common table expression. Like
-
description¶ - inherited from the
descriptionattribute ofFromClausea brief description of this FromClause.
Used primarily for error message formatting.
-
distinct(*expr)¶ Return a new select() construct which will apply DISTINCT to its columns clause.
매개 변수: *expr¶ – optional column expressions. When present, the Postgresql dialect will render a DISTINCT ON (<expressions>>)construct.
-
except_(other, **kwargs)¶ return a SQL EXCEPT of this select() construct against the given selectable.
-
except_all(other, **kwargs)¶ return a SQL EXCEPT ALL of this select() construct against the given selectable.
-
execute(*multiparams, **params)¶ - inherited from the
execute()method ofExecutableCompile and execute this
Executable.
-
execution_options(**kw)¶ - inherited from the
execution_options()method ofExecutableSet non-SQL options for the statement which take effect during execution.
Execution options can be set on a per-statement or per
Connectionbasis. Additionally, theEngineand ORMQueryobjects provide access to execution options which they in turn configure upon connections.The
execution_options()method is generative. A new instance of this statement is returned that contains the options:statement = select([table.c.x, table.c.y]) statement = statement.execution_options(autocommit=True)
Note that only a subset of possible execution options can be applied to a statement - these include “autocommit” and “stream_results”, but not “isolation_level” or “compiled_cache”. See
Connection.execution_options()for a full list of possible options.
-
for_update¶ - inherited from the
for_updateattribute ofGenerativeSelectProvide legacy dialect support for the
for_updateattribute.
-
foreign_keys¶ - inherited from the
foreign_keysattribute ofFromClauseReturn the collection of ForeignKey objects which this FromClause references.
-
froms¶ Return the displayed list of FromClause elements.
-
get_children(column_collections=True, **kwargs)¶ return child elements as per the ClauseElement specification.
-
group_by(*clauses)¶ - inherited from the
group_by()method ofGenerativeSelectreturn a new selectable with the given list of GROUP BY criterion applied.
The criterion will be appended to any pre-existing GROUP BY criterion.
-
having(having)¶ return a new select() construct with the given expression added to its HAVING clause, joined to the existing clause via AND, if any.
-
inner_columns¶ an iterator of all ColumnElement expressions which would be rendered into the columns clause of the resulting SELECT statement.
-
intersect(other, **kwargs)¶ return a SQL INTERSECT of this select() construct against the given selectable.
-
intersect_all(other, **kwargs)¶ return a SQL INTERSECT ALL of this select() construct against the given selectable.
-
join(right, onclause=None, isouter=False, full=False)¶ - inherited from the
join()method ofFromClauseReturn a
Joinfrom thisFromClauseto anotherFromClause.E.g.:
from sqlalchemy import join j = user_table.join(address_table, user_table.c.id == address_table.c.user_id) stmt = select([user_table]).select_from(j)
would emit SQL along the lines of:
SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - isouter¶ – if True, render a LEFT OUTER JOIN, instead of JOIN.
- full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. Implies
FromClause.join.isouter.버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
label(name)¶ - inherited from the
label()method ofSelectBasereturn a ‘scalar’ representation of this selectable, embedded as a subquery with a label.
더 보기
-
lateral(name=None)¶ - inherited from the
lateral()method ofFromClauseReturn a LATERAL alias of this
FromClause.The return value is the
Lateralconstruct also provided by the top-levellateral()function.버전 1.1에 추가.
더 보기
LATERAL correlation - overview of usage.
-
limit(limit)¶ - inherited from the
limit()method ofGenerativeSelectreturn a new selectable with the given LIMIT criterion applied.
This is a numerical value which usually renders as a
LIMITexpression in the resulting select. Backends that don’t supportLIMITwill attempt to provide similar functionality.버전 1.0.0으로 변경: -
Select.limit()can now accept arbitrary SQL expressions as well as integer values.매개 변수: limit¶ – an integer LIMIT parameter, or a SQL expression that provides an integer result.
-
locate_all_froms(*args, **kw)¶ return a Set of all FromClause elements referenced by this Select.
This set is a superset of that returned by the
fromsproperty, which is specifically for those FromClause elements that would actually be rendered.
-
offset(offset)¶ - inherited from the
offset()method ofGenerativeSelectreturn a new selectable with the given OFFSET criterion applied.
This is a numeric value which usually renders as an
OFFSETexpression in the resulting select. Backends that don’t supportOFFSETwill attempt to provide similar functionality.버전 1.0.0으로 변경: -
Select.offset()can now accept arbitrary SQL expressions as well as integer values.매개 변수: offset¶ – an integer OFFSET parameter, or a SQL expression that provides an integer result.
-
order_by(*clauses)¶ - inherited from the
order_by()method ofGenerativeSelectreturn a new selectable with the given list of ORDER BY criterion applied.
The criterion will be appended to any pre-existing ORDER BY criterion.
-
outerjoin(right, onclause=None, full=False)¶ - inherited from the
outerjoin()method ofFromClauseReturn a
Joinfrom thisFromClauseto anotherFromClause, with the “isouter” flag set to True.E.g.:
from sqlalchemy import outerjoin j = user_table.outerjoin(address_table, user_table.c.id == address_table.c.user_id)
The above is equivalent to:
j = user_table.join( address_table, user_table.c.id == address_table.c.user_id, isouter=True)
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN.
버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
params(*optionaldict, **kwargs)¶ - inherited from the
params()method ofClauseElementReturn a copy with
bindparam()elements replaced.Returns a copy of this ClauseElement with
bindparam()elements replaced with values taken from the given dictionary:>>> clause = column('x') + bindparam('foo') >>> print clause.compile().params {'foo':None} >>> print clause.params({'foo':7}).compile().params {'foo':7}
-
prefix_with(*expr, **kw)¶ - inherited from the
prefix_with()method ofHasPrefixesAdd one or more expressions following the statement keyword, i.e. SELECT, INSERT, UPDATE, or DELETE. Generative.
This is used to support backend-specific prefix keywords such as those provided by MySQL.
E.g.:
stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")
Multiple prefixes can be specified by multiple calls to
prefix_with().매개 변수: - *expr¶ – textual or
ClauseElementconstruct which will be rendered following the INSERT, UPDATE, or DELETE keyword. - **kw¶ – A single keyword ‘dialect’ is accepted. This is an optional string dialect name which will limit rendering of this prefix to only that dialect.
- *expr¶ – textual or
-
primary_key¶ - inherited from the
primary_keyattribute ofFromClauseReturn the collection of Column objects which comprise the primary key of this FromClause.
-
reduce_columns(only_synonyms=True)¶ Return a new :func`.select` construct with redundantly named, equivalently-valued columns removed from the columns clause.
“Redundant” here means two columns where one refers to the other either based on foreign key, or via a simple equality comparison in the WHERE clause of the statement. The primary purpose of this method is to automatically construct a select statement with all uniquely-named columns, without the need to use table-qualified labels as
apply_labels()does.When columns are omitted based on foreign key, the referred-to column is the one that’s kept. When columns are omitted based on WHERE eqivalence, the first column in the columns clause is the one that’s kept.
매개 변수: only_synonyms¶ – when True, limit the removal of columns to those which have the same name as the equivalent. Otherwise, all columns that are equivalent to another are removed. 버전 0.8에 추가.
-
replace_selectable(old, alias)¶ - inherited from the
replace_selectable()method ofFromClausereplace all occurrences of FromClause ‘old’ with the given Alias object, returning a copy of this
FromClause.
-
scalar(*multiparams, **params)¶ - inherited from the
scalar()method ofExecutableCompile and execute this
Executable, returning the result’s scalar representation.
-
select(whereclause=None, **params)¶ - inherited from the
select()method ofFromClausereturn a SELECT of this
FromClause.더 보기
select()- general purpose method which allows for arbitrary column lists.
-
select_from(fromclause)¶ return a new
select()construct with the given FROM expression merged into its list of FROM objects.E.g.:
table1 = table('t1', column('a')) table2 = table('t2', column('b')) s = select([table1.c.a]).\ select_from( table1.join(table2, table1.c.a==table2.c.b) )
The “from” list is a unique set on the identity of each element, so adding an already present
Tableor other selectable will have no effect. Passing aJointhat refers to an already presentTableor other selectable will have the effect of concealing the presence of that selectable as an individual element in the rendered FROM list, instead rendering it into a JOIN clause.While the typical purpose of
Select.select_from()is to replace the default, derived FROM clause with a join, it can also be called with individual table elements, multiple times if desired, in the case that the FROM clause cannot be fully derived from the columns clause:select([func.count('*')]).select_from(table1)
-
self_group(against=None)¶ return a ‘grouping’ construct as per the ClauseElement specification.
This produces an element that can be embedded in an expression. Note that this method is called automatically as needed when constructing expressions and should not require explicit use.
-
suffix_with(*expr, **kw)¶ - inherited from the
suffix_with()method ofHasSuffixesAdd one or more expressions following the statement as a whole.
This is used to support backend-specific suffix keywords on certain constructs.
E.g.:
stmt = select([col1, col2]).cte().suffix_with( "cycle empno set y_cycle to 1 default 0", dialect="oracle")
Multiple suffixes can be specified by multiple calls to
suffix_with().매개 변수: - *expr¶ – textual or
ClauseElementconstruct which will be rendered following the target clause. - **kw¶ – A single keyword ‘dialect’ is accepted. This is an optional string dialect name which will limit rendering of this suffix to only that dialect.
- *expr¶ – textual or
-
union(other, **kwargs)¶ return a SQL UNION of this select() construct against the given selectable.
-
union_all(other, **kwargs)¶ return a SQL UNION ALL of this select() construct against the given selectable.
-
unique_params(*optionaldict, **kwargs)¶ - inherited from the
unique_params()method ofClauseElementReturn a copy with
bindparam()elements replaced.Same functionality as
params(), except adds unique=True to affected bind parameters so that multiple statements can be used.
-
where(whereclause)¶ return a new select() construct with the given expression added to its WHERE clause, joined to the existing clause via AND, if any.
-
with_for_update(nowait=False, read=False, of=None)¶ - inherited from the
with_for_update()method ofGenerativeSelectSpecify a
FOR UPDATEclause for thisGenerativeSelect.E.g.:
stmt = select([table]).with_for_update(nowait=True)
On a database like Postgresql or Oracle, the above would render a statement like:
SELECT table.a, table.b FROM table FOR UPDATE NOWAIT
on other backends, the
nowaitoption is ignored and instead would produce:SELECT table.a, table.b FROM table FOR UPDATE
When called with no arguments, the statement will render with the suffix
FOR UPDATE. Additional arguments can then be provided which allow for common database-specific variants.매개 변수: - nowait¶ – boolean; will render
FOR UPDATE NOWAITon Oracle and Postgresql dialects. - read¶ – boolean; will render
LOCK IN SHARE MODEon MySQL,FOR SHAREon Postgresql. On Postgresql, when combined withnowait, will renderFOR SHARE NOWAIT. - of¶ – SQL expression or list of SQL expression elements
(typically
Columnobjects or a compatible expression) which will render into aFOR UPDATE OFclause; supported by PostgreSQL and Oracle. May render as a table or as a column depending on backend.
버전 0.9.0에 추가.
- nowait¶ – boolean; will render
-
with_hint(selectable, text, dialect_name='*')¶ Add an indexing or other executional context hint for the given selectable to this
Select.The text of the hint is rendered in the appropriate location for the database backend in use, relative to the given
TableorAliaspassed as theselectableargument. The dialect implementation typically uses Python string substitution syntax with the token%(name)sto render the name of the table or alias. E.g. when using Oracle, the following:select([mytable]).\ with_hint(mytable, "index(%(name)s ix_mytable)")
Would render SQL as:
select /*+ index(mytable ix_mytable) */ ... from mytable
The
dialect_nameoption will limit the rendering of a particular hint to a particular backend. Such as, to add hints for both Oracle and Sybase simultaneously:select([mytable]).\ with_hint(mytable, "index(%(name)s ix_mytable)", 'oracle').\ with_hint(mytable, "WITH INDEX ix_mytable", 'sybase')
-
with_only_columns(columns)¶ Return a new
select()construct with its columns clause replaced with the given columns.버전 0.7.3으로 변경: Due to a bug fix, this method has a slight behavioral change as of version 0.7.3. Prior to version 0.7.3, the FROM clause of a
select()was calculated upfront and as new columns were added; in 0.7.3 and later it’s calculated at compile time, fixing an issue regarding late binding of columns to parent tables. This changes the behavior ofSelect.with_only_columns()in that FROM clauses no longer represented in the new list are dropped, but this behavior is more consistent in that the FROM clauses are consistently derived from the current columns clause. The original intent of this method is to allow trimming of the existing columns list to be fewer columns than originally present; the use case of replacing the columns list with an entirely different one hadn’t been anticipated until 0.7.3 was released; the usage guidelines below illustrate how this should be done.This method is exactly equivalent to as if the original
select()had been called with the given columns clause. I.e. a statement:s = select([table1.c.a, table1.c.b]) s = s.with_only_columns([table1.c.b])
should be exactly equivalent to:
s = select([table1.c.b])
This means that FROM clauses which are only derived from the column list will be discarded if the new column list no longer contains that FROM:
>>> table1 = table('t1', column('a'), column('b')) >>> table2 = table('t2', column('a'), column('b')) >>> s1 = select([table1.c.a, table2.c.b]) >>> print s1 SELECT t1.a, t2.b FROM t1, t2 >>> s2 = s1.with_only_columns([table2.c.b]) >>> print s2 SELECT t2.b FROM t1
The preferred way to maintain a specific FROM clause in the construct, assuming it won’t be represented anywhere else (i.e. not in the WHERE clause, etc.) is to set it using
Select.select_from():>>> s1 = select([table1.c.a, table2.c.b]).\ ... select_from(table1.join(table2, ... table1.c.a==table2.c.a)) >>> s2 = s1.with_only_columns([table2.c.b]) >>> print s2 SELECT t2.b FROM t1 JOIN t2 ON t1.a=t2.a
Care should also be taken to use the correct set of column objects passed to
Select.with_only_columns(). Since the method is essentially equivalent to calling theselect()construct in the first place with the given columns, the columns passed toSelect.with_only_columns()should usually be a subset of those which were passed to theselect()construct, not those which are available from the.ccollection of thatselect(). That is:s = select([table1.c.a, table1.c.b]).select_from(table1) s = s.with_only_columns([table1.c.b])
and not:
# usually incorrect s = s.with_only_columns([s.c.b])
The latter would produce the SQL:
SELECT b FROM (SELECT t1.a AS a, t1.b AS b FROM t1), t1
Since the
select()construct is essentially being asked to select both fromtable1as well as itself.
-
with_statement_hint(text, dialect_name='*')¶ add a statement hint to this
Select.This method is similar to
Select.with_hint()except that it does not require an individual table, and instead applies to the statement as a whole.Hints here are specific to the backend database and may include directives such as isolation levels, file directives, fetch directives, etc.
버전 1.0.0에 추가.
더 보기
-
-
class
sqlalchemy.sql.expression.Selectable¶ Bases:
sqlalchemy.sql.expression.ClauseElementmark a class as being selectable
-
class
sqlalchemy.sql.expression.SelectBase¶ Bases:
sqlalchemy.sql.expression.HasCTE,sqlalchemy.sql.expression.Executable,sqlalchemy.sql.expression.FromClauseBase class for SELECT statements.
This includes
Select,CompoundSelectandTextAsFrom.-
as_scalar()¶ return a ‘scalar’ representation of this selectable, which can be used as a column expression.
Typically, a select statement which has only one column in its columns clause is eligible to be used as a scalar expression.
The returned object is an instance of
ScalarSelect.
-
autocommit()¶ return a new selectable with the ‘autocommit’ flag set to True.
버전 0.6 폐지:
autocommit()is deprecated. UseExecutable.execution_options()with the ‘autocommit’ flag.
-
label(name)¶ return a ‘scalar’ representation of this selectable, embedded as a subquery with a label.
더 보기
-
-
class
sqlalchemy.sql.expression.TableClause(name, *columns)¶ Bases:
sqlalchemy.sql.expression.Immutable,sqlalchemy.sql.expression.FromClauseRepresents a minimal “table” construct.
This is a lightweight table object that has only a name and a collection of columns, which are typically produced by the
expression.column()function:from sqlalchemy import table, column user = table("user", column("id"), column("name"), column("description"), )
The
TableClauseconstruct serves as the base for the more commonly usedTableobject, providing the usual set ofFromClauseservices including the.c.collection and statement generation methods.It does not provide all the additional schema-level services of
Table, including constraints, references to other tables, or support forMetaData-level services. It’s useful on its own as an ad-hoc construct used to generate quick SQL statements when a more fully fledgedTableis not on hand.-
__init__(name, *columns)¶ Construct a new
TableClauseobject.This constructor is mirrored as a public API function; see
table()for a full usage and argument description.
-
alias(name=None, flat=False)¶ - inherited from the
alias()method ofFromClausereturn an alias of this
FromClause.This is shorthand for calling:
from sqlalchemy import alias a = alias(self, name=name)
See
alias()for details.
-
c¶ - inherited from the
cattribute ofFromClauseAn alias for the
columnsattribute.
-
columns¶ - inherited from the
columnsattribute ofFromClauseA named-based collection of
ColumnElementobjects maintained by thisFromClause.The
columns, orccollection, is the gateway to the construction of SQL expressions using table-bound or other selectable-bound columns:select([mytable]).where(mytable.c.somecolumn == 5)
-
compare(other, **kw)¶ - inherited from the
compare()method ofClauseElementCompare this ClauseElement to the given ClauseElement.
Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass compare() methods and may be used to modify the criteria for comparison. (see
ColumnElement)
-
compile(bind=None, dialect=None, **kw)¶ - inherited from the
compile()method ofClauseElementCompile this SQL expression.
The return value is a
Compiledobject. Callingstr()orunicode()on the returned value will yield a string representation of the result. TheCompiledobject also can return a dictionary of bind parameter names and values using theparamsaccessor.매개 변수: - bind¶ – An
EngineorConnectionfrom which aCompiledwill be acquired. This argument takes precedence over thisClauseElement‘s bound engine, if any. - column_keys¶ – Used for INSERT and UPDATE statements, a list of
column names which should be present in the VALUES clause of the
compiled statement. If
None, all columns from the target table object are rendered. - dialect¶ – A
Dialectinstance from which aCompiledwill be acquired. This argument takes precedence over the bind argument as well as thisClauseElement‘s bound engine, if any. - inline¶ – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
- compile_kwargs¶ –
optional dictionary of additional parameters that will be passed through to the compiler within all “visit” methods. This allows any custom flag to be passed through to a custom compilation construct, for example. It is also used for the case of passing the
literal_bindsflag through:from sqlalchemy.sql import table, column, select t = table('t', column('x')) s = select([t]).where(t.c.x == 5) print s.compile(compile_kwargs={"literal_binds": True})
버전 0.9.0에 추가.
- bind¶ – An
-
correspond_on_equivalents(column, equivalents)¶ - inherited from the
correspond_on_equivalents()method ofFromClauseReturn corresponding_column for the given column, or if None search for a match in the given dictionary.
-
corresponding_column(column, require_embedded=False)¶ - inherited from the
corresponding_column()method ofFromClauseGiven a
ColumnElement, return the exportedColumnElementobject from thisSelectablewhich corresponds to that originalColumnvia a common ancestor column.매개 변수: - column¶ – the target
ColumnElementto be matched - require_embedded¶ – only return corresponding columns for
the given
ColumnElement, if the givenColumnElementis actually present within a sub-element of thisFromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of thisFromClause.
- column¶ – the target
-
count(whereclause=None, **params)¶ return a SELECT COUNT generated against this
TableClause.
-
delete(whereclause=None, **kwargs)¶ Generate a
delete()construct against thisTableClause.E.g.:
table.delete().where(table.c.id==7)
See
delete()for argument and usage information.
-
foreign_keys¶ - inherited from the
foreign_keysattribute ofFromClauseReturn the collection of ForeignKey objects which this FromClause references.
-
implicit_returning= False¶ TableClausedoesn’t support having a primary key or column -level defaults, so implicit returning doesn’t apply.
-
insert(values=None, inline=False, **kwargs)¶ Generate an
insert()construct against thisTableClause.E.g.:
table.insert().values(name='foo')
See
insert()for argument and usage information.
-
is_derived_from(fromclause)¶ - inherited from the
is_derived_from()method ofFromClauseReturn True if this FromClause is ‘derived’ from the given FromClause.
An example would be an Alias of a Table is derived from that Table.
-
join(right, onclause=None, isouter=False, full=False)¶ - inherited from the
join()method ofFromClauseReturn a
Joinfrom thisFromClauseto anotherFromClause.E.g.:
from sqlalchemy import join j = user_table.join(address_table, user_table.c.id == address_table.c.user_id) stmt = select([user_table]).select_from(j)
would emit SQL along the lines of:
SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - isouter¶ – if True, render a LEFT OUTER JOIN, instead of JOIN.
- full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. Implies
FromClause.join.isouter.버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
lateral(name=None)¶ - inherited from the
lateral()method ofFromClauseReturn a LATERAL alias of this
FromClause.The return value is the
Lateralconstruct also provided by the top-levellateral()function.버전 1.1에 추가.
더 보기
LATERAL correlation - overview of usage.
-
outerjoin(right, onclause=None, full=False)¶ - inherited from the
outerjoin()method ofFromClauseReturn a
Joinfrom thisFromClauseto anotherFromClause, with the “isouter” flag set to True.E.g.:
from sqlalchemy import outerjoin j = user_table.outerjoin(address_table, user_table.c.id == address_table.c.user_id)
The above is equivalent to:
j = user_table.join( address_table, user_table.c.id == address_table.c.user_id, isouter=True)
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN.
버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
primary_key¶ - inherited from the
primary_keyattribute ofFromClauseReturn the collection of Column objects which comprise the primary key of this FromClause.
-
replace_selectable(old, alias)¶ - inherited from the
replace_selectable()method ofFromClausereplace all occurrences of FromClause ‘old’ with the given Alias object, returning a copy of this
FromClause.
-
select(whereclause=None, **params)¶ - inherited from the
select()method ofFromClausereturn a SELECT of this
FromClause.더 보기
select()- general purpose method which allows for arbitrary column lists.
-
self_group(against=None)¶ - inherited from the
self_group()method ofClauseElementApply a ‘grouping’ to this
ClauseElement.This method is overridden by subclasses to return a “grouping” construct, i.e. parenthesis. In particular it’s used by “binary” expressions to provide a grouping around themselves when placed into a larger expression, as well as by
select()constructs when placed into the FROM clause of anotherselect(). (Note that subqueries should be normally created using theSelect.alias()method, as many platforms require nested SELECT statements to be named).As expressions are composed together, the application of
self_group()is automatic - end-user code should never need to use this method directly. Note that SQLAlchemy’s clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression likex OR (y AND z)- AND takes precedence over OR.The base
self_group()method ofClauseElementjust returns self.
-
update(whereclause=None, values=None, inline=False, **kwargs)¶ Generate an
update()construct against thisTableClause.E.g.:
table.update().where(table.c.id==7).values(name='foo')
See
update()for argument and usage information.
-
-
class
sqlalchemy.sql.expression.TextAsFrom(text, columns, positional=False)¶ Bases:
sqlalchemy.sql.expression.SelectBaseWrap a
TextClauseconstruct within aSelectBaseinterface.This allows the
TextClauseobject to gain a.ccollection and other FROM-like capabilities such asFromClause.alias(),SelectBase.cte(), etc.The
TextAsFromconstruct is produced via theTextClause.columns()method - see that method for details.버전 0.9.0에 추가.
-
alias(name=None, flat=False)¶ - inherited from the
alias()method ofFromClausereturn an alias of this
FromClause.This is shorthand for calling:
from sqlalchemy import alias a = alias(self, name=name)
See
alias()for details.
-
as_scalar()¶ - inherited from the
as_scalar()method ofSelectBasereturn a ‘scalar’ representation of this selectable, which can be used as a column expression.
Typically, a select statement which has only one column in its columns clause is eligible to be used as a scalar expression.
The returned object is an instance of
ScalarSelect.
-
autocommit()¶ - inherited from the
autocommit()method ofSelectBasereturn a new selectable with the ‘autocommit’ flag set to True.
버전 0.6 폐지:
autocommit()is deprecated. UseExecutable.execution_options()with the ‘autocommit’ flag.
-
bind¶ - inherited from the
bindattribute ofExecutableReturns the
EngineorConnectionto which thisExecutableis bound, or None if none found.This is a traversal which checks locally, then checks among the “from” clauses of associated objects until a bound engine or connection is found.
-
c¶ - inherited from the
cattribute ofFromClauseAn alias for the
columnsattribute.
-
columns¶ - inherited from the
columnsattribute ofFromClauseA named-based collection of
ColumnElementobjects maintained by thisFromClause.The
columns, orccollection, is the gateway to the construction of SQL expressions using table-bound or other selectable-bound columns:select([mytable]).where(mytable.c.somecolumn == 5)
-
compare(other, **kw)¶ - inherited from the
compare()method ofClauseElementCompare this ClauseElement to the given ClauseElement.
Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass compare() methods and may be used to modify the criteria for comparison. (see
ColumnElement)
-
compile(bind=None, dialect=None, **kw)¶ - inherited from the
compile()method ofClauseElementCompile this SQL expression.
The return value is a
Compiledobject. Callingstr()orunicode()on the returned value will yield a string representation of the result. TheCompiledobject also can return a dictionary of bind parameter names and values using theparamsaccessor.매개 변수: - bind¶ – An
EngineorConnectionfrom which aCompiledwill be acquired. This argument takes precedence over thisClauseElement‘s bound engine, if any. - column_keys¶ – Used for INSERT and UPDATE statements, a list of
column names which should be present in the VALUES clause of the
compiled statement. If
None, all columns from the target table object are rendered. - dialect¶ – A
Dialectinstance from which aCompiledwill be acquired. This argument takes precedence over the bind argument as well as thisClauseElement‘s bound engine, if any. - inline¶ – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
- compile_kwargs¶ –
optional dictionary of additional parameters that will be passed through to the compiler within all “visit” methods. This allows any custom flag to be passed through to a custom compilation construct, for example. It is also used for the case of passing the
literal_bindsflag through:from sqlalchemy.sql import table, column, select t = table('t', column('x')) s = select([t]).where(t.c.x == 5) print s.compile(compile_kwargs={"literal_binds": True})
버전 0.9.0에 추가.
- bind¶ – An
-
correspond_on_equivalents(column, equivalents)¶ - inherited from the
correspond_on_equivalents()method ofFromClauseReturn corresponding_column for the given column, or if None search for a match in the given dictionary.
-
corresponding_column(column, require_embedded=False)¶ - inherited from the
corresponding_column()method ofFromClauseGiven a
ColumnElement, return the exportedColumnElementobject from thisSelectablewhich corresponds to that originalColumnvia a common ancestor column.매개 변수: - column¶ – the target
ColumnElementto be matched - require_embedded¶ – only return corresponding columns for
the given
ColumnElement, if the givenColumnElementis actually present within a sub-element of thisFromClause. Normally the column will match if it merely shares a common ancestor with one of the exported columns of thisFromClause.
- column¶ – the target
-
count(whereclause=None, **params)¶ - inherited from the
count()method ofFromClausereturn a SELECT COUNT generated against this
FromClause.
-
cte(name=None, recursive=False)¶ -
Return a new
CTE, or Common Table Expression instance.Common table expressions are a SQL standard whereby SELECT statements can draw upon secondary statements specified along with the primary statement, using a clause called “WITH”. Special semantics regarding UNION can also be employed to allow “recursive” queries, where a SELECT statement can draw upon the set of rows that have previously been selected.
CTEs can also be applied to DML constructs UPDATE, INSERT and DELETE on some databases, both as a source of CTE rows when combined with RETURNING, as well as a consumer of CTE rows.
SQLAlchemy detects
CTEobjects, which are treated similarly toAliasobjects, as special elements to be delivered to the FROM clause of the statement as well as to a WITH clause at the top of the statement.버전 1.1으로 변경: Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE.
매개 변수: - name¶ – name given to the common table expression. Like
_FromClause.alias(), the name can be left asNonein which case an anonymous symbol will be used at query compile time. - recursive¶ – if
True, will renderWITH RECURSIVE. A recursive common table expression is intended to be used in conjunction with UNION ALL in order to derive rows from those already selected.
The following examples include two from Postgresql’s documentation at http://www.postgresql.org/docs/current/static/queries-with.html, as well as additional examples.
Example 1, non recursive:
from sqlalchemy import (Table, Column, String, Integer, MetaData, select, func) metadata = MetaData() orders = Table('orders', metadata, Column('region', String), Column('amount', Integer), Column('product', String), Column('quantity', Integer) ) regional_sales = select([ orders.c.region, func.sum(orders.c.amount).label('total_sales') ]).group_by(orders.c.region).cte("regional_sales") top_regions = select([regional_sales.c.region]).\ where( regional_sales.c.total_sales > select([ func.sum(regional_sales.c.total_sales)/10 ]) ).cte("top_regions") statement = select([ orders.c.region, orders.c.product, func.sum(orders.c.quantity).label("product_units"), func.sum(orders.c.amount).label("product_sales") ]).where(orders.c.region.in_( select([top_regions.c.region]) )).group_by(orders.c.region, orders.c.product) result = conn.execute(statement).fetchall()
Example 2, WITH RECURSIVE:
from sqlalchemy import (Table, Column, String, Integer, MetaData, select, func) metadata = MetaData() parts = Table('parts', metadata, Column('part', String), Column('sub_part', String), Column('quantity', Integer), ) included_parts = select([ parts.c.sub_part, parts.c.part, parts.c.quantity]).\ where(parts.c.part=='our part').\ cte(recursive=True) incl_alias = included_parts.alias() parts_alias = parts.alias() included_parts = included_parts.union_all( select([ parts_alias.c.sub_part, parts_alias.c.part, parts_alias.c.quantity ]). where(parts_alias.c.part==incl_alias.c.sub_part) ) statement = select([ included_parts.c.sub_part, func.sum(included_parts.c.quantity). label('total_quantity') ]).\ group_by(included_parts.c.sub_part) result = conn.execute(statement).fetchall()
Example 3, an upsert using UPDATE and INSERT with CTEs:
orders = table( 'orders', column('region'), column('amount'), column('product'), column('quantity') ) upsert = ( orders.update() .where(orders.c.region == 'Region1') .values(amount=1.0, product='Product1', quantity=1) .returning(*(orders.c._all_columns)).cte('upsert')) insert = orders.insert().from_select( orders.c.keys(), select([ literal('Region1'), literal(1.0), literal('Product1'), literal(1) ).where(exists(upsert.select())) ) connection.execute(insert)더 보기
orm.query.Query.cte()- ORM version ofHasCTE.cte(). - name¶ – name given to the common table expression. Like
-
description¶ - inherited from the
descriptionattribute ofFromClausea brief description of this FromClause.
Used primarily for error message formatting.
-
execute(*multiparams, **params)¶ - inherited from the
execute()method ofExecutableCompile and execute this
Executable.
-
execution_options(**kw)¶ - inherited from the
execution_options()method ofExecutableSet non-SQL options for the statement which take effect during execution.
Execution options can be set on a per-statement or per
Connectionbasis. Additionally, theEngineand ORMQueryobjects provide access to execution options which they in turn configure upon connections.The
execution_options()method is generative. A new instance of this statement is returned that contains the options:statement = select([table.c.x, table.c.y]) statement = statement.execution_options(autocommit=True)
Note that only a subset of possible execution options can be applied to a statement - these include “autocommit” and “stream_results”, but not “isolation_level” or “compiled_cache”. See
Connection.execution_options()for a full list of possible options.
-
foreign_keys¶ - inherited from the
foreign_keysattribute ofFromClauseReturn the collection of ForeignKey objects which this FromClause references.
-
get_children(**kwargs)¶ - inherited from the
get_children()method ofClauseElementReturn immediate child elements of this
ClauseElement.This is used for visit traversal.
**kwargs may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level).
-
is_derived_from(fromclause)¶ - inherited from the
is_derived_from()method ofFromClauseReturn True if this FromClause is ‘derived’ from the given FromClause.
An example would be an Alias of a Table is derived from that Table.
-
join(right, onclause=None, isouter=False, full=False)¶ - inherited from the
join()method ofFromClauseReturn a
Joinfrom thisFromClauseto anotherFromClause.E.g.:
from sqlalchemy import join j = user_table.join(address_table, user_table.c.id == address_table.c.user_id) stmt = select([user_table]).select_from(j)
would emit SQL along the lines of:
SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - isouter¶ – if True, render a LEFT OUTER JOIN, instead of JOIN.
- full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN. Implies
FromClause.join.isouter.버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
label(name)¶ - inherited from the
label()method ofSelectBasereturn a ‘scalar’ representation of this selectable, embedded as a subquery with a label.
더 보기
-
lateral(name=None)¶ - inherited from the
lateral()method ofFromClauseReturn a LATERAL alias of this
FromClause.The return value is the
Lateralconstruct also provided by the top-levellateral()function.버전 1.1에 추가.
더 보기
LATERAL correlation - overview of usage.
-
outerjoin(right, onclause=None, full=False)¶ - inherited from the
outerjoin()method ofFromClauseReturn a
Joinfrom thisFromClauseto anotherFromClause, with the “isouter” flag set to True.E.g.:
from sqlalchemy import outerjoin j = user_table.outerjoin(address_table, user_table.c.id == address_table.c.user_id)
The above is equivalent to:
j = user_table.join( address_table, user_table.c.id == address_table.c.user_id, isouter=True)
매개 변수: - right¶ – the right side of the join; this is any
FromClauseobject such as aTableobject, and may also be a selectable-compatible object such as an ORM-mapped class. - onclause¶ – a SQL expression representing the ON clause of the
join. If left at
None,FromClause.join()will attempt to join the two tables based on a foreign key relationship. - full¶ –
if True, render a FULL OUTER JOIN, instead of LEFT OUTER JOIN.
버전 1.1에 추가.
- right¶ – the right side of the join; this is any
-
params(*optionaldict, **kwargs)¶ - inherited from the
params()method ofClauseElementReturn a copy with
bindparam()elements replaced.Returns a copy of this ClauseElement with
bindparam()elements replaced with values taken from the given dictionary:>>> clause = column('x') + bindparam('foo') >>> print clause.compile().params {'foo':None} >>> print clause.params({'foo':7}).compile().params {'foo':7}
-
primary_key¶ - inherited from the
primary_keyattribute ofFromClauseReturn the collection of Column objects which comprise the primary key of this FromClause.
-
replace_selectable(old, alias)¶ - inherited from the
replace_selectable()method ofFromClausereplace all occurrences of FromClause ‘old’ with the given Alias object, returning a copy of this
FromClause.
-
scalar(*multiparams, **params)¶ - inherited from the
scalar()method ofExecutableCompile and execute this
Executable, returning the result’s scalar representation.
-
select(whereclause=None, **params)¶ - inherited from the
select()method ofFromClausereturn a SELECT of this
FromClause.더 보기
select()- general purpose method which allows for arbitrary column lists.
-
self_group(against=None)¶ - inherited from the
self_group()method ofClauseElementApply a ‘grouping’ to this
ClauseElement.This method is overridden by subclasses to return a “grouping” construct, i.e. parenthesis. In particular it’s used by “binary” expressions to provide a grouping around themselves when placed into a larger expression, as well as by
select()constructs when placed into the FROM clause of anotherselect(). (Note that subqueries should be normally created using theSelect.alias()method, as many platforms require nested SELECT statements to be named).As expressions are composed together, the application of
self_group()is automatic - end-user code should never need to use this method directly. Note that SQLAlchemy’s clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression likex OR (y AND z)- AND takes precedence over OR.The base
self_group()method ofClauseElementjust returns self.
-
unique_params(*optionaldict, **kwargs)¶ - inherited from the
unique_params()method ofClauseElementReturn a copy with
bindparam()elements replaced.Same functionality as
params(), except adds unique=True to affected bind parameters so that multiple statements can be used.
-
