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).
Object Name | Description |
---|---|
|
Return an |
Represents an table or selectable alias (AS). |
|
Forms the basis of |
|
|
Return a new |
Represent a Common Table Expression. |
|
|
Return an |
|
Return an |
Mark a |
|
|
|
Represent an |
|
Represent an element that can be used within the |
|
Base class for SELECT statements where additional elements can be added. |
|
Mixin that declares a class to include CTE support. |
|
|
Return an |
|
Return an |
|
Produce a |
Represent a |
|
|
Return a |
Represent a LATERAL subquery. |
|
|
Return an |
|
Construct a new |
Represents a |
|
Mark a class as being selectable. |
|
Base class for SELECT statements. |
|
|
|
|
Produce a new |
Represents a minimal “table” construct. |
|
|
Return a |
Represent a TABLESAMPLE clause. |
|
Wrap a |
|
|
Return a |
|
Return a |
sqlalchemy.sql.expression.
alias
(selectable, name=None, flat=False)¶Return an Alias
object.
An Alias
represents any
FromClause
with an alternate name assigned within SQL, typically using the AS
clause when generated, e.g. SELECT * FROM table AS aliasname
.
Similar functionality is available via the
FromClause.alias()
method available on all FromClause
subclasses.
In terms of
a SELECT object as generated from the select()
function, the SelectBase.alias()
method returns an
Alias
or similar object which represents a named,
parenthesized subquery.
When an Alias
is created from a
Table
object,
this has the effect of the table being rendered
as tablename AS aliasname
in a SELECT statement.
For select()
objects, the effect is that of
creating a named subquery, i.e. (select ...) AS aliasname
.
The name
parameter 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 FromClause
subclass,
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
- see
Join.alias()
for details.
New in version 0.9.0.
sqlalchemy.sql.expression.
cte
(selectable, name=None, recursive=False)¶Return a new CTE
,
or Common Table Expression instance.
Please see HasCTE.cte()
for detail on CTE usage.
sqlalchemy.sql.expression.
except_
(*selects, **kwargs)¶Return an EXCEPT
of multiple selectables.
The returned object is an instance of
_selectable.CompoundSelect
.
sqlalchemy.sql.expression.
except_all
(*selects, **kwargs)¶Return an EXCEPT ALL
of multiple selectables.
The returned object is an instance of
_selectable.CompoundSelect
.
sqlalchemy.sql.expression.
exists
(*args, **kwargs)¶Construct a new Exists
against an existing
Select
object.
Calling styles are of the following forms:
# use on an existing select()
s = select([table.c.col1]).where(table.c.col2==5)
s_e = exists(s)
# an exists is usually used in a where of another select
# to produce a WHERE EXISTS (SELECT ... )
select([table.c.col1]).where(s_e)
# but can also be used in a select to produce a
# SELECT EXISTS (SELECT ... ) query
select([s_e])
# 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 INTERSECT
of multiple selectables.
The returned object is an instance of
_selectable.CompoundSelect
.
sqlalchemy.sql.expression.
intersect_all
(*selects, **kwargs)¶Return an INTERSECT ALL
of multiple selectables.
The returned object is an instance of
_selectable.CompoundSelect
.
sqlalchemy.sql.expression.
join
(left, right, onclause=None, isouter=False, full=False)¶Produce a Join
object, given two
FromClause
expressions.
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
FromClause
object (e.g. such as a
Table
) using
the FromClause.join()
method.
left¶ – The left side of the join.
right¶ – the right side of the join; this is any
FromClause
object such as a
Table
object, 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.
New in version 1.1.
See also
FromClause.join()
- method form,
based on a given left side.
Join
- the type of object produced.
sqlalchemy.sql.expression.
lateral
(selectable, name=None)¶Return a Lateral
object.
Lateral
is an Alias
subclass 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.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
sqlalchemy.sql.expression.
outerjoin
(left, right, onclause=None, full=False)¶Return an OUTER JOIN
clause element.
The returned object is an instance of Join
.
Similar functionality is also available via the
FromClause.outerjoin()
method on any
FromClause
.
To chain joins together, use the FromClause.join()
or
FromClause.outerjoin()
methods on the resulting
Join
object.
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 any
FromClause
.
All arguments which accept ClauseElement
arguments also
accept string arguments, which will be converted as appropriate into
either text()
or
literal_column()
constructs.
columns¶ –
A list of ColumnElement
or
FromClause
objects which will form the columns clause of the resulting
statement. For those objects that are instances of
FromClause
(typically Table
or Alias
objects), the FromClause.c
collection is extracted
to form a collection of ColumnElement
objects.
This parameter will also accept TextClause
constructs as
given, as well as ORM-mapped classes.
Note
The select.columns
parameter is not available
in the method form of select()
, e.g.
FromClause.select()
.
whereclause¶ –
A ClauseElement
expression which will be used to form the
WHERE
clause. It is typically preferable to add WHERE
criterion to an existing Select
using method chaining
with Select.where()
.
See also
from_obj¶ –
A list of ClauseElement
objects which will be added to the
FROM
clause of the resulting statement. This is equivalent
to calling Select.select_from()
using method chaining on
an existing Select
object.
See also
Select.select_from()
- full description of explicit
FROM clause specification.
autocommit¶ –
legacy autocommit parameter.
Deprecated since version 0.6: The select.autocommit
parameter is deprecated and will be removed in a future release. Please refer to the Connection.execution_options.autocommit
parameter in conjunction with the the Executable.execution_options()
method in order to affect the autocommit behavior for a statement.
bind=None¶ – an Engine
or Connection
instance
to which the
resulting Select
object will be bound. The
Select
object will otherwise automatically bind to
whatever Connectable
instances can be located within
its contained ClauseElement
members.
correlate=True¶ –
indicates that this Select
object should have its
contained FromClause
elements “correlated” to an enclosing
Select
object.
It is typically preferable to specify
correlations on an existing Select
construct using
Select.correlate()
.
See also
Select.correlate()
- full description of correlation.
distinct=False¶ –
when True
, applies a DISTINCT
qualifier 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.
distinct
is also available on an existing
Select
object via the Select.distinct()
method.
See also
for_update=False¶ –
when
True
, appliesFOR UPDATE
to the end of the resulting statement.
for_update
accepts 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
.
See also
Select.with_for_update()
- improved API for
specifying the FOR UPDATE
clause.
group_by¶ –
a list of ClauseElement
objects which will comprise the
GROUP BY
clause of the resulting select. This parameter
is typically specified more naturally using the
Select.group_by()
method on an existing
Select
.
See also
having¶ –
a ClauseElement
that will comprise the HAVING
clause
of the resulting select when GROUP BY
is used. This parameter
is typically specified more naturally using the
Select.having()
method on an existing
Select
.
See also
limit=None¶ –
a numerical value which usually renders as a LIMIT
expression in the resulting select. Backends that don’t
support LIMIT
will attempt to provide similar
functionality. This parameter is typically specified more
naturally using the Select.limit()
method on an existing
Select
.
See also
offset=None¶ –
a numeric value which usually renders as an OFFSET
expression in the resulting select. Backends that don’t
support OFFSET
will attempt to provide similar
functionality. This parameter is typically specified more naturally
using the Select.offset()
method on an existing
Select
.
See also
order_by¶ –
a scalar or list of ClauseElement
objects which will
comprise the ORDER BY
clause of the resulting select.
This parameter is typically specified more naturally using the
Select.order_by()
method on an existing
Select
.
See also
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 resulting Select
object will use these
names as well for targeting column members.
This parameter can also be specified on an existing
Select
object using the
Select.apply_labels()
method.
See also
sqlalchemy.sql.expression.
subquery
(alias, *args, **kwargs)¶sqlalchemy.sql.expression.
table
(name, *columns, **kw)¶Produce a new TableClause
.
The object returned is an instance of
TableClause
, which
represents the “syntactical” portion of the schema-level
Table
object.
It may be used to construct lightweight table constructs.
Changed in version 1.0.0: table()
can now
be imported from the plain sqlalchemy
namespace like any
other SQL element.
sqlalchemy.sql.expression.
tablesample
(selectable, sampling, name=None, seed=None)¶Return a TableSample
object.
TableSample
is an Alias
subclass that represents
a table with the TABLESAMPLE clause applied to it.
tablesample()
is also available from the FromClause
class via the
FromClause.tablesample()
method.
The TABLESAMPLE clause allows selecting a randomly selected approximate percentage of rows from a table. It supports multiple sampling methods, most commonly BERNOULLI and SYSTEM.
e.g.:
from sqlalchemy import func
selectable = people.tablesample(
func.bernoulli(1),
name='alias',
seed=func.random())
stmt = select([selectable.c.people_id])
Assuming people
with a column people_id
, the above
statement would render as:
SELECT alias.people_id FROM
people AS alias TABLESAMPLE bernoulli(:bernoulli_1)
REPEATABLE (random())
New in version 1.1.
sqlalchemy.sql.expression.
union
(*selects, **kwargs)¶Return a UNION
of multiple selectables.
The returned object is an instance of
_selectable.CompoundSelect
.
A similar union()
method is available on all
FromClause
subclasses.
sqlalchemy.sql.expression.
union_all
(*selects, **kwargs)¶Return a UNION ALL
of multiple selectables.
The returned object is an instance of
_selectable.CompoundSelect
.
A similar union_all()
method is available on all
FromClause
subclasses.
sqlalchemy.sql.expression.
Alias
(*arg, **kw)¶Represents an table or selectable alias (AS).
Represents an alias, as typically applied to any table or
sub-select within a SQL statement using the AS
keyword (or
without the keyword on certain databases such as Oracle).
This object is constructed from the alias()
module
level function as well as the FromClause.alias()
method available
on all FromClause
subclasses.
Class signature
class sqlalchemy.sql.expression.Alias
(sqlalchemy.sql.expression.FromClause
)
sqlalchemy.sql.expression.Alias.
alias
(name=None, flat=False)¶inherited from the FromClause.alias()
method of FromClause
Return an alias of this FromClause
.
E.g.:
a2 = some_table.alias('a2')
The above code creates an Alias
object which can be used
as a FROM clause in any SELECT statement.
sqlalchemy.sql.expression.Alias.
c
¶inherited from the FromClause.c
attribute of FromClause
An alias for the columns
attribute.
sqlalchemy.sql.expression.Alias.
columns
¶inherited from the FromClause.columns
attribute of FromClause
A named-based collection of ColumnElement
objects
maintained by this FromClause
.
The columns
, or c
collection, is the gateway
to the construction of SQL expressions using table-bound or
other selectable-bound columns:
select([mytable]).where(mytable.c.somecolumn == 5)
sqlalchemy.sql.expression.Alias.
compare
(other, **kw)¶inherited from the ClauseElement.compare()
method of ClauseElement
Compare 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
).
sqlalchemy.sql.expression.Alias.
compile
(default, bind=None, dialect=None, **kw)¶inherited from the ClauseElement.compile()
method of ClauseElement
Compile this SQL expression.
The return value is a Compiled
object.
Calling str()
or unicode()
on the returned value will yield a
string representation of the result. The
Compiled
object also can return a
dictionary of bind parameter names and values
using the params
accessor.
bind¶ – An Engine
or Connection
from which a
Compiled
will be acquired. This argument takes precedence over
this ClauseElement
’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 Dialect
instance from which a Compiled
will be acquired. This argument takes precedence over the bind
argument as well as this ClauseElement
‘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_binds
flag 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}))
New in version 0.9.0.
sqlalchemy.sql.expression.Alias.
correspond_on_equivalents
(column, equivalents)¶inherited from the FromClause.correspond_on_equivalents()
method of FromClause
Return corresponding_column for the given column, or if None search for a match in the given dictionary.
sqlalchemy.sql.expression.Alias.
corresponding_column
(column, require_embedded=False)¶inherited from the FromClause.corresponding_column()
method of FromClause
Given a ColumnElement
, return the exported
ColumnElement
object from this
expression.Selectable
which corresponds to that original
Column
via a common ancestor
column.
column¶ – the target ColumnElement
to be matched
require_embedded¶ – only return corresponding columns for
the given ColumnElement
, if the given
ColumnElement
is actually present within a sub-element
of this FromClause
.
Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this FromClause
.
sqlalchemy.sql.expression.Alias.
count
(functions, whereclause=None, **params)¶inherited from the FromClause.count()
method of FromClause
Return a SELECT COUNT generated against this
FromClause
.
Deprecated since version 1.1: The FromClause.count()
method is deprecated, and will be removed in a future release. Please use the count
function available from the func
namespace.
See also
sqlalchemy.sql.expression.Alias.
description
¶sqlalchemy.sql.expression.Alias.
foreign_keys
¶inherited from the FromClause.foreign_keys
attribute of FromClause
Return the collection of ForeignKey
objects
which this FromClause references.
sqlalchemy.sql.expression.Alias.
get_children
(column_collections=True, **kw)¶Return 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).
sqlalchemy.sql.expression.Alias.
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.
sqlalchemy.sql.expression.Alias.
join
(right, onclause=None, isouter=False, full=False)¶inherited from the FromClause.join()
method of FromClause
Return a Join
from this
FromClause
to another
FromClause
.
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
FromClause
object such as a
Table
object, 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
.
New in version 1.1.
sqlalchemy.sql.expression.Alias.
lateral
(name=None)¶inherited from the FromClause.lateral()
method of FromClause
Return a LATERAL alias of this FromClause
.
The return value is the Lateral
construct also
provided by the top-level lateral()
function.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
sqlalchemy.sql.expression.Alias.
outerjoin
(right, onclause=None, full=False)¶inherited from the FromClause.outerjoin()
method of FromClause
Return a Join
from this
FromClause
to another FromClause
, 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
FromClause
object such as a
Table
object, 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.
New in version 1.1.
sqlalchemy.sql.expression.Alias.
params
(*optionaldict, **kwargs)¶inherited from the ClauseElement.params()
method of ClauseElement
Return 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}
sqlalchemy.sql.expression.Alias.
primary_key
¶inherited from the FromClause.primary_key
attribute of FromClause
Return the collection of Column
objects
which comprise the primary key of this FromClause.
sqlalchemy.sql.expression.Alias.
replace_selectable
(sqlutil, old, alias)¶inherited from the FromClause.replace_selectable()
method of FromClause
Replace all occurrences of FromClause ‘old’ with the given Alias
object, returning a copy of this FromClause
.
sqlalchemy.sql.expression.Alias.
select
(whereclause=None, **params)¶inherited from the FromClause.select()
method of FromClause
Return a SELECT of this FromClause
.
See also
select()
- general purpose
method which allows for arbitrary column lists.
sqlalchemy.sql.expression.Alias.
self_group
(against=None)¶Apply 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 another
select()
. (Note that subqueries should be
normally created using the Select.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 like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
sqlalchemy.sql.expression.Alias.
tablesample
(sampling, name=None, seed=None)¶inherited from the FromClause.tablesample()
method of FromClause
Return a TABLESAMPLE alias of this FromClause
.
The return value is the TableSample
construct also
provided by the top-level tablesample()
function.
New in version 1.1.
See also
tablesample()
- usage guidelines and parameters
sqlalchemy.sql.expression.Alias.
unique_params
(*optionaldict, **kwargs)¶inherited from the ClauseElement.unique_params()
method of ClauseElement
Return a copy with bindparam()
elements
replaced.
Same functionality as ClauseElement.params()
,
except adds unique=True
to affected bind parameters so that multiple statements can be
used.
sqlalchemy.sql.expression.
CompoundSelect
(keyword, *selects, **kwargs)¶Forms the basis of UNION
, UNION ALL
, and other
SELECT-based set operations.
Class signature
class sqlalchemy.sql.expression.CompoundSelect
(sqlalchemy.sql.expression.GenerativeSelect
)
sqlalchemy.sql.expression.CompoundSelect.
alias
(name=None, flat=False)¶inherited from the FromClause.alias()
method of FromClause
Return an alias of this FromClause
.
E.g.:
a2 = some_table.alias('a2')
The above code creates an Alias
object which can be used
as a FROM clause in any SELECT statement.
sqlalchemy.sql.expression.CompoundSelect.
append_group_by
(*clauses)¶inherited from the GenerativeSelect.append_group_by()
method of GenerativeSelect
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
GenerativeSelect.group_by()
method is preferred,
as it provides standard method chaining.
See also
sqlalchemy.sql.expression.CompoundSelect.
append_order_by
(*clauses)¶inherited from the GenerativeSelect.append_order_by()
method of GenerativeSelect
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
GenerativeSelect.order_by()
method is preferred,
as it
provides standard method chaining.
See also
sqlalchemy.sql.expression.CompoundSelect.
apply_labels
()¶inherited from the GenerativeSelect.apply_labels()
method of GenerativeSelect
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.
sqlalchemy.sql.expression.CompoundSelect.
as_scalar
()¶inherited from the SelectBase.as_scalar()
method of SelectBase
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
.
sqlalchemy.sql.expression.CompoundSelect.
autocommit
()¶inherited from the SelectBase.autocommit()
method of SelectBase
Return a new selectable with the ‘autocommit’ flag set to True.
Deprecated since version 0.6: The SelectBase.autocommit()
method is deprecated, and will be removed in a future release. Please use the the Connection.execution_options.autocommit
parameter in conjunction with the Executable.execution_options()
method.
sqlalchemy.sql.expression.CompoundSelect.
bind
¶sqlalchemy.sql.expression.CompoundSelect.
c
¶inherited from the FromClause.c
attribute of FromClause
An alias for the columns
attribute.
sqlalchemy.sql.expression.CompoundSelect.
columns
¶inherited from the FromClause.columns
attribute of FromClause
A named-based collection of ColumnElement
objects
maintained by this FromClause
.
The columns
, or c
collection, is the gateway
to the construction of SQL expressions using table-bound or
other selectable-bound columns:
select([mytable]).where(mytable.c.somecolumn == 5)
sqlalchemy.sql.expression.CompoundSelect.
compare
(other, **kw)¶inherited from the ClauseElement.compare()
method of ClauseElement
Compare 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
).
sqlalchemy.sql.expression.CompoundSelect.
compile
(default, bind=None, dialect=None, **kw)¶inherited from the ClauseElement.compile()
method of ClauseElement
Compile this SQL expression.
The return value is a Compiled
object.
Calling str()
or unicode()
on the returned value will yield a
string representation of the result. The
Compiled
object also can return a
dictionary of bind parameter names and values
using the params
accessor.
bind¶ – An Engine
or Connection
from which a
Compiled
will be acquired. This argument takes precedence over
this ClauseElement
’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 Dialect
instance from which a Compiled
will be acquired. This argument takes precedence over the bind
argument as well as this ClauseElement
‘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_binds
flag 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}))
New in version 0.9.0.
sqlalchemy.sql.expression.CompoundSelect.
correspond_on_equivalents
(column, equivalents)¶inherited from the FromClause.correspond_on_equivalents()
method of FromClause
Return corresponding_column for the given column, or if None search for a match in the given dictionary.
sqlalchemy.sql.expression.CompoundSelect.
corresponding_column
(column, require_embedded=False)¶inherited from the FromClause.corresponding_column()
method of FromClause
Given a ColumnElement
, return the exported
ColumnElement
object from this
expression.Selectable
which corresponds to that original
Column
via a common ancestor
column.
column¶ – the target ColumnElement
to be matched
require_embedded¶ – only return corresponding columns for
the given ColumnElement
, if the given
ColumnElement
is actually present within a sub-element
of this FromClause
.
Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this FromClause
.
sqlalchemy.sql.expression.CompoundSelect.
count
(functions, whereclause=None, **params)¶inherited from the FromClause.count()
method of FromClause
Return a SELECT COUNT generated against this
FromClause
.
Deprecated since version 1.1: The FromClause.count()
method is deprecated, and will be removed in a future release. Please use the count
function available from the func
namespace.
See also
sqlalchemy.sql.expression.CompoundSelect.
cte
(name=None, recursive=False)¶inherited from the HasCTE.cte()
method of HasCTE
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.
Changed in version 1.1: Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE.
SQLAlchemy detects CTE
objects, which are treated
similarly to Alias
objects, 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.
For special prefixes such as PostgreSQL “MATERIALIZED” and
“NOT MATERIALIZED”, the CTE.prefix_with()
method may be
used to establish these.
Changed in version 1.3.13: Added support for prefixes. In particular - MATERIALIZED and NOT MATERIALIZED.
name¶ – name given to the common table expression. Like
FromClause.alias()
, the name can be left as
None
in which case an anonymous symbol will be used at query
compile time.
recursive¶ – if True
, will render WITH 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:
from datetime import date
from sqlalchemy import (MetaData, Table, Column, Integer,
Date, select, literal, and_, exists)
metadata = MetaData()
visitors = Table('visitors', metadata,
Column('product_id', Integer, primary_key=True),
Column('date', Date, primary_key=True),
Column('count', Integer),
)
# add 5 visitors for the product_id == 1
product_id = 1
day = date.today()
count = 5
update_cte = (
visitors.update()
.where(and_(visitors.c.product_id == product_id,
visitors.c.date == day))
.values(count=visitors.c.count + count)
.returning(literal(1))
.cte('update_cte')
)
upsert = visitors.insert().from_select(
[visitors.c.product_id, visitors.c.date, visitors.c.count],
select([literal(product_id), literal(day), literal(count)])
.where(~exists(update_cte.select()))
)
connection.execute(upsert)
See also
Query.cte()
- ORM version of
HasCTE.cte()
.
sqlalchemy.sql.expression.CompoundSelect.
description
¶inherited from the FromClause.description
attribute of FromClause
A brief description of this FromClause
.
Used primarily for error message formatting.
sqlalchemy.sql.expression.CompoundSelect.
execute
(*multiparams, **params)¶inherited from the Executable.execute()
method of Executable
Compile and execute this Executable
.
sqlalchemy.sql.expression.CompoundSelect.
execution_options
(**kw)¶inherited from the Executable.execution_options()
method of Executable
Set non-SQL options for the statement which take effect during execution.
Execution options can be set on a per-statement or
per Connection
basis. Additionally, the
Engine
and ORM Query
objects 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.
sqlalchemy.sql.expression.CompoundSelect.
for_update
¶inherited from the GenerativeSelect.for_update
attribute of GenerativeSelect
Provide legacy dialect support for the for_update
attribute.
sqlalchemy.sql.expression.CompoundSelect.
foreign_keys
¶inherited from the FromClause.foreign_keys
attribute of FromClause
Return the collection of ForeignKey
objects
which this FromClause references.
sqlalchemy.sql.expression.CompoundSelect.
get_children
(column_collections=True, **kwargs)¶Return 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).
sqlalchemy.sql.expression.CompoundSelect.
get_execution_options
()¶inherited from the Executable.get_execution_options()
method of Executable
Get the non-SQL options which will take effect during execution.
New in version 1.3.
See also
sqlalchemy.sql.expression.CompoundSelect.
group_by
(*clauses)¶inherited from the GenerativeSelect.group_by()
method of GenerativeSelect
Return a new selectable with the given list of GROUP BY criterion applied.
e.g.:
stmt = select([table.c.name, func.max(table.c.stat)]).\
group_by(table.c.name)
*clauses¶ – a series of ColumnElement
constructs
which will be used to generate an GROUP BY clause.
sqlalchemy.sql.expression.CompoundSelect.
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.
sqlalchemy.sql.expression.CompoundSelect.
join
(right, onclause=None, isouter=False, full=False)¶inherited from the FromClause.join()
method of FromClause
Return a Join
from this
FromClause
to another
FromClause
.
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
FromClause
object such as a
Table
object, 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
.
New in version 1.1.
sqlalchemy.sql.expression.CompoundSelect.
label
(name)¶inherited from the SelectBase.label()
method of SelectBase
Return a ‘scalar’ representation of this selectable, embedded as a subquery with a label.
See also
sqlalchemy.sql.expression.CompoundSelect.
lateral
(name=None)¶inherited from the FromClause.lateral()
method of FromClause
Return a LATERAL alias of this FromClause
.
The return value is the Lateral
construct also
provided by the top-level lateral()
function.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
sqlalchemy.sql.expression.CompoundSelect.
limit
(limit)¶inherited from the GenerativeSelect.limit()
method of GenerativeSelect
Return a new selectable with the given LIMIT criterion applied.
This is a numerical value which usually renders as a LIMIT
expression in the resulting select. Backends that don’t
support LIMIT
will attempt to provide similar
functionality.
Changed in version 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.
sqlalchemy.sql.expression.CompoundSelect.
offset
(offset)¶inherited from the GenerativeSelect.offset()
method of GenerativeSelect
Return a new selectable with the given OFFSET criterion applied.
This is a numeric value which usually renders as an OFFSET
expression in the resulting select. Backends that don’t
support OFFSET
will attempt to provide similar
functionality.
Changed in version 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.
sqlalchemy.sql.expression.CompoundSelect.
order_by
(*clauses)¶inherited from the GenerativeSelect.order_by()
method of GenerativeSelect
Return a new selectable with the given list of ORDER BY criterion applied.
e.g.:
stmt = select([table]).order_by(table.c.id, table.c.name)
*clauses¶ – a series of ColumnElement
constructs
which will be used to generate an ORDER BY clause.
sqlalchemy.sql.expression.CompoundSelect.
outerjoin
(right, onclause=None, full=False)¶inherited from the FromClause.outerjoin()
method of FromClause
Return a Join
from this
FromClause
to another FromClause
, 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
FromClause
object such as a
Table
object, 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.
New in version 1.1.
sqlalchemy.sql.expression.CompoundSelect.
params
(*optionaldict, **kwargs)¶inherited from the ClauseElement.params()
method of ClauseElement
Return 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}
sqlalchemy.sql.expression.CompoundSelect.
primary_key
¶inherited from the FromClause.primary_key
attribute of FromClause
Return the collection of Column
objects
which comprise the primary key of this FromClause.
sqlalchemy.sql.expression.CompoundSelect.
replace_selectable
(sqlutil, old, alias)¶inherited from the FromClause.replace_selectable()
method of FromClause
Replace all occurrences of FromClause ‘old’ with the given Alias
object, returning a copy of this FromClause
.
sqlalchemy.sql.expression.CompoundSelect.
scalar
(*multiparams, **params)¶inherited from the Executable.scalar()
method of Executable
Compile and execute this Executable
, returning the
result’s scalar representation.
sqlalchemy.sql.expression.CompoundSelect.
select
(whereclause=None, **params)¶inherited from the FromClause.select()
method of FromClause
Return a SELECT of this FromClause
.
See also
select()
- general purpose
method which allows for arbitrary column lists.
sqlalchemy.sql.expression.CompoundSelect.
self_group
(against=None)¶Apply 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 another
select()
. (Note that subqueries should be
normally created using the Select.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 like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
sqlalchemy.sql.expression.CompoundSelect.
tablesample
(sampling, name=None, seed=None)¶inherited from the FromClause.tablesample()
method of FromClause
Return a TABLESAMPLE alias of this FromClause
.
The return value is the TableSample
construct also
provided by the top-level tablesample()
function.
New in version 1.1.
See also
tablesample()
- usage guidelines and parameters
sqlalchemy.sql.expression.CompoundSelect.
unique_params
(*optionaldict, **kwargs)¶inherited from the ClauseElement.unique_params()
method of ClauseElement
Return a copy with bindparam()
elements
replaced.
Same functionality as ClauseElement.params()
,
except adds unique=True
to affected bind parameters so that multiple statements can be
used.
sqlalchemy.sql.expression.CompoundSelect.
with_for_update
(nowait=False, read=False, of=None, skip_locked=False, key_share=False)¶inherited from the GenerativeSelect.with_for_update()
method of GenerativeSelect
Specify a FOR UPDATE
clause for this
GenerativeSelect
.
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 nowait
option 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 NOWAIT
on Oracle
and PostgreSQL dialects.
read¶ – boolean; will render LOCK IN SHARE MODE
on MySQL,
FOR SHARE
on PostgreSQL. On PostgreSQL, when combined with
nowait
, will render FOR SHARE NOWAIT
.
of¶ – SQL expression or list of SQL expression elements
(typically Column
objects or a compatible expression) which
will render into a FOR UPDATE OF
clause; supported by PostgreSQL
and Oracle. May render as a table or as a column depending on
backend.
skip_locked¶ –
boolean, will render FOR UPDATE SKIP LOCKED
on Oracle and PostgreSQL dialects or FOR SHARE SKIP LOCKED
if
read=True
is also specified.
New in version 1.1.0.
key_share¶ –
boolean, will render FOR NO KEY UPDATE
,
or if combined with read=True
will render FOR KEY SHARE
,
on the PostgreSQL dialect.
New in version 1.1.0.
sqlalchemy.sql.expression.
CTE
(*arg, **kw)¶Represent a Common Table Expression.
The CTE
object is obtained using the
SelectBase.cte()
method from any selectable.
See that method for complete examples.
Class signature
class sqlalchemy.sql.expression.CTE
(sqlalchemy.sql.expression.Generative
, sqlalchemy.sql.expression.HasPrefixes
, sqlalchemy.sql.expression.HasSuffixes
, sqlalchemy.sql.expression.Alias
)
sqlalchemy.sql.expression.CTE.
alias
(name=None, flat=False)¶This method is a CTE-specific specialization of the
FromClause.alias()
method.
sqlalchemy.sql.expression.CTE.
c
¶inherited from the FromClause.c
attribute of FromClause
An alias for the columns
attribute.
sqlalchemy.sql.expression.CTE.
columns
¶inherited from the FromClause.columns
attribute of FromClause
A named-based collection of ColumnElement
objects
maintained by this FromClause
.
The columns
, or c
collection, is the gateway
to the construction of SQL expressions using table-bound or
other selectable-bound columns:
select([mytable]).where(mytable.c.somecolumn == 5)
sqlalchemy.sql.expression.CTE.
compare
(other, **kw)¶inherited from the ClauseElement.compare()
method of ClauseElement
Compare 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
).
sqlalchemy.sql.expression.CTE.
compile
(default, bind=None, dialect=None, **kw)¶inherited from the ClauseElement.compile()
method of ClauseElement
Compile this SQL expression.
The return value is a Compiled
object.
Calling str()
or unicode()
on the returned value will yield a
string representation of the result. The
Compiled
object also can return a
dictionary of bind parameter names and values
using the params
accessor.
bind¶ – An Engine
or Connection
from which a
Compiled
will be acquired. This argument takes precedence over
this ClauseElement
’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 Dialect
instance from which a Compiled
will be acquired. This argument takes precedence over the bind
argument as well as this ClauseElement
‘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_binds
flag 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}))
New in version 0.9.0.
sqlalchemy.sql.expression.CTE.
correspond_on_equivalents
(column, equivalents)¶inherited from the FromClause.correspond_on_equivalents()
method of FromClause
Return corresponding_column for the given column, or if None search for a match in the given dictionary.
sqlalchemy.sql.expression.CTE.
corresponding_column
(column, require_embedded=False)¶inherited from the FromClause.corresponding_column()
method of FromClause
Given a ColumnElement
, return the exported
ColumnElement
object from this
expression.Selectable
which corresponds to that original
Column
via a common ancestor
column.
column¶ – the target ColumnElement
to be matched
require_embedded¶ – only return corresponding columns for
the given ColumnElement
, if the given
ColumnElement
is actually present within a sub-element
of this FromClause
.
Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this FromClause
.
sqlalchemy.sql.expression.CTE.
count
(functions, whereclause=None, **params)¶inherited from the FromClause.count()
method of FromClause
Return a SELECT COUNT generated against this
FromClause
.
Deprecated since version 1.1: The FromClause.count()
method is deprecated, and will be removed in a future release. Please use the count
function available from the func
namespace.
See also
sqlalchemy.sql.expression.CTE.
description
¶inherited from the Alias.description
attribute of Alias
sqlalchemy.sql.expression.CTE.
foreign_keys
¶inherited from the FromClause.foreign_keys
attribute of FromClause
Return the collection of ForeignKey
objects
which this FromClause references.
sqlalchemy.sql.expression.CTE.
get_children
(column_collections=True, **kw)¶inherited from the Alias.get_children()
method of Alias
Return 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).
sqlalchemy.sql.expression.CTE.
is_derived_from
(fromclause)¶inherited from the Alias.is_derived_from()
method of Alias
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.
sqlalchemy.sql.expression.CTE.
join
(right, onclause=None, isouter=False, full=False)¶inherited from the FromClause.join()
method of FromClause
Return a Join
from this
FromClause
to another
FromClause
.
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
FromClause
object such as a
Table
object, 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
.
New in version 1.1.
sqlalchemy.sql.expression.CTE.
lateral
(name=None)¶inherited from the FromClause.lateral()
method of FromClause
Return a LATERAL alias of this FromClause
.
The return value is the Lateral
construct also
provided by the top-level lateral()
function.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
sqlalchemy.sql.expression.CTE.
outerjoin
(right, onclause=None, full=False)¶inherited from the FromClause.outerjoin()
method of FromClause
Return a Join
from this
FromClause
to another FromClause
, 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
FromClause
object such as a
Table
object, 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.
New in version 1.1.
sqlalchemy.sql.expression.CTE.
params
(*optionaldict, **kwargs)¶inherited from the ClauseElement.params()
method of ClauseElement
Return 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}
sqlalchemy.sql.expression.CTE.
prefix_with
(*expr, **kw)¶inherited from the HasPrefixes.prefix_with()
method of HasPrefixes
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")
# MySQL 5.7 optimizer hints
stmt = select([table]).prefix_with(
"/*+ BKA(t1) */", dialect="mysql")
Multiple prefixes can be specified by multiple calls
to HasPrefixes.prefix_with()
.
*expr¶ –
textual or ClauseElement
construct which
will be rendered following the INSERT, UPDATE, or DELETE
keyword.
Warning
The HasPrefixes.prefix_with.*expr
argument to HasPrefixes.prefix_with()
can be passed as a Python string argument, which will be treated as trusted SQL text and rendered as given. DO NOT PASS UNTRUSTED INPUT TO THIS PARAMETER.
**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.
sqlalchemy.sql.expression.CTE.
primary_key
¶inherited from the FromClause.primary_key
attribute of FromClause
Return the collection of Column
objects
which comprise the primary key of this FromClause.
sqlalchemy.sql.expression.CTE.
replace_selectable
(sqlutil, old, alias)¶inherited from the FromClause.replace_selectable()
method of FromClause
Replace all occurrences of FromClause ‘old’ with the given Alias
object, returning a copy of this FromClause
.
sqlalchemy.sql.expression.CTE.
select
(whereclause=None, **params)¶inherited from the FromClause.select()
method of FromClause
Return a SELECT of this FromClause
.
See also
select()
- general purpose
method which allows for arbitrary column lists.
sqlalchemy.sql.expression.CTE.
self_group
(against=None)¶inherited from the Alias.self_group()
method of Alias
Apply 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 another
select()
. (Note that subqueries should be
normally created using the Select.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 like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
sqlalchemy.sql.expression.CTE.
suffix_with
(*expr, **kw)¶inherited from the HasSuffixes.suffix_with()
method of HasSuffixes
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 HasSuffixes.suffix_with()
.
*expr¶ –
textual or ClauseElement
construct which
will be rendered following the target clause.
Warning
The HasSuffixes.suffix_with.*expr
argument to HasSuffixes.suffix_with()
can be passed as a Python string argument, which will be treated as trusted SQL text and rendered as given. DO NOT PASS UNTRUSTED INPUT TO THIS PARAMETER.
**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.
sqlalchemy.sql.expression.CTE.
tablesample
(sampling, name=None, seed=None)¶inherited from the FromClause.tablesample()
method of FromClause
Return a TABLESAMPLE alias of this FromClause
.
The return value is the TableSample
construct also
provided by the top-level tablesample()
function.
New in version 1.1.
See also
tablesample()
- usage guidelines and parameters
sqlalchemy.sql.expression.CTE.
unique_params
(*optionaldict, **kwargs)¶inherited from the ClauseElement.unique_params()
method of ClauseElement
Return a copy with bindparam()
elements
replaced.
Same functionality as ClauseElement.params()
,
except adds unique=True
to affected bind parameters so that multiple statements can be
used.
sqlalchemy.sql.expression.
Executable
¶Mark a ClauseElement
as supporting execution.
Executable
is a superclass for all “statement” types
of objects, including select()
, delete()
, update()
,
insert()
, text()
.
Class signature
class sqlalchemy.sql.expression.Executable
(sqlalchemy.sql.expression.Generative
)
sqlalchemy.sql.expression.Executable.
bind
¶Returns the Engine
or Connection
to which this Executable
is 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.
sqlalchemy.sql.expression.Executable.
execute
(*multiparams, **params)¶Compile and execute this Executable
.
sqlalchemy.sql.expression.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 Connection
basis. Additionally, the
Engine
and ORM Query
objects 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.
sqlalchemy.sql.expression.Executable.
get_execution_options
()¶Get the non-SQL options which will take effect during execution.
New in version 1.3.
See also
sqlalchemy.sql.expression.Executable.
scalar
(*multiparams, **params)¶Compile and execute this Executable
, returning the
result’s scalar representation.
sqlalchemy.sql.expression.
Exists
(*args, **kwargs)¶Represent an EXISTS
clause.
Class signature
class sqlalchemy.sql.expression.Exists
(sqlalchemy.sql.expression.UnaryExpression
)
sqlalchemy.sql.expression.Exists.
__init__
(*args, **kwargs)¶Construct a new Exists
object.
This constructor is mirrored as a public API function; see sqlalchemy.sql.expression.exists()
for a full usage and argument description.
sqlalchemy.sql.expression.Exists.
select_from
(clause)¶Return a new Exists
construct,
applying the given
expression to the Select.select_from()
method of the select
statement contained.
sqlalchemy.sql.expression.Exists.
where
(clause)¶Return a new exists()
construct with the
given expression added to
its WHERE clause, joined to the existing clause via AND, if any.
sqlalchemy.sql.expression.
FromClause
¶Represent an element that can be used within the FROM
clause of a SELECT
statement.
The most common forms of FromClause
are the
Table
and the select()
constructs. Key
features common to all FromClause
objects include:
a c
collection, which provides per-name access to a collection
of ColumnElement
objects.
a primary_key
attribute, which is a collection of all those
ColumnElement
objects that indicate the primary_key
flag.
Methods to generate various derivations of a “from” clause, including
FromClause.alias()
,
FromClause.join()
,
FromClause.select()
.
Class signature
class sqlalchemy.sql.expression.FromClause
(sqlalchemy.sql.expression.Selectable
)
sqlalchemy.sql.expression.FromClause.
alias
(name=None, flat=False)¶Return an alias of this FromClause
.
E.g.:
a2 = some_table.alias('a2')
The above code creates an Alias
object which can be used
as a FROM clause in any SELECT statement.
sqlalchemy.sql.expression.FromClause.
c
¶An alias for the columns
attribute.
sqlalchemy.sql.expression.FromClause.
columns
¶A named-based collection of ColumnElement
objects
maintained by this FromClause
.
The columns
, or c
collection, is the gateway
to the construction of SQL expressions using table-bound or
other selectable-bound columns:
select([mytable]).where(mytable.c.somecolumn == 5)
sqlalchemy.sql.expression.FromClause.
correspond_on_equivalents
(column, equivalents)¶Return corresponding_column for the given column, or if None search for a match in the given dictionary.
sqlalchemy.sql.expression.FromClause.
corresponding_column
(column, require_embedded=False)¶Given a ColumnElement
, return the exported
ColumnElement
object from this
expression.Selectable
which corresponds to that original
Column
via a common ancestor
column.
column¶ – the target ColumnElement
to be matched
require_embedded¶ – only return corresponding columns for
the given ColumnElement
, if the given
ColumnElement
is actually present within a sub-element
of this FromClause
.
Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this FromClause
.
sqlalchemy.sql.expression.FromClause.
count
(functions, whereclause=None, **params)¶Return a SELECT COUNT generated against this
FromClause
.
Deprecated since version 1.1: The FromClause.count()
method is deprecated, and will be removed in a future release. Please use the count
function available from the func
namespace.
See also
sqlalchemy.sql.expression.FromClause.
description
¶A brief description of this FromClause
.
Used primarily for error message formatting.
sqlalchemy.sql.expression.FromClause.
foreign_keys
¶Return the collection of ForeignKey
objects
which this FromClause references.
sqlalchemy.sql.expression.FromClause.
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.
sqlalchemy.sql.expression.FromClause.
join
(right, onclause=None, isouter=False, full=False)¶Return a Join
from this
FromClause
to another
FromClause
.
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
FromClause
object such as a
Table
object, 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
.
New in version 1.1.
sqlalchemy.sql.expression.FromClause.
lateral
(name=None)¶Return a LATERAL alias of this FromClause
.
The return value is the Lateral
construct also
provided by the top-level lateral()
function.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
sqlalchemy.sql.expression.FromClause.
outerjoin
(right, onclause=None, full=False)¶Return a Join
from this
FromClause
to another FromClause
, 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
FromClause
object such as a
Table
object, 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.
New in version 1.1.
sqlalchemy.sql.expression.FromClause.
primary_key
¶Return the collection of Column
objects
which comprise the primary key of this FromClause.
sqlalchemy.sql.expression.FromClause.
replace_selectable
(sqlutil, old, alias)¶Replace all occurrences of FromClause ‘old’ with the given Alias
object, returning a copy of this FromClause
.
sqlalchemy.sql.expression.FromClause.
schema
= None¶Define the ‘schema’ attribute for this FromClause
.
This is typically None
for most objects except that of
Table
, where it is taken as the value of the
Table.schema
argument.
sqlalchemy.sql.expression.FromClause.
select
(whereclause=None, **params)¶Return a SELECT of this FromClause
.
See also
select()
- general purpose
method which allows for arbitrary column lists.
sqlalchemy.sql.expression.FromClause.
tablesample
(sampling, name=None, seed=None)¶Return a TABLESAMPLE alias of this FromClause
.
The return value is the TableSample
construct also
provided by the top-level tablesample()
function.
New in version 1.1.
See also
tablesample()
- usage guidelines and parameters
sqlalchemy.sql.expression.
GenerativeSelect
(use_labels=False, for_update=False, limit=None, offset=None, order_by=None, group_by=None, bind=None, autocommit=None)¶Base class for SELECT statements where additional elements can be added.
This serves as the base for Select
and
_selectable.CompoundSelect
where elements such as ORDER BY, GROUP BY can be added and column
rendering can be controlled. Compare to TextAsFrom
, which,
while it subclasses SelectBase
and is also a SELECT construct,
represents a fixed textual string which cannot be altered at this level,
only wrapped as a subquery.
New in version 0.9.0: GenerativeSelect
was added to
provide functionality specific to Select
and
_selectable.CompoundSelect
while allowing
SelectBase
to be
used for other SELECT-like objects, e.g. TextAsFrom
.
Class signature
class sqlalchemy.sql.expression.GenerativeSelect
(sqlalchemy.sql.expression.SelectBase
)
sqlalchemy.sql.expression.GenerativeSelect.
alias
(name=None, flat=False)¶inherited from the FromClause.alias()
method of FromClause
Return an alias of this FromClause
.
E.g.:
a2 = some_table.alias('a2')
The above code creates an Alias
object which can be used
as a FROM clause in any SELECT statement.
sqlalchemy.sql.expression.GenerativeSelect.
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
GenerativeSelect.group_by()
method is preferred,
as it provides standard method chaining.
See also
sqlalchemy.sql.expression.GenerativeSelect.
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
GenerativeSelect.order_by()
method is preferred,
as it
provides standard method chaining.
See also
sqlalchemy.sql.expression.GenerativeSelect.
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.
sqlalchemy.sql.expression.GenerativeSelect.
as_scalar
()¶inherited from the SelectBase.as_scalar()
method of SelectBase
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
.
sqlalchemy.sql.expression.GenerativeSelect.
autocommit
()¶inherited from the SelectBase.autocommit()
method of SelectBase
Return a new selectable with the ‘autocommit’ flag set to True.
Deprecated since version 0.6: The SelectBase.autocommit()
method is deprecated, and will be removed in a future release. Please use the the Connection.execution_options.autocommit
parameter in conjunction with the Executable.execution_options()
method.
sqlalchemy.sql.expression.GenerativeSelect.
bind
¶inherited from the Executable.bind
attribute of Executable
Returns the Engine
or Connection
to which this Executable
is 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.
sqlalchemy.sql.expression.GenerativeSelect.
c
¶inherited from the FromClause.c
attribute of FromClause
An alias for the columns
attribute.
sqlalchemy.sql.expression.GenerativeSelect.
columns
¶inherited from the FromClause.columns
attribute of FromClause
A named-based collection of ColumnElement
objects
maintained by this FromClause
.
The columns
, or c
collection, is the gateway
to the construction of SQL expressions using table-bound or
other selectable-bound columns:
select([mytable]).where(mytable.c.somecolumn == 5)
sqlalchemy.sql.expression.GenerativeSelect.
compare
(other, **kw)¶inherited from the ClauseElement.compare()
method of ClauseElement
Compare 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
).
sqlalchemy.sql.expression.GenerativeSelect.
compile
(default, bind=None, dialect=None, **kw)¶inherited from the ClauseElement.compile()
method of ClauseElement
Compile this SQL expression.
The return value is a Compiled
object.
Calling str()
or unicode()
on the returned value will yield a
string representation of the result. The
Compiled
object also can return a
dictionary of bind parameter names and values
using the params
accessor.
bind¶ – An Engine
or Connection
from which a
Compiled
will be acquired. This argument takes precedence over
this ClauseElement
’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 Dialect
instance from which a Compiled
will be acquired. This argument takes precedence over the bind
argument as well as this ClauseElement
‘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_binds
flag 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}))
New in version 0.9.0.
sqlalchemy.sql.expression.GenerativeSelect.
correspond_on_equivalents
(column, equivalents)¶inherited from the FromClause.correspond_on_equivalents()
method of FromClause
Return corresponding_column for the given column, or if None search for a match in the given dictionary.
sqlalchemy.sql.expression.GenerativeSelect.
corresponding_column
(column, require_embedded=False)¶inherited from the FromClause.corresponding_column()
method of FromClause
Given a ColumnElement
, return the exported
ColumnElement
object from this
expression.Selectable
which corresponds to that original
Column
via a common ancestor
column.
column¶ – the target ColumnElement
to be matched
require_embedded¶ – only return corresponding columns for
the given ColumnElement
, if the given
ColumnElement
is actually present within a sub-element
of this FromClause
.
Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this FromClause
.
sqlalchemy.sql.expression.GenerativeSelect.
count
(functions, whereclause=None, **params)¶inherited from the FromClause.count()
method of FromClause
Return a SELECT COUNT generated against this
FromClause
.
Deprecated since version 1.1: The FromClause.count()
method is deprecated, and will be removed in a future release. Please use the count
function available from the func
namespace.
See also
sqlalchemy.sql.expression.GenerativeSelect.
cte
(name=None, recursive=False)¶inherited from the HasCTE.cte()
method of HasCTE
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.
Changed in version 1.1: Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE.
SQLAlchemy detects CTE
objects, which are treated
similarly to Alias
objects, 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.
For special prefixes such as PostgreSQL “MATERIALIZED” and
“NOT MATERIALIZED”, the CTE.prefix_with()
method may be
used to establish these.
Changed in version 1.3.13: Added support for prefixes. In particular - MATERIALIZED and NOT MATERIALIZED.
name¶ – name given to the common table expression. Like
FromClause.alias()
, the name can be left as
None
in which case an anonymous symbol will be used at query
compile time.
recursive¶ – if True
, will render WITH 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:
from datetime import date
from sqlalchemy import (MetaData, Table, Column, Integer,
Date, select, literal, and_, exists)
metadata = MetaData()
visitors = Table('visitors', metadata,
Column('product_id', Integer, primary_key=True),
Column('date', Date, primary_key=True),
Column('count', Integer),
)
# add 5 visitors for the product_id == 1
product_id = 1
day = date.today()
count = 5
update_cte = (
visitors.update()
.where(and_(visitors.c.product_id == product_id,
visitors.c.date == day))
.values(count=visitors.c.count + count)
.returning(literal(1))
.cte('update_cte')
)
upsert = visitors.insert().from_select(
[visitors.c.product_id, visitors.c.date, visitors.c.count],
select([literal(product_id), literal(day), literal(count)])
.where(~exists(update_cte.select()))
)
connection.execute(upsert)
See also
Query.cte()
- ORM version of
HasCTE.cte()
.
sqlalchemy.sql.expression.GenerativeSelect.
description
¶inherited from the FromClause.description
attribute of FromClause
A brief description of this FromClause
.
Used primarily for error message formatting.
sqlalchemy.sql.expression.GenerativeSelect.
execute
(*multiparams, **params)¶inherited from the Executable.execute()
method of Executable
Compile and execute this Executable
.
sqlalchemy.sql.expression.GenerativeSelect.
execution_options
(**kw)¶inherited from the Executable.execution_options()
method of Executable
Set non-SQL options for the statement which take effect during execution.
Execution options can be set on a per-statement or
per Connection
basis. Additionally, the
Engine
and ORM Query
objects 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.
sqlalchemy.sql.expression.GenerativeSelect.
for_update
¶Provide legacy dialect support for the for_update
attribute.
sqlalchemy.sql.expression.GenerativeSelect.
foreign_keys
¶inherited from the FromClause.foreign_keys
attribute of FromClause
Return the collection of ForeignKey
objects
which this FromClause references.
sqlalchemy.sql.expression.GenerativeSelect.
get_children
(**kwargs)¶inherited from the ClauseElement.get_children()
method of ClauseElement
Return 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).
sqlalchemy.sql.expression.GenerativeSelect.
get_execution_options
()¶inherited from the Executable.get_execution_options()
method of Executable
Get the non-SQL options which will take effect during execution.
New in version 1.3.
See also
sqlalchemy.sql.expression.GenerativeSelect.
group_by
(*clauses)¶Return a new selectable with the given list of GROUP BY criterion applied.
e.g.:
stmt = select([table.c.name, func.max(table.c.stat)]).\
group_by(table.c.name)
*clauses¶ – a series of ColumnElement
constructs
which will be used to generate an GROUP BY clause.
sqlalchemy.sql.expression.GenerativeSelect.
is_derived_from
(fromclause)¶inherited from the FromClause.is_derived_from()
method of 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.
sqlalchemy.sql.expression.GenerativeSelect.
join
(right, onclause=None, isouter=False, full=False)¶inherited from the FromClause.join()
method of FromClause
Return a Join
from this
FromClause
to another
FromClause
.
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
FromClause
object such as a
Table
object, 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
.
New in version 1.1.
sqlalchemy.sql.expression.GenerativeSelect.
label
(name)¶inherited from the SelectBase.label()
method of SelectBase
Return a ‘scalar’ representation of this selectable, embedded as a subquery with a label.
See also
sqlalchemy.sql.expression.GenerativeSelect.
lateral
(name=None)¶inherited from the FromClause.lateral()
method of FromClause
Return a LATERAL alias of this FromClause
.
The return value is the Lateral
construct also
provided by the top-level lateral()
function.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
sqlalchemy.sql.expression.GenerativeSelect.
limit
(limit)¶Return a new selectable with the given LIMIT criterion applied.
This is a numerical value which usually renders as a LIMIT
expression in the resulting select. Backends that don’t
support LIMIT
will attempt to provide similar
functionality.
Changed in version 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.
sqlalchemy.sql.expression.GenerativeSelect.
offset
(offset)¶Return a new selectable with the given OFFSET criterion applied.
This is a numeric value which usually renders as an OFFSET
expression in the resulting select. Backends that don’t
support OFFSET
will attempt to provide similar
functionality.
Changed in version 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.
sqlalchemy.sql.expression.GenerativeSelect.
order_by
(*clauses)¶Return a new selectable with the given list of ORDER BY criterion applied.
e.g.:
stmt = select([table]).order_by(table.c.id, table.c.name)
*clauses¶ – a series of ColumnElement
constructs
which will be used to generate an ORDER BY clause.
sqlalchemy.sql.expression.GenerativeSelect.
outerjoin
(right, onclause=None, full=False)¶inherited from the FromClause.outerjoin()
method of FromClause
Return a Join
from this
FromClause
to another FromClause
, 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
FromClause
object such as a
Table
object, 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.
New in version 1.1.
sqlalchemy.sql.expression.GenerativeSelect.
params
(*optionaldict, **kwargs)¶inherited from the ClauseElement.params()
method of ClauseElement
Return 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}
sqlalchemy.sql.expression.GenerativeSelect.
primary_key
¶inherited from the FromClause.primary_key
attribute of FromClause
Return the collection of Column
objects
which comprise the primary key of this FromClause.
sqlalchemy.sql.expression.GenerativeSelect.
replace_selectable
(sqlutil, old, alias)¶inherited from the FromClause.replace_selectable()
method of FromClause
Replace all occurrences of FromClause ‘old’ with the given Alias
object, returning a copy of this FromClause
.
sqlalchemy.sql.expression.GenerativeSelect.
scalar
(*multiparams, **params)¶inherited from the Executable.scalar()
method of Executable
Compile and execute this Executable
, returning the
result’s scalar representation.
sqlalchemy.sql.expression.GenerativeSelect.
select
(whereclause=None, **params)¶inherited from the FromClause.select()
method of FromClause
Return a SELECT of this FromClause
.
See also
select()
- general purpose
method which allows for arbitrary column lists.
sqlalchemy.sql.expression.GenerativeSelect.
self_group
(against=None)¶inherited from the ClauseElement.self_group()
method of ClauseElement
Apply 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 another
select()
. (Note that subqueries should be
normally created using the Select.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 like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
sqlalchemy.sql.expression.GenerativeSelect.
tablesample
(sampling, name=None, seed=None)¶inherited from the FromClause.tablesample()
method of FromClause
Return a TABLESAMPLE alias of this FromClause
.
The return value is the TableSample
construct also
provided by the top-level tablesample()
function.
New in version 1.1.
See also
tablesample()
- usage guidelines and parameters
sqlalchemy.sql.expression.GenerativeSelect.
unique_params
(*optionaldict, **kwargs)¶inherited from the ClauseElement.unique_params()
method of ClauseElement
Return a copy with bindparam()
elements
replaced.
Same functionality as ClauseElement.params()
,
except adds unique=True
to affected bind parameters so that multiple statements can be
used.
sqlalchemy.sql.expression.GenerativeSelect.
with_for_update
(nowait=False, read=False, of=None, skip_locked=False, key_share=False)¶Specify a FOR UPDATE
clause for this
GenerativeSelect
.
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 nowait
option 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 NOWAIT
on Oracle
and PostgreSQL dialects.
read¶ – boolean; will render LOCK IN SHARE MODE
on MySQL,
FOR SHARE
on PostgreSQL. On PostgreSQL, when combined with
nowait
, will render FOR SHARE NOWAIT
.
of¶ – SQL expression or list of SQL expression elements
(typically Column
objects or a compatible expression) which
will render into a FOR UPDATE OF
clause; supported by PostgreSQL
and Oracle. May render as a table or as a column depending on
backend.
skip_locked¶ –
boolean, will render FOR UPDATE SKIP LOCKED
on Oracle and PostgreSQL dialects or FOR SHARE SKIP LOCKED
if
read=True
is also specified.
New in version 1.1.0.
key_share¶ –
boolean, will render FOR NO KEY UPDATE
,
or if combined with read=True
will render FOR KEY SHARE
,
on the PostgreSQL dialect.
New in version 1.1.0.
sqlalchemy.sql.expression.
HasCTE
¶Mixin that declares a class to include CTE support.
New in version 1.1.
sqlalchemy.sql.expression.HasCTE.
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.
Changed in version 1.1: Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE.
SQLAlchemy detects CTE
objects, which are treated
similarly to Alias
objects, 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.
For special prefixes such as PostgreSQL “MATERIALIZED” and
“NOT MATERIALIZED”, the CTE.prefix_with()
method may be
used to establish these.
Changed in version 1.3.13: Added support for prefixes. In particular - MATERIALIZED and NOT MATERIALIZED.
name¶ – name given to the common table expression. Like
FromClause.alias()
, the name can be left as
None
in which case an anonymous symbol will be used at query
compile time.
recursive¶ – if True
, will render WITH 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:
from datetime import date
from sqlalchemy import (MetaData, Table, Column, Integer,
Date, select, literal, and_, exists)
metadata = MetaData()
visitors = Table('visitors', metadata,
Column('product_id', Integer, primary_key=True),
Column('date', Date, primary_key=True),
Column('count', Integer),
)
# add 5 visitors for the product_id == 1
product_id = 1
day = date.today()
count = 5
update_cte = (
visitors.update()
.where(and_(visitors.c.product_id == product_id,
visitors.c.date == day))
.values(count=visitors.c.count + count)
.returning(literal(1))
.cte('update_cte')
)
upsert = visitors.insert().from_select(
[visitors.c.product_id, visitors.c.date, visitors.c.count],
select([literal(product_id), literal(day), literal(count)])
.where(~exists(update_cte.select()))
)
connection.execute(upsert)
See also
Query.cte()
- ORM version of
HasCTE.cte()
.
sqlalchemy.sql.expression.
HasPrefixes
¶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")
# MySQL 5.7 optimizer hints
stmt = select([table]).prefix_with(
"/*+ BKA(t1) */", dialect="mysql")
Multiple prefixes can be specified by multiple calls
to HasPrefixes.prefix_with()
.
*expr¶ –
textual or ClauseElement
construct which
will be rendered following the INSERT, UPDATE, or DELETE
keyword.
Warning
The HasPrefixes.prefix_with.*expr
argument to HasPrefixes.prefix_with()
can be passed as a Python string argument, which will be treated as trusted SQL text and rendered as given. DO NOT PASS UNTRUSTED INPUT TO THIS PARAMETER.
**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.
sqlalchemy.sql.expression.
HasSuffixes
¶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 HasSuffixes.suffix_with()
.
*expr¶ –
textual or ClauseElement
construct which
will be rendered following the target clause.
Warning
The HasSuffixes.suffix_with.*expr
argument to HasSuffixes.suffix_with()
can be passed as a Python string argument, which will be treated as trusted SQL text and rendered as given. DO NOT PASS UNTRUSTED INPUT TO THIS PARAMETER.
**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.
sqlalchemy.sql.expression.
Join
(left, right, onclause=None, isouter=False, full=False)¶Represent a JOIN
construct between two
FromClause
elements.
The public constructor function for Join
is the module-level
join()
function, as well as the
FromClause.join()
method
of any FromClause
(e.g. such as
Table
).
Class signature
class sqlalchemy.sql.expression.Join
(sqlalchemy.sql.expression.FromClause
)
sqlalchemy.sql.expression.Join.
__init__
(left, right, onclause=None, isouter=False, full=False)¶Construct a new Join
.
The usual entrypoint here is the join()
function or the FromClause.join()
method of any
FromClause
object.
sqlalchemy.sql.expression.Join.
alias
(sqlutil, 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 an
Alias
from 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_1
The equivalent long-hand form, given a Join
object
j
, 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 resulting Alias
represents
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. The
flat=True
option will call FromClause.alias()
against the left and right sides individually.
Using this option, no new SELECT
is 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=True
argument 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_id
The standalone alias()
function as well as the
base FromClause.alias()
method also support the flat=True
argument as a no-op, so that the argument can be passed to the
alias()
method of any selectable.
New in version 0.9.0: Added the flat=True
option to create
“aliases” of joins without enclosing inside of a SELECT
subquery.
sqlalchemy.sql.expression.Join.
c
¶inherited from the FromClause.c
attribute of FromClause
An alias for the columns
attribute.
sqlalchemy.sql.expression.Join.
columns
¶inherited from the FromClause.columns
attribute of FromClause
A named-based collection of ColumnElement
objects
maintained by this FromClause
.
The columns
, or c
collection, is the gateway
to the construction of SQL expressions using table-bound or
other selectable-bound columns:
select([mytable]).where(mytable.c.somecolumn == 5)
sqlalchemy.sql.expression.Join.
compare
(other, **kw)¶inherited from the ClauseElement.compare()
method of ClauseElement
Compare 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
).
sqlalchemy.sql.expression.Join.
compile
(default, bind=None, dialect=None, **kw)¶inherited from the ClauseElement.compile()
method of ClauseElement
Compile this SQL expression.
The return value is a Compiled
object.
Calling str()
or unicode()
on the returned value will yield a
string representation of the result. The
Compiled
object also can return a
dictionary of bind parameter names and values
using the params
accessor.
bind¶ – An Engine
or Connection
from which a
Compiled
will be acquired. This argument takes precedence over
this ClauseElement
’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 Dialect
instance from which a Compiled
will be acquired. This argument takes precedence over the bind
argument as well as this ClauseElement
‘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_binds
flag 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}))
New in version 0.9.0.
sqlalchemy.sql.expression.Join.
correspond_on_equivalents
(column, equivalents)¶inherited from the FromClause.correspond_on_equivalents()
method of FromClause
Return corresponding_column for the given column, or if None search for a match in the given dictionary.
sqlalchemy.sql.expression.Join.
corresponding_column
(column, require_embedded=False)¶inherited from the FromClause.corresponding_column()
method of FromClause
Given a ColumnElement
, return the exported
ColumnElement
object from this
expression.Selectable
which corresponds to that original
Column
via a common ancestor
column.
column¶ – the target ColumnElement
to be matched
require_embedded¶ – only return corresponding columns for
the given ColumnElement
, if the given
ColumnElement
is actually present within a sub-element
of this FromClause
.
Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this FromClause
.
sqlalchemy.sql.expression.Join.
count
(functions, whereclause=None, **params)¶inherited from the FromClause.count()
method of FromClause
Return a SELECT COUNT generated against this
FromClause
.
Deprecated since version 1.1: The FromClause.count()
method is deprecated, and will be removed in a future release. Please use the count
function available from the func
namespace.
See also
sqlalchemy.sql.expression.Join.
description
¶sqlalchemy.sql.expression.Join.
foreign_keys
¶inherited from the FromClause.foreign_keys
attribute of FromClause
Return the collection of ForeignKey
objects
which this FromClause references.
sqlalchemy.sql.expression.Join.
get_children
(**kwargs)¶Return 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).
sqlalchemy.sql.expression.Join.
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.
sqlalchemy.sql.expression.Join.
join
(right, onclause=None, isouter=False, full=False)¶inherited from the FromClause.join()
method of FromClause
Return a Join
from this
FromClause
to another
FromClause
.
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
FromClause
object such as a
Table
object, 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
.
New in version 1.1.
sqlalchemy.sql.expression.Join.
lateral
(name=None)¶inherited from the FromClause.lateral()
method of FromClause
Return a LATERAL alias of this FromClause
.
The return value is the Lateral
construct also
provided by the top-level lateral()
function.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
sqlalchemy.sql.expression.Join.
outerjoin
(right, onclause=None, full=False)¶inherited from the FromClause.outerjoin()
method of FromClause
Return a Join
from this
FromClause
to another FromClause
, 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
FromClause
object such as a
Table
object, 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.
New in version 1.1.
sqlalchemy.sql.expression.Join.
params
(*optionaldict, **kwargs)¶inherited from the ClauseElement.params()
method of ClauseElement
Return 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}
sqlalchemy.sql.expression.Join.
primary_key
¶inherited from the FromClause.primary_key
attribute of FromClause
Return the collection of Column
objects
which comprise the primary key of this FromClause.
sqlalchemy.sql.expression.Join.
replace_selectable
(sqlutil, old, alias)¶inherited from the FromClause.replace_selectable()
method of FromClause
Replace all occurrences of FromClause ‘old’ with the given Alias
object, returning a copy of this FromClause
.
sqlalchemy.sql.expression.Join.
select
(whereclause=None, **kwargs)¶Create a Select
from this
Join
.
The equivalent long-hand form, given a Join
object
j
, is:
from sqlalchemy import select
j = select([j.left, j.right], **kw).\
where(whereclause).\
select_from(j)
sqlalchemy.sql.expression.Join.
self_group
(against=None)¶Apply 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 another
select()
. (Note that subqueries should be
normally created using the Select.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 like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
sqlalchemy.sql.expression.Join.
tablesample
(sampling, name=None, seed=None)¶inherited from the FromClause.tablesample()
method of FromClause
Return a TABLESAMPLE alias of this FromClause
.
The return value is the TableSample
construct also
provided by the top-level tablesample()
function.
New in version 1.1.
See also
tablesample()
- usage guidelines and parameters
sqlalchemy.sql.expression.Join.
unique_params
(*optionaldict, **kwargs)¶inherited from the ClauseElement.unique_params()
method of ClauseElement
Return a copy with bindparam()
elements
replaced.
Same functionality as ClauseElement.params()
,
except adds unique=True
to affected bind parameters so that multiple statements can be
used.
sqlalchemy.sql.expression.
Lateral
(*arg, **kw)¶Represent a LATERAL subquery.
This object is constructed from the lateral()
module
level function as well as the FromClause.lateral()
method available
on all FromClause
subclasses.
While LATERAL is part of the SQL standard, currently only more recent PostgreSQL versions provide support for this keyword.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
Class signature
class sqlalchemy.sql.expression.Lateral
(sqlalchemy.sql.expression.Alias
)
sqlalchemy.sql.expression.Lateral.
alias
(name=None, flat=False)¶inherited from the FromClause.alias()
method of FromClause
Return an alias of this FromClause
.
E.g.:
a2 = some_table.alias('a2')
The above code creates an Alias
object which can be used
as a FROM clause in any SELECT statement.
sqlalchemy.sql.expression.Lateral.
c
¶inherited from the FromClause.c
attribute of FromClause
An alias for the columns
attribute.
sqlalchemy.sql.expression.Lateral.
columns
¶inherited from the FromClause.columns
attribute of FromClause
A named-based collection of ColumnElement
objects
maintained by this FromClause
.
The columns
, or c
collection, is the gateway
to the construction of SQL expressions using table-bound or
other selectable-bound columns:
select([mytable]).where(mytable.c.somecolumn == 5)
sqlalchemy.sql.expression.Lateral.
compare
(other, **kw)¶inherited from the ClauseElement.compare()
method of ClauseElement
Compare 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
).
sqlalchemy.sql.expression.Lateral.
compile
(default, bind=None, dialect=None, **kw)¶inherited from the ClauseElement.compile()
method of ClauseElement
Compile this SQL expression.
The return value is a Compiled
object.
Calling str()
or unicode()
on the returned value will yield a
string representation of the result. The
Compiled
object also can return a
dictionary of bind parameter names and values
using the params
accessor.
bind¶ – An Engine
or Connection
from which a
Compiled
will be acquired. This argument takes precedence over
this ClauseElement
’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 Dialect
instance from which a Compiled
will be acquired. This argument takes precedence over the bind
argument as well as this ClauseElement
‘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_binds
flag 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}))
New in version 0.9.0.
sqlalchemy.sql.expression.Lateral.
correspond_on_equivalents
(column, equivalents)¶inherited from the FromClause.correspond_on_equivalents()
method of FromClause
Return corresponding_column for the given column, or if None search for a match in the given dictionary.
sqlalchemy.sql.expression.Lateral.
corresponding_column
(column, require_embedded=False)¶inherited from the FromClause.corresponding_column()
method of FromClause
Given a ColumnElement
, return the exported
ColumnElement
object from this
expression.Selectable
which corresponds to that original
Column
via a common ancestor
column.
column¶ – the target ColumnElement
to be matched
require_embedded¶ – only return corresponding columns for
the given ColumnElement
, if the given
ColumnElement
is actually present within a sub-element
of this FromClause
.
Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this FromClause
.
sqlalchemy.sql.expression.Lateral.
count
(functions, whereclause=None, **params)¶inherited from the FromClause.count()
method of FromClause
Return a SELECT COUNT generated against this
FromClause
.
Deprecated since version 1.1: The FromClause.count()
method is deprecated, and will be removed in a future release. Please use the count
function available from the func
namespace.
See also
sqlalchemy.sql.expression.Lateral.
description
¶inherited from the Alias.description
attribute of Alias
sqlalchemy.sql.expression.Lateral.
foreign_keys
¶inherited from the FromClause.foreign_keys
attribute of FromClause
Return the collection of ForeignKey
objects
which this FromClause references.
sqlalchemy.sql.expression.Lateral.
get_children
(column_collections=True, **kw)¶inherited from the Alias.get_children()
method of Alias
Return 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).
sqlalchemy.sql.expression.Lateral.
is_derived_from
(fromclause)¶inherited from the Alias.is_derived_from()
method of Alias
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.
sqlalchemy.sql.expression.Lateral.
join
(right, onclause=None, isouter=False, full=False)¶inherited from the FromClause.join()
method of FromClause
Return a Join
from this
FromClause
to another
FromClause
.
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
FromClause
object such as a
Table
object, 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
.
New in version 1.1.
sqlalchemy.sql.expression.Lateral.
lateral
(name=None)¶inherited from the FromClause.lateral()
method of FromClause
Return a LATERAL alias of this FromClause
.
The return value is the Lateral
construct also
provided by the top-level lateral()
function.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
sqlalchemy.sql.expression.Lateral.
outerjoin
(right, onclause=None, full=False)¶inherited from the FromClause.outerjoin()
method of FromClause
Return a Join
from this
FromClause
to another FromClause
, 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
FromClause
object such as a
Table
object, 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.
New in version 1.1.
sqlalchemy.sql.expression.Lateral.
params
(*optionaldict, **kwargs)¶inherited from the ClauseElement.params()
method of ClauseElement
Return 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}
sqlalchemy.sql.expression.Lateral.
primary_key
¶inherited from the FromClause.primary_key
attribute of FromClause
Return the collection of Column
objects
which comprise the primary key of this FromClause.
sqlalchemy.sql.expression.Lateral.
replace_selectable
(sqlutil, old, alias)¶inherited from the FromClause.replace_selectable()
method of FromClause
Replace all occurrences of FromClause ‘old’ with the given Alias
object, returning a copy of this FromClause
.
sqlalchemy.sql.expression.Lateral.
select
(whereclause=None, **params)¶inherited from the FromClause.select()
method of FromClause
Return a SELECT of this FromClause
.
See also
select()
- general purpose
method which allows for arbitrary column lists.
sqlalchemy.sql.expression.Lateral.
self_group
(against=None)¶inherited from the Alias.self_group()
method of Alias
Apply 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 another
select()
. (Note that subqueries should be
normally created using the Select.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 like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
sqlalchemy.sql.expression.Lateral.
tablesample
(sampling, name=None, seed=None)¶inherited from the FromClause.tablesample()
method of FromClause
Return a TABLESAMPLE alias of this FromClause
.
The return value is the TableSample
construct also
provided by the top-level tablesample()
function.
New in version 1.1.
See also
tablesample()
- usage guidelines and parameters
sqlalchemy.sql.expression.Lateral.
unique_params
(*optionaldict, **kwargs)¶inherited from the ClauseElement.unique_params()
method of ClauseElement
Return a copy with bindparam()
elements
replaced.
Same functionality as ClauseElement.params()
,
except adds unique=True
to affected bind parameters so that multiple statements can be
used.
sqlalchemy.sql.expression.
ScalarSelect
(element)¶Class signature
class sqlalchemy.sql.expression.ScalarSelect
(sqlalchemy.sql.expression.Generative
, sqlalchemy.sql.expression.Grouping
)
sqlalchemy.sql.expression.ScalarSelect.
self_group
(**kwargs)¶Apply 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 another
select()
. (Note that subqueries should be
normally created using the Select.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 like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
sqlalchemy.sql.expression.ScalarSelect.
where
(crit)¶Apply a WHERE clause to the SELECT statement referred to
by this ScalarSelect
.
sqlalchemy.sql.expression.
Select
(columns=None, whereclause=None, from_obj=None, distinct=False, having=None, correlate=True, prefixes=None, suffixes=None, **kwargs)¶Represents a SELECT
statement.
Class signature
class sqlalchemy.sql.expression.Select
(sqlalchemy.sql.expression.HasPrefixes
, sqlalchemy.sql.expression.HasSuffixes
, sqlalchemy.sql.expression.GenerativeSelect
)
sqlalchemy.sql.expression.Select.
__init__
(columns=None, whereclause=None, from_obj=None, distinct=False, having=None, correlate=True, prefixes=None, suffixes=None, **kwargs)¶Construct a new Select
object.
This constructor is mirrored as a public API function; see sqlalchemy.sql.expression.select()
for a full usage and argument description.
sqlalchemy.sql.expression.Select.
alias
(name=None, flat=False)¶inherited from the FromClause.alias()
method of FromClause
Return an alias of this FromClause
.
E.g.:
a2 = some_table.alias('a2')
The above code creates an Alias
object which can be used
as a FROM clause in any SELECT statement.
sqlalchemy.sql.expression.Select.
append_column
(column)¶Append the given column expression to the columns clause of this
select()
construct.
E.g.:
my_select.append_column(some_table.c.new_column)
This is an in-place mutation method; the
Select.column()
method is preferred,
as it provides standard method chaining.
See the documentation for Select.with_only_columns()
for guidelines on adding /replacing the columns of a
Select
object.
sqlalchemy.sql.expression.Select.
append_correlation
(fromclause)¶Append the given correlation expression to this
select()
construct.
This is an in-place mutation method; the
Select.correlate()
method is preferred,
as it provides standard method chaining.
sqlalchemy.sql.expression.Select.
append_from
(fromclause)¶Append the given FromClause expression to this
select()
construct’s FROM clause.
This is an in-place mutation method; the
Select.select_from()
method is preferred,
as it provides standard method chaining.
sqlalchemy.sql.expression.Select.
append_group_by
(*clauses)¶inherited from the GenerativeSelect.append_group_by()
method of GenerativeSelect
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
GenerativeSelect.group_by()
method is preferred,
as it provides standard method chaining.
See also
sqlalchemy.sql.expression.Select.
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
Select.having()
method is preferred,
as it provides standard method chaining.
sqlalchemy.sql.expression.Select.
append_order_by
(*clauses)¶inherited from the GenerativeSelect.append_order_by()
method of GenerativeSelect
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
GenerativeSelect.order_by()
method is preferred,
as it
provides standard method chaining.
See also
sqlalchemy.sql.expression.Select.
append_prefix
(clause)¶Append the given columns clause prefix expression to this
select()
construct.
This is an in-place mutation method; the
Select.prefix_with()
method is preferred,
as it provides standard method chaining.
sqlalchemy.sql.expression.Select.
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
Select.where()
method is preferred,
as it provides standard method chaining.
sqlalchemy.sql.expression.Select.
apply_labels
()¶inherited from the GenerativeSelect.apply_labels()
method of GenerativeSelect
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.
sqlalchemy.sql.expression.Select.
as_scalar
()¶inherited from the SelectBase.as_scalar()
method of SelectBase
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
.
sqlalchemy.sql.expression.Select.
autocommit
()¶inherited from the SelectBase.autocommit()
method of SelectBase
Return a new selectable with the ‘autocommit’ flag set to True.
Deprecated since version 0.6: The SelectBase.autocommit()
method is deprecated, and will be removed in a future release. Please use the the Connection.execution_options.autocommit
parameter in conjunction with the Executable.execution_options()
method.
sqlalchemy.sql.expression.Select.
bind
¶sqlalchemy.sql.expression.Select.
c
¶inherited from the FromClause.c
attribute of FromClause
An alias for the columns
attribute.
sqlalchemy.sql.expression.Select.
column
(column)¶Return a new select()
construct with
the given column expression added to its columns clause.
E.g.:
my_select = my_select.column(table.c.new_column)
See the documentation for
Select.with_only_columns()
for guidelines on adding /replacing the columns of a
Select
object.
sqlalchemy.sql.expression.Select.
columns
¶inherited from the FromClause.columns
attribute of FromClause
A named-based collection of ColumnElement
objects
maintained by this FromClause
.
The columns
, or c
collection, is the gateway
to the construction of SQL expressions using table-bound or
other selectable-bound columns:
select([mytable]).where(mytable.c.somecolumn == 5)
sqlalchemy.sql.expression.Select.
correlate
(*fromclauses)¶Return a new Select
which will correlate the given FROM
clauses to that of an enclosing Select
.
Calling this method turns off the Select
object’s
default behavior of “auto-correlation”. Normally, FROM elements
which appear in a Select
that encloses this one via
its WHERE clause, ORDER BY, HAVING or
columns clause will be omitted from this
Select
object’s FROM clause.
Setting an explicit correlation collection using the
Select.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 this
Select
object is, relative to an enclosing Select
which refers to
the same FROM object. This is in contrast to the behavior of
“auto-correlation” which only correlates to an immediate enclosing
Select
.
Multi-level correlation ensures that the link
between enclosed and enclosing Select
is always via
at least one WHERE/ORDER BY/HAVING/columns clause in order for
correlation to take place.
If None
is passed, the Select
object will correlate
none of its FROM entries, and all will render unconditionally
in the local FROM clause.
*fromclauses¶ – a list of one or more
FromClause
constructs, or other compatible constructs (i.e. ORM-mapped
classes) to become part of the correlate collection.
sqlalchemy.sql.expression.Select.
correlate_except
(*fromclauses)¶Return a new Select
which will omit the given FROM
clauses from the auto-correlation process.
Calling Select.correlate_except()
turns off the
Select
object’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.
If None
is passed, the Select
object will correlate
all of its FROM entries.
*fromclauses¶ – a list of one or more
FromClause
constructs, or other compatible constructs (i.e. ORM-mapped
classes) to become part of the correlate-exception collection.
sqlalchemy.sql.expression.Select.
correspond_on_equivalents
(column, equivalents)¶inherited from the FromClause.correspond_on_equivalents()
method of FromClause
Return corresponding_column for the given column, or if None search for a match in the given dictionary.
sqlalchemy.sql.expression.Select.
corresponding_column
(column, require_embedded=False)¶inherited from the FromClause.corresponding_column()
method of FromClause
Given a ColumnElement
, return the exported
ColumnElement
object from this
expression.Selectable
which corresponds to that original
Column
via a common ancestor
column.
column¶ – the target ColumnElement
to be matched
require_embedded¶ – only return corresponding columns for
the given ColumnElement
, if the given
ColumnElement
is actually present within a sub-element
of this FromClause
.
Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this FromClause
.
sqlalchemy.sql.expression.Select.
count
(functions, whereclause=None, **params)¶inherited from the FromClause.count()
method of FromClause
Return a SELECT COUNT generated against this
FromClause
.
Deprecated since version 1.1: The FromClause.count()
method is deprecated, and will be removed in a future release. Please use the count
function available from the func
namespace.
See also
sqlalchemy.sql.expression.Select.
cte
(name=None, recursive=False)¶inherited from the HasCTE.cte()
method of HasCTE
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.
Changed in version 1.1: Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE.
SQLAlchemy detects CTE
objects, which are treated
similarly to Alias
objects, 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.
For special prefixes such as PostgreSQL “MATERIALIZED” and
“NOT MATERIALIZED”, the CTE.prefix_with()
method may be
used to establish these.
Changed in version 1.3.13: Added support for prefixes. In particular - MATERIALIZED and NOT MATERIALIZED.
name¶ – name given to the common table expression. Like
FromClause.alias()
, the name can be left as
None
in which case an anonymous symbol will be used at query
compile time.
recursive¶ – if True
, will render WITH 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:
from datetime import date
from sqlalchemy import (MetaData, Table, Column, Integer,
Date, select, literal, and_, exists)
metadata = MetaData()
visitors = Table('visitors', metadata,
Column('product_id', Integer, primary_key=True),
Column('date', Date, primary_key=True),
Column('count', Integer),
)
# add 5 visitors for the product_id == 1
product_id = 1
day = date.today()
count = 5
update_cte = (
visitors.update()
.where(and_(visitors.c.product_id == product_id,
visitors.c.date == day))
.values(count=visitors.c.count + count)
.returning(literal(1))
.cte('update_cte')
)
upsert = visitors.insert().from_select(
[visitors.c.product_id, visitors.c.date, visitors.c.count],
select([literal(product_id), literal(day), literal(count)])
.where(~exists(update_cte.select()))
)
connection.execute(upsert)
See also
Query.cte()
- ORM version of
HasCTE.cte()
.
sqlalchemy.sql.expression.Select.
description
¶inherited from the FromClause.description
attribute of FromClause
A brief description of this FromClause
.
Used primarily for error message formatting.
sqlalchemy.sql.expression.Select.
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.
sqlalchemy.sql.expression.Select.
except_
(other, **kwargs)¶Return a SQL EXCEPT
of this select() construct against
the given selectable.
sqlalchemy.sql.expression.Select.
except_all
(other, **kwargs)¶Return a SQL EXCEPT ALL
of this select() construct against
the given selectable.
sqlalchemy.sql.expression.Select.
execute
(*multiparams, **params)¶inherited from the Executable.execute()
method of Executable
Compile and execute this Executable
.
sqlalchemy.sql.expression.Select.
execution_options
(**kw)¶inherited from the Executable.execution_options()
method of Executable
Set non-SQL options for the statement which take effect during execution.
Execution options can be set on a per-statement or
per Connection
basis. Additionally, the
Engine
and ORM Query
objects 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.
sqlalchemy.sql.expression.Select.
for_update
¶inherited from the GenerativeSelect.for_update
attribute of GenerativeSelect
Provide legacy dialect support for the for_update
attribute.
sqlalchemy.sql.expression.Select.
foreign_keys
¶inherited from the FromClause.foreign_keys
attribute of FromClause
Return the collection of ForeignKey
objects
which this FromClause references.
sqlalchemy.sql.expression.Select.
froms
¶Return the displayed list of FromClause elements.
sqlalchemy.sql.expression.Select.
get_children
(column_collections=True, **kwargs)¶Return child elements as per the ClauseElement specification.
sqlalchemy.sql.expression.Select.
get_execution_options
()¶inherited from the Executable.get_execution_options()
method of Executable
Get the non-SQL options which will take effect during execution.
New in version 1.3.
See also
sqlalchemy.sql.expression.Select.
group_by
(*clauses)¶inherited from the GenerativeSelect.group_by()
method of GenerativeSelect
Return a new selectable with the given list of GROUP BY criterion applied.
e.g.:
stmt = select([table.c.name, func.max(table.c.stat)]).\
group_by(table.c.name)
*clauses¶ – a series of ColumnElement
constructs
which will be used to generate an GROUP BY clause.
sqlalchemy.sql.expression.Select.
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.
sqlalchemy.sql.expression.Select.
inner_columns
¶An iterator of all ColumnElement
expressions which would
be rendered into the columns clause of the resulting SELECT statement.
sqlalchemy.sql.expression.Select.
intersect
(other, **kwargs)¶Return a SQL INTERSECT
of this select() construct against
the given selectable.
sqlalchemy.sql.expression.Select.
intersect_all
(other, **kwargs)¶Return a SQL INTERSECT ALL
of this select() construct
against the given selectable.
sqlalchemy.sql.expression.Select.
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.
sqlalchemy.sql.expression.Select.
join
(right, onclause=None, isouter=False, full=False)¶inherited from the FromClause.join()
method of FromClause
Return a Join
from this
FromClause
to another
FromClause
.
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
FromClause
object such as a
Table
object, 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
.
New in version 1.1.
sqlalchemy.sql.expression.Select.
label
(name)¶inherited from the SelectBase.label()
method of SelectBase
Return a ‘scalar’ representation of this selectable, embedded as a subquery with a label.
See also
sqlalchemy.sql.expression.Select.
lateral
(name=None)¶inherited from the FromClause.lateral()
method of FromClause
Return a LATERAL alias of this FromClause
.
The return value is the Lateral
construct also
provided by the top-level lateral()
function.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
sqlalchemy.sql.expression.Select.
limit
(limit)¶inherited from the GenerativeSelect.limit()
method of GenerativeSelect
Return a new selectable with the given LIMIT criterion applied.
This is a numerical value which usually renders as a LIMIT
expression in the resulting select. Backends that don’t
support LIMIT
will attempt to provide similar
functionality.
Changed in version 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.
sqlalchemy.sql.expression.Select.
locate_all_froms
()¶Return a Set of all FromClause
elements
referenced by this Select.
This set is a superset of that returned by the froms
property,
which is specifically for those FromClause elements that would
actually be rendered.
sqlalchemy.sql.expression.Select.
offset
(offset)¶inherited from the GenerativeSelect.offset()
method of GenerativeSelect
Return a new selectable with the given OFFSET criterion applied.
This is a numeric value which usually renders as an OFFSET
expression in the resulting select. Backends that don’t
support OFFSET
will attempt to provide similar
functionality.
Changed in version 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.
sqlalchemy.sql.expression.Select.
order_by
(*clauses)¶inherited from the GenerativeSelect.order_by()
method of GenerativeSelect
Return a new selectable with the given list of ORDER BY criterion applied.
e.g.:
stmt = select([table]).order_by(table.c.id, table.c.name)
*clauses¶ – a series of ColumnElement
constructs
which will be used to generate an ORDER BY clause.
sqlalchemy.sql.expression.Select.
outerjoin
(right, onclause=None, full=False)¶inherited from the FromClause.outerjoin()
method of FromClause
Return a Join
from this
FromClause
to another FromClause
, 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
FromClause
object such as a
Table
object, 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.
New in version 1.1.
sqlalchemy.sql.expression.Select.
prefix_with
(*expr, **kw)¶inherited from the HasPrefixes.prefix_with()
method of HasPrefixes
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")
# MySQL 5.7 optimizer hints
stmt = select([table]).prefix_with(
"/*+ BKA(t1) */", dialect="mysql")
Multiple prefixes can be specified by multiple calls
to HasPrefixes.prefix_with()
.
*expr¶ –
textual or ClauseElement
construct which
will be rendered following the INSERT, UPDATE, or DELETE
keyword.
Warning
The HasPrefixes.prefix_with.*expr
argument to HasPrefixes.prefix_with()
can be passed as a Python string argument, which will be treated as trusted SQL text and rendered as given. DO NOT PASS UNTRUSTED INPUT TO THIS PARAMETER.
**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.
sqlalchemy.sql.expression.Select.
primary_key
¶inherited from the FromClause.primary_key
attribute of FromClause
Return the collection of Column
objects
which comprise the primary key of this FromClause.
sqlalchemy.sql.expression.Select.
reduce_columns
(sqlutil, only_synonyms=True)¶Return a new 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 Select.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 equivalence, 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.
sqlalchemy.sql.expression.Select.
replace_selectable
(sqlutil, old, alias)¶inherited from the FromClause.replace_selectable()
method of FromClause
Replace all occurrences of FromClause ‘old’ with the given Alias
object, returning a copy of this FromClause
.
sqlalchemy.sql.expression.Select.
scalar
(*multiparams, **params)¶inherited from the Executable.scalar()
method of Executable
Compile and execute this Executable
, returning the
result’s scalar representation.
sqlalchemy.sql.expression.Select.
select
(whereclause=None, **params)¶inherited from the FromClause.select()
method of FromClause
Return a SELECT of this FromClause
.
See also
select()
- general purpose
method which allows for arbitrary column lists.
sqlalchemy.sql.expression.Select.
select_from
(fromclause)¶Return a new select()
construct with the
given FROM expression(s)
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 Table
or other selectable
will have no effect. Passing a Join
that refers
to an already present Table
or 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)
sqlalchemy.sql.expression.Select.
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.
sqlalchemy.sql.expression.Select.
suffix_with
(*expr, **kw)¶inherited from the HasSuffixes.suffix_with()
method of HasSuffixes
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 HasSuffixes.suffix_with()
.
*expr¶ –
textual or ClauseElement
construct which
will be rendered following the target clause.
Warning
The HasSuffixes.suffix_with.*expr
argument to HasSuffixes.suffix_with()
can be passed as a Python string argument, which will be treated as trusted SQL text and rendered as given. DO NOT PASS UNTRUSTED INPUT TO THIS PARAMETER.
**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.
sqlalchemy.sql.expression.Select.
tablesample
(sampling, name=None, seed=None)¶inherited from the FromClause.tablesample()
method of FromClause
Return a TABLESAMPLE alias of this FromClause
.
The return value is the TableSample
construct also
provided by the top-level tablesample()
function.
New in version 1.1.
See also
tablesample()
- usage guidelines and parameters
sqlalchemy.sql.expression.Select.
union
(other, **kwargs)¶Return a SQL UNION
of this select() construct against
the given selectable.
sqlalchemy.sql.expression.Select.
union_all
(other, **kwargs)¶Return a SQL UNION ALL
of this select() construct against
the given selectable.
sqlalchemy.sql.expression.Select.
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.
sqlalchemy.sql.expression.Select.
with_for_update
(nowait=False, read=False, of=None, skip_locked=False, key_share=False)¶inherited from the GenerativeSelect.with_for_update()
method of GenerativeSelect
Specify a FOR UPDATE
clause for this
GenerativeSelect
.
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 nowait
option 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 NOWAIT
on Oracle
and PostgreSQL dialects.
read¶ – boolean; will render LOCK IN SHARE MODE
on MySQL,
FOR SHARE
on PostgreSQL. On PostgreSQL, when combined with
nowait
, will render FOR SHARE NOWAIT
.
of¶ – SQL expression or list of SQL expression elements
(typically Column
objects or a compatible expression) which
will render into a FOR UPDATE OF
clause; supported by PostgreSQL
and Oracle. May render as a table or as a column depending on
backend.
skip_locked¶ –
boolean, will render FOR UPDATE SKIP LOCKED
on Oracle and PostgreSQL dialects or FOR SHARE SKIP LOCKED
if
read=True
is also specified.
New in version 1.1.0.
key_share¶ –
boolean, will render FOR NO KEY UPDATE
,
or if combined with read=True
will render FOR KEY SHARE
,
on the PostgreSQL dialect.
New in version 1.1.0.
sqlalchemy.sql.expression.Select.
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 Table
or Alias
passed as the
selectable
argument. The dialect implementation
typically uses Python string substitution syntax
with the token %(name)s
to 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_name
option 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')
See also
sqlalchemy.sql.expression.Select.
with_only_columns
(columns)¶Return a new select()
construct with its columns
clause replaced with the given columns.
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 the select()
construct in the first place with the given columns, the columns passed
to Select.with_only_columns()
should usually be a subset of
those which were passed to the select()
construct, not those which are available from the .c
collection of
that select()
. 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 from table1
as well as itself.
sqlalchemy.sql.expression.Select.
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.
New in version 1.0.0.
See also
Select.prefix_with()
- generic SELECT prefixing which also
can suit some database-specific HINT syntaxes such as MySQL
optimizer hints
sqlalchemy.sql.expression.
Selectable
¶Mark a class as being selectable.
Class signature
class sqlalchemy.sql.expression.Selectable
(sqlalchemy.sql.expression.ClauseElement
)
sqlalchemy.sql.expression.
SelectBase
¶Base class for SELECT statements.
This includes Select
,
_selectable.CompoundSelect
and
TextAsFrom
.
Class signature
class sqlalchemy.sql.expression.SelectBase
(sqlalchemy.sql.expression.HasCTE
, sqlalchemy.sql.expression.Executable
, sqlalchemy.sql.expression.FromClause
)
sqlalchemy.sql.expression.SelectBase.
alias
(name=None, flat=False)¶inherited from the FromClause.alias()
method of FromClause
Return an alias of this FromClause
.
E.g.:
a2 = some_table.alias('a2')
The above code creates an Alias
object which can be used
as a FROM clause in any SELECT statement.
sqlalchemy.sql.expression.SelectBase.
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
.
sqlalchemy.sql.expression.SelectBase.
autocommit
()¶Return a new selectable with the ‘autocommit’ flag set to True.
Deprecated since version 0.6: The SelectBase.autocommit()
method is deprecated, and will be removed in a future release. Please use the the Connection.execution_options.autocommit
parameter in conjunction with the Executable.execution_options()
method.
sqlalchemy.sql.expression.SelectBase.
bind
¶inherited from the Executable.bind
attribute of Executable
Returns the Engine
or Connection
to which this Executable
is 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.
sqlalchemy.sql.expression.SelectBase.
c
¶inherited from the FromClause.c
attribute of FromClause
An alias for the columns
attribute.
sqlalchemy.sql.expression.SelectBase.
columns
¶inherited from the FromClause.columns
attribute of FromClause
A named-based collection of ColumnElement
objects
maintained by this FromClause
.
The columns
, or c
collection, is the gateway
to the construction of SQL expressions using table-bound or
other selectable-bound columns:
select([mytable]).where(mytable.c.somecolumn == 5)
sqlalchemy.sql.expression.SelectBase.
correspond_on_equivalents
(column, equivalents)¶inherited from the FromClause.correspond_on_equivalents()
method of FromClause
Return corresponding_column for the given column, or if None search for a match in the given dictionary.
sqlalchemy.sql.expression.SelectBase.
corresponding_column
(column, require_embedded=False)¶inherited from the FromClause.corresponding_column()
method of FromClause
Given a ColumnElement
, return the exported
ColumnElement
object from this
expression.Selectable
which corresponds to that original
Column
via a common ancestor
column.
column¶ – the target ColumnElement
to be matched
require_embedded¶ – only return corresponding columns for
the given ColumnElement
, if the given
ColumnElement
is actually present within a sub-element
of this FromClause
.
Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this FromClause
.
sqlalchemy.sql.expression.SelectBase.
count
(functions, whereclause=None, **params)¶inherited from the FromClause.count()
method of FromClause
Return a SELECT COUNT generated against this
FromClause
.
Deprecated since version 1.1: The FromClause.count()
method is deprecated, and will be removed in a future release. Please use the count
function available from the func
namespace.
See also
sqlalchemy.sql.expression.SelectBase.
cte
(name=None, recursive=False)¶inherited from the HasCTE.cte()
method of HasCTE
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.
Changed in version 1.1: Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE.
SQLAlchemy detects CTE
objects, which are treated
similarly to Alias
objects, 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.
For special prefixes such as PostgreSQL “MATERIALIZED” and
“NOT MATERIALIZED”, the CTE.prefix_with()
method may be
used to establish these.
Changed in version 1.3.13: Added support for prefixes. In particular - MATERIALIZED and NOT MATERIALIZED.
name¶ – name given to the common table expression. Like
FromClause.alias()
, the name can be left as
None
in which case an anonymous symbol will be used at query
compile time.
recursive¶ – if True
, will render WITH 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:
from datetime import date
from sqlalchemy import (MetaData, Table, Column, Integer,
Date, select, literal, and_, exists)
metadata = MetaData()
visitors = Table('visitors', metadata,
Column('product_id', Integer, primary_key=True),
Column('date', Date, primary_key=True),
Column('count', Integer),
)
# add 5 visitors for the product_id == 1
product_id = 1
day = date.today()
count = 5
update_cte = (
visitors.update()
.where(and_(visitors.c.product_id == product_id,
visitors.c.date == day))
.values(count=visitors.c.count + count)
.returning(literal(1))
.cte('update_cte')
)
upsert = visitors.insert().from_select(
[visitors.c.product_id, visitors.c.date, visitors.c.count],
select([literal(product_id), literal(day), literal(count)])
.where(~exists(update_cte.select()))
)
connection.execute(upsert)
See also
Query.cte()
- ORM version of
HasCTE.cte()
.
sqlalchemy.sql.expression.SelectBase.
description
¶inherited from the FromClause.description
attribute of FromClause
A brief description of this FromClause
.
Used primarily for error message formatting.
sqlalchemy.sql.expression.SelectBase.
execute
(*multiparams, **params)¶inherited from the Executable.execute()
method of Executable
Compile and execute this Executable
.
sqlalchemy.sql.expression.SelectBase.
execution_options
(**kw)¶inherited from the Executable.execution_options()
method of Executable
Set non-SQL options for the statement which take effect during execution.
Execution options can be set on a per-statement or
per Connection
basis. Additionally, the
Engine
and ORM Query
objects 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.
sqlalchemy.sql.expression.SelectBase.
foreign_keys
¶inherited from the FromClause.foreign_keys
attribute of FromClause
Return the collection of ForeignKey
objects
which this FromClause references.
sqlalchemy.sql.expression.SelectBase.
get_execution_options
()¶inherited from the Executable.get_execution_options()
method of Executable
Get the non-SQL options which will take effect during execution.
New in version 1.3.
See also
sqlalchemy.sql.expression.SelectBase.
is_derived_from
(fromclause)¶inherited from the FromClause.is_derived_from()
method of 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.
sqlalchemy.sql.expression.SelectBase.
join
(right, onclause=None, isouter=False, full=False)¶inherited from the FromClause.join()
method of FromClause
Return a Join
from this
FromClause
to another
FromClause
.
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
FromClause
object such as a
Table
object, 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
.
New in version 1.1.
sqlalchemy.sql.expression.SelectBase.
label
(name)¶Return a ‘scalar’ representation of this selectable, embedded as a subquery with a label.
See also
sqlalchemy.sql.expression.SelectBase.
lateral
(name=None)¶inherited from the FromClause.lateral()
method of FromClause
Return a LATERAL alias of this FromClause
.
The return value is the Lateral
construct also
provided by the top-level lateral()
function.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
sqlalchemy.sql.expression.SelectBase.
outerjoin
(right, onclause=None, full=False)¶inherited from the FromClause.outerjoin()
method of FromClause
Return a Join
from this
FromClause
to another FromClause
, 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
FromClause
object such as a
Table
object, 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.
New in version 1.1.
sqlalchemy.sql.expression.SelectBase.
primary_key
¶inherited from the FromClause.primary_key
attribute of FromClause
Return the collection of Column
objects
which comprise the primary key of this FromClause.
sqlalchemy.sql.expression.SelectBase.
replace_selectable
(sqlutil, old, alias)¶inherited from the FromClause.replace_selectable()
method of FromClause
Replace all occurrences of FromClause ‘old’ with the given Alias
object, returning a copy of this FromClause
.
sqlalchemy.sql.expression.SelectBase.
scalar
(*multiparams, **params)¶inherited from the Executable.scalar()
method of Executable
Compile and execute this Executable
, returning the
result’s scalar representation.
sqlalchemy.sql.expression.SelectBase.
select
(whereclause=None, **params)¶inherited from the FromClause.select()
method of FromClause
Return a SELECT of this FromClause
.
See also
select()
- general purpose
method which allows for arbitrary column lists.
sqlalchemy.sql.expression.SelectBase.
tablesample
(sampling, name=None, seed=None)¶inherited from the FromClause.tablesample()
method of FromClause
Return a TABLESAMPLE alias of this FromClause
.
The return value is the TableSample
construct also
provided by the top-level tablesample()
function.
New in version 1.1.
See also
tablesample()
- usage guidelines and parameters
sqlalchemy.sql.expression.
TableClause
(name, *columns, **kw)¶Represents a minimal “table” construct.
This is a lightweight table object that has only a name, a
collection of columns, which are typically produced
by the column()
function, and a schema:
from sqlalchemy import table, column
user = table("user",
column("id"),
column("name"),
column("description"),
)
The TableClause
construct serves as the base for
the more commonly used Table
object, providing
the usual set of FromClause
services 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 for MetaData
-level services.
It’s useful
on its own as an ad-hoc construct used to generate quick SQL
statements when a more fully fledged Table
is not on hand.
Class signature
class sqlalchemy.sql.expression.TableClause
(sqlalchemy.sql.expression.Immutable
, sqlalchemy.sql.expression.FromClause
)
sqlalchemy.sql.expression.TableClause.
__init__
(name, *columns, **kw)¶Construct a new TableClause
object.
This constructor is mirrored as a public API function; see sqlalchemy.sql.expression.table()
for a full usage and argument description.
sqlalchemy.sql.expression.TableClause.
alias
(name=None, flat=False)¶inherited from the FromClause.alias()
method of FromClause
Return an alias of this FromClause
.
E.g.:
a2 = some_table.alias('a2')
The above code creates an Alias
object which can be used
as a FROM clause in any SELECT statement.
sqlalchemy.sql.expression.TableClause.
c
¶inherited from the FromClause.c
attribute of FromClause
An alias for the columns
attribute.
sqlalchemy.sql.expression.TableClause.
columns
¶inherited from the FromClause.columns
attribute of FromClause
A named-based collection of ColumnElement
objects
maintained by this FromClause
.
The columns
, or c
collection, is the gateway
to the construction of SQL expressions using table-bound or
other selectable-bound columns:
select([mytable]).where(mytable.c.somecolumn == 5)
sqlalchemy.sql.expression.TableClause.
compare
(other, **kw)¶inherited from the ClauseElement.compare()
method of ClauseElement
Compare 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
).
sqlalchemy.sql.expression.TableClause.
compile
(default, bind=None, dialect=None, **kw)¶inherited from the ClauseElement.compile()
method of ClauseElement
Compile this SQL expression.
The return value is a Compiled
object.
Calling str()
or unicode()
on the returned value will yield a
string representation of the result. The
Compiled
object also can return a
dictionary of bind parameter names and values
using the params
accessor.
bind¶ – An Engine
or Connection
from which a
Compiled
will be acquired. This argument takes precedence over
this ClauseElement
’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 Dialect
instance from which a Compiled
will be acquired. This argument takes precedence over the bind
argument as well as this ClauseElement
‘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_binds
flag 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}))
New in version 0.9.0.
sqlalchemy.sql.expression.TableClause.
correspond_on_equivalents
(column, equivalents)¶inherited from the FromClause.correspond_on_equivalents()
method of FromClause
Return corresponding_column for the given column, or if None search for a match in the given dictionary.
sqlalchemy.sql.expression.TableClause.
corresponding_column
(column, require_embedded=False)¶inherited from the FromClause.corresponding_column()
method of FromClause
Given a ColumnElement
, return the exported
ColumnElement
object from this
expression.Selectable
which corresponds to that original
Column
via a common ancestor
column.
column¶ – the target ColumnElement
to be matched
require_embedded¶ – only return corresponding columns for
the given ColumnElement
, if the given
ColumnElement
is actually present within a sub-element
of this FromClause
.
Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this FromClause
.
sqlalchemy.sql.expression.TableClause.
count
(functions, whereclause=None, **params)¶inherited from the FromClause.count()
method of FromClause
Return a SELECT COUNT generated against this
FromClause
.
Deprecated since version 1.1: The FromClause.count()
method is deprecated, and will be removed in a future release. Please use the count
function available from the func
namespace.
See also
sqlalchemy.sql.expression.TableClause.
delete
(dml, whereclause=None, **kwargs)¶Generate a delete()
construct against this
TableClause
.
E.g.:
table.delete().where(table.c.id==7)
See delete()
for argument and usage information.
sqlalchemy.sql.expression.TableClause.
foreign_keys
¶inherited from the FromClause.foreign_keys
attribute of FromClause
Return the collection of ForeignKey
objects
which this FromClause references.
sqlalchemy.sql.expression.TableClause.
get_children
(column_collections=True, **kwargs)¶Return 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).
sqlalchemy.sql.expression.TableClause.
implicit_returning
= False¶TableClause
doesn’t support having a primary key or column
-level defaults, so implicit returning doesn’t apply.
sqlalchemy.sql.expression.TableClause.
insert
(dml, values=None, inline=False, **kwargs)¶Generate an insert()
construct against this
TableClause
.
E.g.:
table.insert().values(name='foo')
See insert()
for argument and usage information.
sqlalchemy.sql.expression.TableClause.
is_derived_from
(fromclause)¶inherited from the FromClause.is_derived_from()
method of 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.
sqlalchemy.sql.expression.TableClause.
join
(right, onclause=None, isouter=False, full=False)¶inherited from the FromClause.join()
method of FromClause
Return a Join
from this
FromClause
to another
FromClause
.
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
FromClause
object such as a
Table
object, 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
.
New in version 1.1.
sqlalchemy.sql.expression.TableClause.
lateral
(name=None)¶inherited from the FromClause.lateral()
method of FromClause
Return a LATERAL alias of this FromClause
.
The return value is the Lateral
construct also
provided by the top-level lateral()
function.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
sqlalchemy.sql.expression.TableClause.
outerjoin
(right, onclause=None, full=False)¶inherited from the FromClause.outerjoin()
method of FromClause
Return a Join
from this
FromClause
to another FromClause
, 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
FromClause
object such as a
Table
object, 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.
New in version 1.1.
sqlalchemy.sql.expression.TableClause.
primary_key
¶inherited from the FromClause.primary_key
attribute of FromClause
Return the collection of Column
objects
which comprise the primary key of this FromClause.
sqlalchemy.sql.expression.TableClause.
replace_selectable
(sqlutil, old, alias)¶inherited from the FromClause.replace_selectable()
method of FromClause
Replace all occurrences of FromClause ‘old’ with the given Alias
object, returning a copy of this FromClause
.
sqlalchemy.sql.expression.TableClause.
select
(whereclause=None, **params)¶inherited from the FromClause.select()
method of FromClause
Return a SELECT of this FromClause
.
See also
select()
- general purpose
method which allows for arbitrary column lists.
sqlalchemy.sql.expression.TableClause.
self_group
(against=None)¶inherited from the ClauseElement.self_group()
method of ClauseElement
Apply 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 another
select()
. (Note that subqueries should be
normally created using the Select.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 like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
sqlalchemy.sql.expression.TableClause.
tablesample
(sampling, name=None, seed=None)¶inherited from the FromClause.tablesample()
method of FromClause
Return a TABLESAMPLE alias of this FromClause
.
The return value is the TableSample
construct also
provided by the top-level tablesample()
function.
New in version 1.1.
See also
tablesample()
- usage guidelines and parameters
sqlalchemy.sql.expression.TableClause.
update
(dml, whereclause=None, values=None, inline=False, **kwargs)¶Generate an update()
construct against this
TableClause
.
E.g.:
table.update().where(table.c.id==7).values(name='foo')
See update()
for argument and usage information.
sqlalchemy.sql.expression.
TableSample
(*arg, **kw)¶Represent a TABLESAMPLE clause.
This object is constructed from the tablesample()
module
level function as well as the FromClause.tablesample()
method
available on all FromClause
subclasses.
New in version 1.1.
See also
Class signature
class sqlalchemy.sql.expression.TableSample
(sqlalchemy.sql.expression.Alias
)
sqlalchemy.sql.expression.TableSample.
alias
(name=None, flat=False)¶inherited from the FromClause.alias()
method of FromClause
Return an alias of this FromClause
.
E.g.:
a2 = some_table.alias('a2')
The above code creates an Alias
object which can be used
as a FROM clause in any SELECT statement.
sqlalchemy.sql.expression.TableSample.
c
¶inherited from the FromClause.c
attribute of FromClause
An alias for the columns
attribute.
sqlalchemy.sql.expression.TableSample.
columns
¶inherited from the FromClause.columns
attribute of FromClause
A named-based collection of ColumnElement
objects
maintained by this FromClause
.
The columns
, or c
collection, is the gateway
to the construction of SQL expressions using table-bound or
other selectable-bound columns:
select([mytable]).where(mytable.c.somecolumn == 5)
sqlalchemy.sql.expression.TableSample.
compare
(other, **kw)¶inherited from the ClauseElement.compare()
method of ClauseElement
Compare 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
).
sqlalchemy.sql.expression.TableSample.
compile
(default, bind=None, dialect=None, **kw)¶inherited from the ClauseElement.compile()
method of ClauseElement
Compile this SQL expression.
The return value is a Compiled
object.
Calling str()
or unicode()
on the returned value will yield a
string representation of the result. The
Compiled
object also can return a
dictionary of bind parameter names and values
using the params
accessor.
bind¶ – An Engine
or Connection
from which a
Compiled
will be acquired. This argument takes precedence over
this ClauseElement
’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 Dialect
instance from which a Compiled
will be acquired. This argument takes precedence over the bind
argument as well as this ClauseElement
‘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_binds
flag 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}))
New in version 0.9.0.
sqlalchemy.sql.expression.TableSample.
correspond_on_equivalents
(column, equivalents)¶inherited from the FromClause.correspond_on_equivalents()
method of FromClause
Return corresponding_column for the given column, or if None search for a match in the given dictionary.
sqlalchemy.sql.expression.TableSample.
corresponding_column
(column, require_embedded=False)¶inherited from the FromClause.corresponding_column()
method of FromClause
Given a ColumnElement
, return the exported
ColumnElement
object from this
expression.Selectable
which corresponds to that original
Column
via a common ancestor
column.
column¶ – the target ColumnElement
to be matched
require_embedded¶ – only return corresponding columns for
the given ColumnElement
, if the given
ColumnElement
is actually present within a sub-element
of this FromClause
.
Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this FromClause
.
sqlalchemy.sql.expression.TableSample.
count
(functions, whereclause=None, **params)¶inherited from the FromClause.count()
method of FromClause
Return a SELECT COUNT generated against this
FromClause
.
Deprecated since version 1.1: The FromClause.count()
method is deprecated, and will be removed in a future release. Please use the count
function available from the func
namespace.
See also
sqlalchemy.sql.expression.TableSample.
description
¶inherited from the Alias.description
attribute of Alias
sqlalchemy.sql.expression.TableSample.
foreign_keys
¶inherited from the FromClause.foreign_keys
attribute of FromClause
Return the collection of ForeignKey
objects
which this FromClause references.
sqlalchemy.sql.expression.TableSample.
get_children
(column_collections=True, **kw)¶inherited from the Alias.get_children()
method of Alias
Return 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).
sqlalchemy.sql.expression.TableSample.
is_derived_from
(fromclause)¶inherited from the Alias.is_derived_from()
method of Alias
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.
sqlalchemy.sql.expression.TableSample.
join
(right, onclause=None, isouter=False, full=False)¶inherited from the FromClause.join()
method of FromClause
Return a Join
from this
FromClause
to another
FromClause
.
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
FromClause
object such as a
Table
object, 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
.
New in version 1.1.
sqlalchemy.sql.expression.TableSample.
lateral
(name=None)¶inherited from the FromClause.lateral()
method of FromClause
Return a LATERAL alias of this FromClause
.
The return value is the Lateral
construct also
provided by the top-level lateral()
function.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
sqlalchemy.sql.expression.TableSample.
outerjoin
(right, onclause=None, full=False)¶inherited from the FromClause.outerjoin()
method of FromClause
Return a Join
from this
FromClause
to another FromClause
, 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
FromClause
object such as a
Table
object, 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.
New in version 1.1.
sqlalchemy.sql.expression.TableSample.
params
(*optionaldict, **kwargs)¶inherited from the ClauseElement.params()
method of ClauseElement
Return 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}
sqlalchemy.sql.expression.TableSample.
primary_key
¶inherited from the FromClause.primary_key
attribute of FromClause
Return the collection of Column
objects
which comprise the primary key of this FromClause.
sqlalchemy.sql.expression.TableSample.
replace_selectable
(sqlutil, old, alias)¶inherited from the FromClause.replace_selectable()
method of FromClause
Replace all occurrences of FromClause ‘old’ with the given Alias
object, returning a copy of this FromClause
.
sqlalchemy.sql.expression.TableSample.
select
(whereclause=None, **params)¶inherited from the FromClause.select()
method of FromClause
Return a SELECT of this FromClause
.
See also
select()
- general purpose
method which allows for arbitrary column lists.
sqlalchemy.sql.expression.TableSample.
self_group
(against=None)¶inherited from the Alias.self_group()
method of Alias
Apply 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 another
select()
. (Note that subqueries should be
normally created using the Select.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 like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
sqlalchemy.sql.expression.TableSample.
tablesample
(sampling, name=None, seed=None)¶inherited from the FromClause.tablesample()
method of FromClause
Return a TABLESAMPLE alias of this FromClause
.
The return value is the TableSample
construct also
provided by the top-level tablesample()
function.
New in version 1.1.
See also
tablesample()
- usage guidelines and parameters
sqlalchemy.sql.expression.TableSample.
unique_params
(*optionaldict, **kwargs)¶inherited from the ClauseElement.unique_params()
method of ClauseElement
Return a copy with bindparam()
elements
replaced.
Same functionality as ClauseElement.params()
,
except adds unique=True
to affected bind parameters so that multiple statements can be
used.
sqlalchemy.sql.expression.
TextAsFrom
(text, columns, positional=False)¶Wrap a TextClause
construct within a
SelectBase
interface.
This allows the TextClause
object to gain a
.c
collection
and other FROM-like capabilities such as
FromClause.alias()
,
SelectBase.cte()
, etc.
The TextAsFrom
construct is produced via the
TextClause.columns()
method - see that method for details.
New in version 0.9.0.
Class signature
class sqlalchemy.sql.expression.TextAsFrom
(sqlalchemy.sql.expression.SelectBase
)
sqlalchemy.sql.expression.TextAsFrom.
alias
(name=None, flat=False)¶inherited from the FromClause.alias()
method of FromClause
Return an alias of this FromClause
.
E.g.:
a2 = some_table.alias('a2')
The above code creates an Alias
object which can be used
as a FROM clause in any SELECT statement.
sqlalchemy.sql.expression.TextAsFrom.
as_scalar
()¶inherited from the SelectBase.as_scalar()
method of SelectBase
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
.
sqlalchemy.sql.expression.TextAsFrom.
autocommit
()¶inherited from the SelectBase.autocommit()
method of SelectBase
Return a new selectable with the ‘autocommit’ flag set to True.
Deprecated since version 0.6: The SelectBase.autocommit()
method is deprecated, and will be removed in a future release. Please use the the Connection.execution_options.autocommit
parameter in conjunction with the Executable.execution_options()
method.
sqlalchemy.sql.expression.TextAsFrom.
bind
¶inherited from the Executable.bind
attribute of Executable
Returns the Engine
or Connection
to which this Executable
is 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.
sqlalchemy.sql.expression.TextAsFrom.
c
¶inherited from the FromClause.c
attribute of FromClause
An alias for the columns
attribute.
sqlalchemy.sql.expression.TextAsFrom.
columns
¶inherited from the FromClause.columns
attribute of FromClause
A named-based collection of ColumnElement
objects
maintained by this FromClause
.
The columns
, or c
collection, is the gateway
to the construction of SQL expressions using table-bound or
other selectable-bound columns:
select([mytable]).where(mytable.c.somecolumn == 5)
sqlalchemy.sql.expression.TextAsFrom.
compare
(other, **kw)¶inherited from the ClauseElement.compare()
method of ClauseElement
Compare 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
).
sqlalchemy.sql.expression.TextAsFrom.
compile
(default, bind=None, dialect=None, **kw)¶inherited from the ClauseElement.compile()
method of ClauseElement
Compile this SQL expression.
The return value is a Compiled
object.
Calling str()
or unicode()
on the returned value will yield a
string representation of the result. The
Compiled
object also can return a
dictionary of bind parameter names and values
using the params
accessor.
bind¶ – An Engine
or Connection
from which a
Compiled
will be acquired. This argument takes precedence over
this ClauseElement
’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 Dialect
instance from which a Compiled
will be acquired. This argument takes precedence over the bind
argument as well as this ClauseElement
‘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_binds
flag 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}))
New in version 0.9.0.
sqlalchemy.sql.expression.TextAsFrom.
correspond_on_equivalents
(column, equivalents)¶inherited from the FromClause.correspond_on_equivalents()
method of FromClause
Return corresponding_column for the given column, or if None search for a match in the given dictionary.
sqlalchemy.sql.expression.TextAsFrom.
corresponding_column
(column, require_embedded=False)¶inherited from the FromClause.corresponding_column()
method of FromClause
Given a ColumnElement
, return the exported
ColumnElement
object from this
expression.Selectable
which corresponds to that original
Column
via a common ancestor
column.
column¶ – the target ColumnElement
to be matched
require_embedded¶ – only return corresponding columns for
the given ColumnElement
, if the given
ColumnElement
is actually present within a sub-element
of this FromClause
.
Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this FromClause
.
sqlalchemy.sql.expression.TextAsFrom.
count
(functions, whereclause=None, **params)¶inherited from the FromClause.count()
method of FromClause
Return a SELECT COUNT generated against this
FromClause
.
Deprecated since version 1.1: The FromClause.count()
method is deprecated, and will be removed in a future release. Please use the count
function available from the func
namespace.
See also
sqlalchemy.sql.expression.TextAsFrom.
cte
(name=None, recursive=False)¶inherited from the HasCTE.cte()
method of HasCTE
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.
Changed in version 1.1: Added support for UPDATE/INSERT/DELETE as CTE, CTEs added to UPDATE/INSERT/DELETE.
SQLAlchemy detects CTE
objects, which are treated
similarly to Alias
objects, 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.
For special prefixes such as PostgreSQL “MATERIALIZED” and
“NOT MATERIALIZED”, the CTE.prefix_with()
method may be
used to establish these.
Changed in version 1.3.13: Added support for prefixes. In particular - MATERIALIZED and NOT MATERIALIZED.
name¶ – name given to the common table expression. Like
FromClause.alias()
, the name can be left as
None
in which case an anonymous symbol will be used at query
compile time.
recursive¶ – if True
, will render WITH 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:
from datetime import date
from sqlalchemy import (MetaData, Table, Column, Integer,
Date, select, literal, and_, exists)
metadata = MetaData()
visitors = Table('visitors', metadata,
Column('product_id', Integer, primary_key=True),
Column('date', Date, primary_key=True),
Column('count', Integer),
)
# add 5 visitors for the product_id == 1
product_id = 1
day = date.today()
count = 5
update_cte = (
visitors.update()
.where(and_(visitors.c.product_id == product_id,
visitors.c.date == day))
.values(count=visitors.c.count + count)
.returning(literal(1))
.cte('update_cte')
)
upsert = visitors.insert().from_select(
[visitors.c.product_id, visitors.c.date, visitors.c.count],
select([literal(product_id), literal(day), literal(count)])
.where(~exists(update_cte.select()))
)
connection.execute(upsert)
See also
Query.cte()
- ORM version of
HasCTE.cte()
.
sqlalchemy.sql.expression.TextAsFrom.
description
¶inherited from the FromClause.description
attribute of FromClause
A brief description of this FromClause
.
Used primarily for error message formatting.
sqlalchemy.sql.expression.TextAsFrom.
execute
(*multiparams, **params)¶inherited from the Executable.execute()
method of Executable
Compile and execute this Executable
.
sqlalchemy.sql.expression.TextAsFrom.
execution_options
(**kw)¶inherited from the Executable.execution_options()
method of Executable
Set non-SQL options for the statement which take effect during execution.
Execution options can be set on a per-statement or
per Connection
basis. Additionally, the
Engine
and ORM Query
objects 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.
sqlalchemy.sql.expression.TextAsFrom.
foreign_keys
¶inherited from the FromClause.foreign_keys
attribute of FromClause
Return the collection of ForeignKey
objects
which this FromClause references.
sqlalchemy.sql.expression.TextAsFrom.
get_children
(**kwargs)¶inherited from the ClauseElement.get_children()
method of ClauseElement
Return 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).
sqlalchemy.sql.expression.TextAsFrom.
get_execution_options
()¶inherited from the Executable.get_execution_options()
method of Executable
Get the non-SQL options which will take effect during execution.
New in version 1.3.
See also
sqlalchemy.sql.expression.TextAsFrom.
is_derived_from
(fromclause)¶inherited from the FromClause.is_derived_from()
method of 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.
sqlalchemy.sql.expression.TextAsFrom.
join
(right, onclause=None, isouter=False, full=False)¶inherited from the FromClause.join()
method of FromClause
Return a Join
from this
FromClause
to another
FromClause
.
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
FromClause
object such as a
Table
object, 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
.
New in version 1.1.
sqlalchemy.sql.expression.TextAsFrom.
label
(name)¶inherited from the SelectBase.label()
method of SelectBase
Return a ‘scalar’ representation of this selectable, embedded as a subquery with a label.
See also
sqlalchemy.sql.expression.TextAsFrom.
lateral
(name=None)¶inherited from the FromClause.lateral()
method of FromClause
Return a LATERAL alias of this FromClause
.
The return value is the Lateral
construct also
provided by the top-level lateral()
function.
New in version 1.1.
See also
LATERAL correlation - overview of usage.
sqlalchemy.sql.expression.TextAsFrom.
outerjoin
(right, onclause=None, full=False)¶inherited from the FromClause.outerjoin()
method of FromClause
Return a Join
from this
FromClause
to another FromClause
, 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
FromClause
object such as a
Table
object, 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.
New in version 1.1.
sqlalchemy.sql.expression.TextAsFrom.
params
(*optionaldict, **kwargs)¶inherited from the ClauseElement.params()
method of ClauseElement
Return 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}
sqlalchemy.sql.expression.TextAsFrom.
primary_key
¶inherited from the FromClause.primary_key
attribute of FromClause
Return the collection of Column
objects
which comprise the primary key of this FromClause.
sqlalchemy.sql.expression.TextAsFrom.
replace_selectable
(sqlutil, old, alias)¶inherited from the FromClause.replace_selectable()
method of FromClause
Replace all occurrences of FromClause ‘old’ with the given Alias
object, returning a copy of this FromClause
.
sqlalchemy.sql.expression.TextAsFrom.
scalar
(*multiparams, **params)¶inherited from the Executable.scalar()
method of Executable
Compile and execute this Executable
, returning the
result’s scalar representation.
sqlalchemy.sql.expression.TextAsFrom.
select
(whereclause=None, **params)¶inherited from the FromClause.select()
method of FromClause
Return a SELECT of this FromClause
.
See also
select()
- general purpose
method which allows for arbitrary column lists.
sqlalchemy.sql.expression.TextAsFrom.
self_group
(against=None)¶inherited from the ClauseElement.self_group()
method of ClauseElement
Apply 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 another
select()
. (Note that subqueries should be
normally created using the Select.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 like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
sqlalchemy.sql.expression.TextAsFrom.
tablesample
(sampling, name=None, seed=None)¶inherited from the FromClause.tablesample()
method of FromClause
Return a TABLESAMPLE alias of this FromClause
.
The return value is the TableSample
construct also
provided by the top-level tablesample()
function.
New in version 1.1.
See also
tablesample()
- usage guidelines and parameters
sqlalchemy.sql.expression.TextAsFrom.
unique_params
(*optionaldict, **kwargs)¶inherited from the ClauseElement.unique_params()
method of ClauseElement
Return a copy with bindparam()
elements
replaced.
Same functionality as ClauseElement.params()
,
except adds unique=True
to affected bind parameters so that multiple statements can be
used.
flambé! the dragon and The Alchemist image designs created and generously donated by Rotem Yaari.
Created using Sphinx 3.5.3.