Expressions
plateforme.core.database.expressions
This module provides utilities for managing database expressions within the Plateforme framework using SQLAlchemy features.
BinaryExpression
BinaryExpression(
left: ColumnElement[Any],
right: ColumnElement[Any],
operator: OperatorType,
type_: Optional[_TypeEngineArgument[_T]] = None,
negate: Optional[OperatorType] = None,
modifiers: Optional[Mapping[str, Any]] = None,
)
Bases: OperatorExpression[_T]
Represent an expression that is LEFT <operator> RIGHT
.
A :class:.BinaryExpression
is generated automatically
whenever two column expressions are used in a Python binary expression:
.. sourcecode:: pycon+sql
>>> from sqlalchemy.sql import column
>>> column('a') + column('b')
<sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0>
>>> print(column('a') + column('b'))
{printsql}a + b
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
inherit_cache
class-attribute
instance-attribute
Indicate if this :class:.HasCacheKey
instance should make use of the
cache key generation scheme used by its immediate superclass.
The attribute defaults to None
, which indicates that a construct has
not yet taken into account whether or not its appropriate for it to
participate in caching; this is functionally equivalent to setting the
value to False
, except that a warning is also emitted.
This flag can be set to True
on a particular class, if the SQL that
corresponds to the object does not change based on attributes which
are local to this class, and not its superclass.
.. seealso::
:ref:`compilerext_caching` - General guideslines for setting the
:attr:`.HasCacheKey.inherit_cache` attribute for third-party or user
defined SQL constructs.
timetuple
class-attribute
instance-attribute
Hack, allows datetime objects to be compared on the LHS.
key
class-attribute
instance-attribute
The 'key' that in some circumstances refers to this object in a Python namespace.
This typically refers to the "key" of the column as present in the
.c
collection of a selectable, e.g. sometable.c["somekey"]
would
return a :class:_schema.Column
with a .key
of "somekey".
expression
property
expression: ColumnElement[Any]
Return a column expression.
Part of the inspection interface; returns self.
memoized_attribute
Bases: memoized_property[_T]
A read-only @property that is only evaluated once.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
memoized_instancemethod
classmethod
Decorate a method memoize its return value.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
proxy_set
proxy_set() -> FrozenSet[ColumnElement[Any]]
set of all columns we are proxying
as of 2.0 this is explicitly deannotated columns. previously it was effectively deannotated columns but wasn't enforced. annotated columns should basically not go into sets if at all possible because their hashing behavior is very non-performant.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
unique_params
Return a copy with :func:_expression.bindparam
elements
replaced.
Same functionality as :meth:_expression.ClauseElement.params
,
except adds unique=True
to affected bind parameters so that multiple statements can be
used.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
params
Return a copy with :func:_expression.bindparam
elements
replaced.
Returns a copy of this ClauseElement with
:func:_expression.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)
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
compare
compare(other: ClauseElement, **kw: Any) -> bool
Compare this :class:_expression.ClauseElement
to
the given :class:_expression.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 :class:_expression.ColumnElement
).
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
label
Produce a column label, i.e. <columnname> AS <name>
.
This is a shortcut to the :func:_expression.label
function.
If 'name' is None
, an anonymous label name will be generated.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
shares_lineage
shares_lineage(othercolumn: ColumnElement[Any]) -> bool
Return True if the given :class:_expression.ColumnElement
has a common ancestor to this :class:_expression.ColumnElement
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
cast
cast(type_: _TypeEngineArgument[_OPT]) -> Cast[_OPT]
Produce a type cast, i.e. CAST(<expression> AS <type>)
.
This is a shortcut to the :func:_expression.cast
function.
.. seealso::
:ref:`tutorial_casts`
:func:`_expression.cast`
:func:`_expression.type_coerce`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
Executable
Bases: StatementRole
Mark a :class:_expression.ClauseElement
as supporting execution.
:class:.Executable
is a superclass for all "statement" types
of objects, including :func:select
, :func:delete
, :func:update
,
:func:insert
, :func:text
.
options
Apply options to this statement.
In the general sense, options are any kind of Python object that can be interpreted by the SQL compiler for the statement. These options can be consumed by specific dialects or specific kinds of compilers.
The most commonly known kind of option are the ORM level options that apply "eager load" and other loading behaviors to an ORM query. However, options can theoretically be used for many other purposes.
For background on specific kinds of options for specific kinds of statements, refer to the documentation for those option objects.
.. versionchanged:: 1.4 - added :meth:.Executable.options
to
Core statement objects towards the goal of allowing unified
Core / ORM querying capabilities.
.. seealso::
:ref:`loading_columns` - refers to options specific to the usage
of ORM queries
:ref:`relationship_loader_options` - refers to options specific
to the usage of ORM queries
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
execution_options
execution_options(
*,
compiled_cache: Optional[CompiledCacheType] = ...,
logging_token: str = ...,
isolation_level: IsolationLevel = ...,
no_parameters: bool = False,
stream_results: bool = False,
max_row_buffer: int = ...,
yield_per: int = ...,
insertmanyvalues_page_size: int = ...,
schema_translate_map: Optional[
SchemaTranslateMapType
] = ...,
populate_existing: bool = False,
autoflush: bool = False,
synchronize_session: SynchronizeSessionArgument = ...,
dml_strategy: DMLStrategyArgument = ...,
render_nulls: bool = ...,
is_delete_using: bool = ...,
is_update_from: bool = ...,
**opt: Any,
) -> Self
execution_options(**opt: Any) -> Self
execution_options(**kw: Any) -> Self
Set non-SQL options for the statement which take effect during execution.
Execution options can be set at many scopes, including per-statement,
per-connection, or per execution, using methods such as
:meth:_engine.Connection.execution_options
and parameters which
accept a dictionary of options such as
:paramref:_engine.Connection.execute.execution_options
and
:paramref:_orm.Session.execute.execution_options
.
The primary characteristic of an execution option, as opposed to other kinds of options such as ORM loader options, is that execution options never affect the compiled SQL of a query, only things that affect how the SQL statement itself is invoked or how results are fetched. That is, execution options are not part of what's accommodated by SQL compilation nor are they considered part of the cached state of a statement.
The :meth:_sql.Executable.execution_options
method is
:term:generative
, as
is the case for the method as applied to the :class:_engine.Engine
and :class:_orm.Query
objects, which means when the method is called,
a copy of the object is returned, which applies the given parameters to
that new copy, but leaves the original unchanged::
statement = select(table.c.x, table.c.y)
new_statement = statement.execution_options(my_option=True)
An exception to this behavior is the :class:_engine.Connection
object, where the :meth:_engine.Connection.execution_options
method
is explicitly not generative.
The kinds of options that may be passed to
:meth:_sql.Executable.execution_options
and other related methods and
parameter dictionaries include parameters that are explicitly consumed
by SQLAlchemy Core or ORM, as well as arbitrary keyword arguments not
defined by SQLAlchemy, which means the methods and/or parameter
dictionaries may be used for user-defined parameters that interact with
custom code, which may access the parameters using methods such as
:meth:_sql.Executable.get_execution_options
and
:meth:_engine.Connection.get_execution_options
, or within selected
event hooks using a dedicated execution_options
event parameter
such as
:paramref:_events.ConnectionEvents.before_execute.execution_options
or :attr:_orm.ORMExecuteState.execution_options
, e.g.::
from sqlalchemy import event
@event.listens_for(some_engine, "before_execute")
def _process_opt(conn, statement, multiparams, params, execution_options):
"run a SQL function before invoking a statement"
if execution_options.get("do_special_thing", False):
conn.exec_driver_sql("run_special_function()")
Within the scope of options that are explicitly recognized by SQLAlchemy, most apply to specific classes of objects and not others. The most common execution options include:
-
:paramref:
_engine.Connection.execution_options.isolation_level
- sets the isolation level for a connection or a class of connections via an :class:_engine.Engine
. This option is accepted only by :class:_engine.Connection
or :class:_engine.Engine
. -
:paramref:
_engine.Connection.execution_options.stream_results
- indicates results should be fetched using a server side cursor; this option is accepted by :class:_engine.Connection
, by the :paramref:_engine.Connection.execute.execution_options
parameter on :meth:_engine.Connection.execute
, and additionally by :meth:_sql.Executable.execution_options
on a SQL statement object, as well as by ORM constructs like :meth:_orm.Session.execute
. -
:paramref:
_engine.Connection.execution_options.compiled_cache
- indicates a dictionary that will serve as the :ref:SQL compilation cache <sql_caching>
for a :class:_engine.Connection
or :class:_engine.Engine
, as well as for ORM methods like :meth:_orm.Session.execute
. Can be passed asNone
to disable caching for statements. This option is not accepted by :meth:_sql.Executable.execution_options
as it is inadvisable to carry along a compilation cache within a statement object. -
:paramref:
_engine.Connection.execution_options.schema_translate_map
- a mapping of schema names used by the
:ref:
Schema Translate Map <schema_translating>
feature, accepted by :class:_engine.Connection
, :class:_engine.Engine
, :class:_sql.Executable
, as well as by ORM constructs like :meth:_orm.Session.execute
.
.. seealso::
:meth:`_engine.Connection.execution_options`
:paramref:`_engine.Connection.execute.execution_options`
:paramref:`_orm.Session.execute.execution_options`
:ref:`orm_queryguide_execution_options` - documentation on all
ORM-specific execution options
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 |
|
get_execution_options
Get the non-SQL options which will take effect during execution.
.. versionadded:: 1.3
.. seealso::
:meth:`.Executable.execution_options`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
OperatorExpression
Bases: ColumnElement[_T]
base for expressions that contain an operator and operands
.. versionadded:: 2.0
inherit_cache
class-attribute
instance-attribute
Indicate if this :class:.HasCacheKey
instance should make use of the
cache key generation scheme used by its immediate superclass.
The attribute defaults to None
, which indicates that a construct has
not yet taken into account whether or not its appropriate for it to
participate in caching; this is functionally equivalent to setting the
value to False
, except that a warning is also emitted.
This flag can be set to True
on a particular class, if the SQL that
corresponds to the object does not change based on attributes which
are local to this class, and not its superclass.
.. seealso::
:ref:`compilerext_caching` - General guideslines for setting the
:attr:`.HasCacheKey.inherit_cache` attribute for third-party or user
defined SQL constructs.
timetuple
class-attribute
instance-attribute
Hack, allows datetime objects to be compared on the LHS.
key
class-attribute
instance-attribute
The 'key' that in some circumstances refers to this object in a Python namespace.
This typically refers to the "key" of the column as present in the
.c
collection of a selectable, e.g. sometable.c["somekey"]
would
return a :class:_schema.Column
with a .key
of "somekey".
expression
property
expression: ColumnElement[Any]
Return a column expression.
Part of the inspection interface; returns self.
memoized_attribute
Bases: memoized_property[_T]
A read-only @property that is only evaluated once.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
memoized_instancemethod
classmethod
Decorate a method memoize its return value.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
proxy_set
proxy_set() -> FrozenSet[ColumnElement[Any]]
set of all columns we are proxying
as of 2.0 this is explicitly deannotated columns. previously it was effectively deannotated columns but wasn't enforced. annotated columns should basically not go into sets if at all possible because their hashing behavior is very non-performant.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
unique_params
Return a copy with :func:_expression.bindparam
elements
replaced.
Same functionality as :meth:_expression.ClauseElement.params
,
except adds unique=True
to affected bind parameters so that multiple statements can be
used.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
params
Return a copy with :func:_expression.bindparam
elements
replaced.
Returns a copy of this ClauseElement with
:func:_expression.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)
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
compare
compare(other: ClauseElement, **kw: Any) -> bool
Compare this :class:_expression.ClauseElement
to
the given :class:_expression.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 :class:_expression.ColumnElement
).
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
label
Produce a column label, i.e. <columnname> AS <name>
.
This is a shortcut to the :func:_expression.label
function.
If 'name' is None
, an anonymous label name will be generated.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
shares_lineage
shares_lineage(othercolumn: ColumnElement[Any]) -> bool
Return True if the given :class:_expression.ColumnElement
has a common ancestor to this :class:_expression.ColumnElement
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
cast
cast(type_: _TypeEngineArgument[_OPT]) -> Cast[_OPT]
Produce a type cast, i.e. CAST(<expression> AS <type>)
.
This is a shortcut to the :func:_expression.cast
function.
.. seealso::
:ref:`tutorial_casts`
:func:`_expression.cast`
:func:`_expression.type_coerce`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
Select
Select(*entities: _ColumnsClauseArgument[Any])
Bases: HasPrefixes
, HasSuffixes
, HasHints
, HasCompileState
, _SelectFromElements
, GenerativeSelect
, TypedReturnsRows[_TP]
Represents a SELECT
statement.
The :class:_sql.Select
object is normally constructed using the
:func:_sql.select
function. See that function for details.
.. seealso::
:func:`_sql.select`
:ref:`tutorial_selecting_data` - in the 2.0 tutorial
Construct a new :class:_expression.Select
.
The public constructor for :class:_expression.Select
is the
:func:_sql.select
function.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
inherit_cache
class-attribute
instance-attribute
Indicate if this :class:.HasCacheKey
instance should make use of the
cache key generation scheme used by its immediate superclass.
The attribute defaults to None
, which indicates that a construct has
not yet taken into account whether or not its appropriate for it to
participate in caching; this is functionally equivalent to setting the
value to False
, except that a warning is also emitted.
This flag can be set to True
on a particular class, if the SQL that
corresponds to the object does not change based on attributes which
are local to this class, and not its superclass.
.. seealso::
:ref:`compilerext_caching` - General guideslines for setting the
:attr:`.HasCacheKey.inherit_cache` attribute for third-party or user
defined SQL constructs.
exported_columns
property
exported_columns: ReadOnlyColumnCollection[
str, ColumnElement[Any]
]
A :class:_expression.ColumnCollection
that represents the "exported"
columns of this :class:_expression.Selectable
, not including
:class:_sql.TextClause
constructs.
The "exported" columns for a :class:_expression.SelectBase
object are synonymous
with the :attr:_expression.SelectBase.selected_columns
collection.
.. versionadded:: 1.4
.. seealso::
:attr:`_expression.Select.exported_columns`
:attr:`_expression.Selectable.exported_columns`
:attr:`_expression.FromClause.exported_columns`
column_descriptions
property
column_descriptions: Any
Return a :term:plugin-enabled
'column descriptions' structure
referring to the columns which are SELECTed by this statement.
This attribute is generally useful when using the ORM, as an
extended structure which includes information about mapped
entities is returned. The section :ref:queryguide_inspection
contains more background.
For a Core-only statement, the structure returned by this accessor
is derived from the same objects that are returned by the
:attr:.Select.selected_columns
accessor, formatted as a list of
dictionaries which contain the keys name
, type
and expr
,
which indicate the column expressions to be selected::
>>> stmt = select(user_table)
>>> stmt.column_descriptions
[
{
'name': 'id',
'type': Integer(),
'expr': Column('id', Integer(), ...)},
{
'name': 'name',
'type': String(length=30),
'expr': Column('name', String(length=30), ...)}
]
.. versionchanged:: 1.4.33 The :attr:.Select.column_descriptions
attribute returns a structure for a Core-only set of entities,
not just ORM-only entities.
.. seealso::
:attr:`.UpdateBase.entity_description` - entity information for
an :func:`.insert`, :func:`.update`, or :func:`.delete`
:ref:`queryguide_inspection` - ORM background
froms
property
froms: Sequence[FromClause]
Return the displayed list of :class:_expression.FromClause
elements.
columns_clause_froms
property
columns_clause_froms: List[FromClause]
Return the set of :class:_expression.FromClause
objects implied
by the columns clause of this SELECT statement.
.. versionadded:: 1.4.23
.. seealso::
:attr:`_sql.Select.froms` - "final" FROM list taking the full
statement into account
:meth:`_sql.Select.with_only_columns` - makes use of this
collection to set up a new FROM list
inner_columns
property
An iterator of all :class:_expression.ColumnElement
expressions which would
be rendered into the columns clause of the resulting SELECT statement.
This method is legacy as of 1.4 and is superseded by the
:attr:_expression.Select.exported_columns
collection.
whereclause
property
whereclause: Optional[ColumnElement[Any]]
Return the completed WHERE clause for this
:class:_expression.Select
statement.
This assembles the current collection of WHERE criteria
into a single :class:_expression.BooleanClauseList
construct.
.. versionadded:: 1.4
memoized_attribute
Bases: memoized_property[_T]
A read-only @property that is only evaluated once.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
memoized_instancemethod
classmethod
Decorate a method memoize its return value.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
unique_params
Return a copy with :func:_expression.bindparam
elements
replaced.
Same functionality as :meth:_expression.ClauseElement.params
,
except adds unique=True
to affected bind parameters so that multiple statements can be
used.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
params
Return a copy with :func:_expression.bindparam
elements
replaced.
Returns a copy of this ClauseElement with
:func:_expression.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)
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
compare
compare(other: ClauseElement, **kw: Any) -> bool
Compare this :class:_expression.ClauseElement
to
the given :class:_expression.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 :class:_expression.ColumnElement
).
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
lateral
Return a LATERAL alias of this :class:_expression.Selectable
.
The return value is the :class:_expression.Lateral
construct also
provided by the top-level :func:_expression.lateral
function.
.. seealso::
:ref:`tutorial_lateral_correlation` - overview of usage.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
replace_selectable
replace_selectable(old: FromClause, alias: Alias) -> Self
Replace all occurrences of :class:_expression.FromClause
'old' with the given :class:_expression.Alias
object, returning a copy of this :class:_expression.FromClause
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
corresponding_column
corresponding_column(
column: KeyedColumnElement[Any],
require_embedded: bool = False,
) -> Optional[KeyedColumnElement[Any]]
Given a :class:_expression.ColumnElement
, return the exported
:class:_expression.ColumnElement
object from the
:attr:_expression.Selectable.exported_columns
collection of this :class:_expression.Selectable
which corresponds to that
original :class:_expression.ColumnElement
via a common ancestor
column.
:param column: the target :class:_expression.ColumnElement
to be matched.
:param require_embedded: only return corresponding columns for
the given :class:_expression.ColumnElement
, if the given
:class:_expression.ColumnElement
is actually present within a sub-element
of this :class:_expression.Selectable
.
Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this :class:_expression.Selectable
.
.. seealso::
:attr:`_expression.Selectable.exported_columns` - the
:class:`_expression.ColumnCollection`
that is used for the operation.
:meth:`_expression.ColumnCollection.corresponding_column`
- implementation
method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
add_cte
Add one or more :class:_sql.CTE
constructs to this statement.
This method will associate the given :class:_sql.CTE
constructs with
the parent statement such that they will each be unconditionally
rendered in the WITH clause of the final statement, even if not
referenced elsewhere within the statement or any sub-selects.
The optional :paramref:.HasCTE.add_cte.nest_here
parameter when set
to True will have the effect that each given :class:_sql.CTE
will
render in a WITH clause rendered directly along with this statement,
rather than being moved to the top of the ultimate rendered statement,
even if this statement is rendered as a subquery within a larger
statement.
This method has two general uses. One is to embed CTE statements that serve some purpose without being referenced explicitly, such as the use case of embedding a DML statement such as an INSERT or UPDATE as a CTE inline with a primary statement that may draw from its results indirectly. The other is to provide control over the exact placement of a particular series of CTE constructs that should remain rendered directly in terms of a particular statement that may be nested in a larger statement.
E.g.::
from sqlalchemy import table, column, select
t = table('t', column('c1'), column('c2'))
ins = t.insert().values({"c1": "x", "c2": "y"}).cte()
stmt = select(t).add_cte(ins)
Would render::
WITH anon_1 AS
(INSERT INTO t (c1, c2) VALUES (:param_1, :param_2))
SELECT t.c1, t.c2
FROM t
Above, the "anon_1" CTE is not referenced in the SELECT statement, however still accomplishes the task of running an INSERT statement.
Similarly in a DML-related context, using the PostgreSQL
:class:_postgresql.Insert
construct to generate an "upsert"::
from sqlalchemy import table, column
from sqlalchemy.dialects.postgresql import insert
t = table("t", column("c1"), column("c2"))
delete_statement_cte = (
t.delete().where(t.c.c1 < 1).cte("deletions")
)
insert_stmt = insert(t).values({"c1": 1, "c2": 2})
update_statement = insert_stmt.on_conflict_do_update(
index_elements=[t.c.c1],
set_={
"c1": insert_stmt.excluded.c1,
"c2": insert_stmt.excluded.c2,
},
).add_cte(delete_statement_cte)
print(update_statement)
The above statement renders as::
WITH deletions AS
(DELETE FROM t WHERE t.c1 < %(c1_1)s)
INSERT INTO t (c1, c2) VALUES (%(c1)s, %(c2)s)
ON CONFLICT (c1) DO UPDATE SET c1 = excluded.c1, c2 = excluded.c2
.. versionadded:: 1.4.21
:param *ctes: zero or more :class:.CTE
constructs.
.. versionchanged:: 2.0 Multiple CTE instances are accepted
:param nest_here: if True, the given CTE or CTEs will be rendered
as though they specified the :paramref:.HasCTE.cte.nesting
flag
to True
when they were added to this :class:.HasCTE
.
Assuming the given CTEs are not referenced in an outer-enclosing
statement as well, the CTEs given should render at the level of
this statement when this flag is given.
.. versionadded:: 2.0
.. seealso::
:paramref:`.HasCTE.cte.nesting`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 |
|
cte
Return a new :class:_expression.CTE
,
or Common Table Expression instance.
Common table expressions are a SQL standard whereby SELECT statements can draw upon secondary statements specified along with the primary statement, using a clause called "WITH". Special semantics regarding UNION can also be employed to allow "recursive" queries, where a SELECT statement can draw upon the set of rows that have previously been selected.
CTEs can also be applied to DML constructs UPDATE, INSERT and DELETE on some databases, both as a source of CTE rows when combined with RETURNING, as well as a consumer of CTE rows.
SQLAlchemy detects :class:_expression.CTE
objects, which are treated
similarly to :class:_expression.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 :meth:_expression.CTE.prefix_with
method may be
used to establish these.
.. versionchanged:: 1.3.13 Added support for prefixes. In particular - MATERIALIZED and NOT MATERIALIZED.
:param name: name given to the common table expression. Like
:meth:_expression.FromClause.alias
, the name can be left as
None
in which case an anonymous symbol will be used at query
compile time.
:param 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.
:param nesting: if True
, will render the CTE locally to the
statement in which it is referenced. For more complex scenarios,
the :meth:.HasCTE.add_cte
method using the
:paramref:.HasCTE.add_cte.nest_here
parameter may also be used to more carefully
control the exact placement of a particular CTE.
.. versionadded:: 1.4.24
.. seealso::
:meth:`.HasCTE.add_cte`
The following examples include two from PostgreSQL's documentation at https://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)
Example 4, Nesting CTE (SQLAlchemy 1.4.24 and above)::
value_a = select(
literal("root").label("n")
).cte("value_a")
# A nested CTE with the same name as the root one
value_a_nested = select(
literal("nesting").label("n")
).cte("value_a", nesting=True)
# Nesting CTEs takes ascendency locally
# over the CTEs at a higher level
value_b = select(value_a_nested.c.n).cte("value_b")
value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b"))
The above query will render the second CTE nested inside the first, shown with inline parameters below as::
WITH
value_a AS
(SELECT 'root' AS n),
value_b AS
(WITH value_a AS
(SELECT 'nesting' AS n)
SELECT value_a.n AS n FROM value_a)
SELECT value_a.n AS a, value_b.n AS b
FROM value_a, value_b
The same CTE can be set up using the :meth:.HasCTE.add_cte
method
as follows (SQLAlchemy 2.0 and above)::
value_a = select(
literal("root").label("n")
).cte("value_a")
# A nested CTE with the same name as the root one
value_a_nested = select(
literal("nesting").label("n")
).cte("value_a")
# Nesting CTEs takes ascendency locally
# over the CTEs at a higher level
value_b = (
select(value_a_nested.c.n).
add_cte(value_a_nested, nest_here=True).
cte("value_b")
)
value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b"))
Example 5, Non-Linear CTE (SQLAlchemy 1.4.28 and above)::
edge = Table(
"edge",
metadata,
Column("id", Integer, primary_key=True),
Column("left", Integer),
Column("right", Integer),
)
root_node = select(literal(1).label("node")).cte(
"nodes", recursive=True
)
left_edge = select(edge.c.left).join(
root_node, edge.c.right == root_node.c.node
)
right_edge = select(edge.c.right).join(
root_node, edge.c.left == root_node.c.node
)
subgraph_cte = root_node.union(left_edge, right_edge)
subgraph = select(subgraph_cte)
The above query will render 2 UNIONs inside the recursive CTE::
WITH RECURSIVE nodes(node) AS (
SELECT 1 AS node
UNION
SELECT edge."left" AS "left"
FROM edge JOIN nodes ON edge."right" = nodes.node
UNION
SELECT edge."right" AS "right"
FROM edge JOIN nodes ON edge."left" = nodes.node
)
SELECT nodes.node FROM nodes
.. seealso::
:meth:`_orm.Query.cte` - ORM version of
:meth:`_expression.HasCTE.cte`.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 |
|
options
Apply options to this statement.
In the general sense, options are any kind of Python object that can be interpreted by the SQL compiler for the statement. These options can be consumed by specific dialects or specific kinds of compilers.
The most commonly known kind of option are the ORM level options that apply "eager load" and other loading behaviors to an ORM query. However, options can theoretically be used for many other purposes.
For background on specific kinds of options for specific kinds of statements, refer to the documentation for those option objects.
.. versionchanged:: 1.4 - added :meth:.Executable.options
to
Core statement objects towards the goal of allowing unified
Core / ORM querying capabilities.
.. seealso::
:ref:`loading_columns` - refers to options specific to the usage
of ORM queries
:ref:`relationship_loader_options` - refers to options specific
to the usage of ORM queries
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
execution_options
execution_options(
*,
compiled_cache: Optional[CompiledCacheType] = ...,
logging_token: str = ...,
isolation_level: IsolationLevel = ...,
no_parameters: bool = False,
stream_results: bool = False,
max_row_buffer: int = ...,
yield_per: int = ...,
insertmanyvalues_page_size: int = ...,
schema_translate_map: Optional[
SchemaTranslateMapType
] = ...,
populate_existing: bool = False,
autoflush: bool = False,
synchronize_session: SynchronizeSessionArgument = ...,
dml_strategy: DMLStrategyArgument = ...,
render_nulls: bool = ...,
is_delete_using: bool = ...,
is_update_from: bool = ...,
**opt: Any,
) -> Self
execution_options(**opt: Any) -> Self
execution_options(**kw: Any) -> Self
Set non-SQL options for the statement which take effect during execution.
Execution options can be set at many scopes, including per-statement,
per-connection, or per execution, using methods such as
:meth:_engine.Connection.execution_options
and parameters which
accept a dictionary of options such as
:paramref:_engine.Connection.execute.execution_options
and
:paramref:_orm.Session.execute.execution_options
.
The primary characteristic of an execution option, as opposed to other kinds of options such as ORM loader options, is that execution options never affect the compiled SQL of a query, only things that affect how the SQL statement itself is invoked or how results are fetched. That is, execution options are not part of what's accommodated by SQL compilation nor are they considered part of the cached state of a statement.
The :meth:_sql.Executable.execution_options
method is
:term:generative
, as
is the case for the method as applied to the :class:_engine.Engine
and :class:_orm.Query
objects, which means when the method is called,
a copy of the object is returned, which applies the given parameters to
that new copy, but leaves the original unchanged::
statement = select(table.c.x, table.c.y)
new_statement = statement.execution_options(my_option=True)
An exception to this behavior is the :class:_engine.Connection
object, where the :meth:_engine.Connection.execution_options
method
is explicitly not generative.
The kinds of options that may be passed to
:meth:_sql.Executable.execution_options
and other related methods and
parameter dictionaries include parameters that are explicitly consumed
by SQLAlchemy Core or ORM, as well as arbitrary keyword arguments not
defined by SQLAlchemy, which means the methods and/or parameter
dictionaries may be used for user-defined parameters that interact with
custom code, which may access the parameters using methods such as
:meth:_sql.Executable.get_execution_options
and
:meth:_engine.Connection.get_execution_options
, or within selected
event hooks using a dedicated execution_options
event parameter
such as
:paramref:_events.ConnectionEvents.before_execute.execution_options
or :attr:_orm.ORMExecuteState.execution_options
, e.g.::
from sqlalchemy import event
@event.listens_for(some_engine, "before_execute")
def _process_opt(conn, statement, multiparams, params, execution_options):
"run a SQL function before invoking a statement"
if execution_options.get("do_special_thing", False):
conn.exec_driver_sql("run_special_function()")
Within the scope of options that are explicitly recognized by SQLAlchemy, most apply to specific classes of objects and not others. The most common execution options include:
-
:paramref:
_engine.Connection.execution_options.isolation_level
- sets the isolation level for a connection or a class of connections via an :class:_engine.Engine
. This option is accepted only by :class:_engine.Connection
or :class:_engine.Engine
. -
:paramref:
_engine.Connection.execution_options.stream_results
- indicates results should be fetched using a server side cursor; this option is accepted by :class:_engine.Connection
, by the :paramref:_engine.Connection.execute.execution_options
parameter on :meth:_engine.Connection.execute
, and additionally by :meth:_sql.Executable.execution_options
on a SQL statement object, as well as by ORM constructs like :meth:_orm.Session.execute
. -
:paramref:
_engine.Connection.execution_options.compiled_cache
- indicates a dictionary that will serve as the :ref:SQL compilation cache <sql_caching>
for a :class:_engine.Connection
or :class:_engine.Engine
, as well as for ORM methods like :meth:_orm.Session.execute
. Can be passed asNone
to disable caching for statements. This option is not accepted by :meth:_sql.Executable.execution_options
as it is inadvisable to carry along a compilation cache within a statement object. -
:paramref:
_engine.Connection.execution_options.schema_translate_map
- a mapping of schema names used by the
:ref:
Schema Translate Map <schema_translating>
feature, accepted by :class:_engine.Connection
, :class:_engine.Engine
, :class:_sql.Executable
, as well as by ORM constructs like :meth:_orm.Session.execute
.
.. seealso::
:meth:`_engine.Connection.execution_options`
:paramref:`_engine.Connection.execute.execution_options`
:paramref:`_orm.Session.execute.execution_options`
:ref:`orm_queryguide_execution_options` - documentation on all
ORM-specific execution options
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 |
|
get_execution_options
Get the non-SQL options which will take effect during execution.
.. versionadded:: 1.3
.. seealso::
:meth:`.Executable.execution_options`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/base.py
subquery
Return a subquery of this :class:_expression.SelectBase
.
A subquery is from a SQL perspective a parenthesized, named construct that can be placed in the FROM clause of another SELECT statement.
Given a SELECT statement such as::
stmt = select(table.c.id, table.c.name)
The above statement might look like::
SELECT table.id, table.name FROM table
The subquery form by itself renders the same way, however when embedded into the FROM clause of another SELECT statement, it becomes a named sub-element::
subq = stmt.subquery()
new_stmt = select(subq)
The above renders as::
SELECT anon_1.id, anon_1.name
FROM (SELECT table.id, table.name FROM table) AS anon_1
Historically, :meth:_expression.SelectBase.subquery
is equivalent to calling
the :meth:_expression.FromClause.alias
method on a FROM object; however,
as a :class:_expression.SelectBase
object is not directly FROM object,
the :meth:_expression.SelectBase.subquery
method provides clearer semantics.
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
get_label_style
get_label_style() -> SelectLabelStyle
Retrieve the current label style.
.. versionadded:: 1.4
set_label_style
set_label_style(style: SelectLabelStyle) -> Self
Return a new selectable with the specified label style.
There are three "label styles" available,
:attr:_sql.SelectLabelStyle.LABEL_STYLE_DISAMBIGUATE_ONLY
,
:attr:_sql.SelectLabelStyle.LABEL_STYLE_TABLENAME_PLUS_COL
, and
:attr:_sql.SelectLabelStyle.LABEL_STYLE_NONE
. The default style is
:attr:_sql.SelectLabelStyle.LABEL_STYLE_TABLENAME_PLUS_COL
.
In modern SQLAlchemy, there is not generally a need to change the
labeling style, as per-expression labels are more effectively used by
making use of the :meth:_sql.ColumnElement.label
method. In past
versions, :data:_sql.LABEL_STYLE_TABLENAME_PLUS_COL
was used to
disambiguate same-named columns from different tables, aliases, or
subqueries; the newer :data:_sql.LABEL_STYLE_DISAMBIGUATE_ONLY
now
applies labels only to names that conflict with an existing name so
that the impact of this labeling is minimal.
The rationale for disambiguation is mostly so that all column
expressions are available from a given :attr:_sql.FromClause.c
collection when a subquery is created.
.. versionadded:: 1.4 - the
:meth:_sql.GenerativeSelect.set_label_style
method replaces the
previous combination of .apply_labels()
, .with_labels()
and
use_labels=True
methods and/or parameters.
.. seealso::
:data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY`
:data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL`
:data:`_sql.LABEL_STYLE_NONE`
:data:`_sql.LABEL_STYLE_DEFAULT`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
exists
exists() -> Exists
Return an :class:_sql.Exists
representation of this selectable,
which can be used as a column expression.
The returned object is an instance of :class:_sql.Exists
.
.. seealso::
:func:`_sql.exists`
:ref:`tutorial_exists` - in the :term:`2.0 style` tutorial.
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
label
Return a 'scalar' representation of this selectable, embedded as a subquery with a label.
.. seealso::
:meth:`_expression.SelectBase.scalar_subquery`.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
alias
Return a named subquery against this
:class:_expression.SelectBase
.
For a :class:_expression.SelectBase
(as opposed to a
:class:_expression.FromClause
),
this returns a :class:.Subquery
object which behaves mostly the
same as the :class:_expression.Alias
object that is used with a
:class:_expression.FromClause
.
.. versionchanged:: 1.4 The :meth:_expression.SelectBase.alias
method is now
a synonym for the :meth:_expression.SelectBase.subquery
method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
with_for_update
with_for_update(
*,
nowait: bool = False,
read: bool = False,
of: Optional[_ForUpdateOfArgument] = None,
skip_locked: bool = False,
key_share: bool = False,
) -> Self
Specify a FOR UPDATE
clause for this
:class:_expression.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.
:param nowait: boolean; will render FOR UPDATE NOWAIT
on Oracle
and PostgreSQL dialects.
:param 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
.
:param of: SQL expression or list of SQL expression elements,
(typically :class:_schema.Column
objects or a compatible expression,
for some backends may also be a table expression) which will render
into a FOR UPDATE OF
clause; supported by PostgreSQL, Oracle, some
MySQL versions and possibly others. May render as a table or as a
column depending on backend.
:param 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.
:param key_share: boolean, will render FOR NO KEY UPDATE
,
or if combined with read=True
will render FOR KEY SHARE
,
on the PostgreSQL dialect.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 |
|
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.
.. note::
The :meth:_sql.GenerativeSelect.limit
method will replace
any clause applied with :meth:_sql.GenerativeSelect.fetch
.
:param limit: an integer LIMIT parameter, or a SQL expression
that provides an integer result. Pass None
to reset it.
.. seealso::
:meth:_sql.GenerativeSelect.fetch
:meth:_sql.GenerativeSelect.offset
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
fetch
Return a new selectable with the given FETCH FIRST criterion applied.
This is a numeric value which usually renders as
FETCH {FIRST | NEXT} [ count ] {ROW | ROWS} {ONLY | WITH TIES}
expression in the resulting select. This functionality is
is currently implemented for Oracle, PostgreSQL, MSSQL.
Use :meth:_sql.GenerativeSelect.offset
to specify the offset.
.. note::
The :meth:_sql.GenerativeSelect.fetch
method will replace
any clause applied with :meth:_sql.GenerativeSelect.limit
.
.. versionadded:: 1.4
:param count: an integer COUNT parameter, or a SQL expression
that provides an integer result. When percent=True
this will
represent the percentage of rows to return, not the absolute value.
Pass None
to reset it.
:param with_ties: When True
, the WITH TIES option is used
to return any additional rows that tie for the last place in the
result set according to the ORDER BY
clause. The
ORDER BY
may be mandatory in this case. Defaults to False
:param percent: When True
, count
represents the percentage
of the total number of selected rows to return. Defaults to False
.. seealso::
:meth:_sql.GenerativeSelect.limit
:meth:_sql.GenerativeSelect.offset
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
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.
:param offset: an integer OFFSET parameter, or a SQL expression
that provides an integer result. Pass None
to reset it.
.. seealso::
:meth:_sql.GenerativeSelect.limit
:meth:_sql.GenerativeSelect.fetch
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
slice
Apply LIMIT / OFFSET to this statement based on a slice.
The start and stop indices behave like the argument to Python's
built-in :func:range
function. This method provides an
alternative to using LIMIT
/OFFSET
to get a slice of the
query.
For example, ::
stmt = select(User).order_by(User).id.slice(1, 3)
renders as
.. sourcecode:: sql
SELECT users.id AS users_id, users.name AS users_name FROM users ORDER BY users.id LIMIT ? OFFSET ? (2, 1)
.. note::
The :meth:_sql.GenerativeSelect.slice
method will replace
any clause applied with :meth:_sql.GenerativeSelect.fetch
.
.. versionadded:: 1.4 Added the :meth:_sql.GenerativeSelect.slice
method generalized from the ORM.
.. seealso::
:meth:_sql.GenerativeSelect.limit
:meth:_sql.GenerativeSelect.offset
:meth:_sql.GenerativeSelect.fetch
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
order_by
order_by(
__first: Union[
Literal[None, NO_ARG],
_ColumnExpressionOrStrLabelArgument[Any],
] = NO_ARG,
*clauses: _ColumnExpressionOrStrLabelArgument[Any],
) -> Self
Return a new selectable with the given list of ORDER BY criteria applied.
e.g.::
stmt = select(table).order_by(table.c.id, table.c.name)
Calling this method multiple times is equivalent to calling it once
with all the clauses concatenated. All existing ORDER BY criteria may
be cancelled by passing None
by itself. New ORDER BY criteria may
then be added by invoking :meth:_orm.Query.order_by
again, e.g.::
# will erase all ORDER BY and ORDER BY new_col alone
stmt = stmt.order_by(None).order_by(new_col)
:param *clauses: a series of :class:_expression.ColumnElement
constructs
which will be used to generate an ORDER BY clause.
.. seealso::
:ref:`tutorial_order_by` - in the :ref:`unified_tutorial`
:ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
group_by
group_by(
__first: Union[
Literal[None, NO_ARG],
_ColumnExpressionOrStrLabelArgument[Any],
] = NO_ARG,
*clauses: _ColumnExpressionOrStrLabelArgument[Any],
) -> Self
Return a new selectable with the given list of GROUP BY criterion applied.
All existing GROUP BY settings can be suppressed by passing None
.
e.g.::
stmt = select(table.c.name, func.max(table.c.stat)).\
group_by(table.c.name)
:param *clauses: a series of :class:_expression.ColumnElement
constructs
which will be used to generate an GROUP BY clause.
.. seealso::
:ref:`tutorial_group_by_w_aggregates` - in the
:ref:`unified_tutorial`
:ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
with_statement_hint
Add a statement hint to this :class:_expression.Select
or
other selectable object.
This method is similar to :meth:_expression.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.
.. seealso::
:meth:`_expression.Select.with_hint`
:meth:`_expression.Select.prefix_with` - generic SELECT prefixing
which also can suit some database-specific HINT syntaxes such as
MySQL optimizer hints
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
with_hint
Add an indexing or other executional context hint for the given
selectable to this :class:_expression.Select
or other selectable
object.
The text of the hint is rendered in the appropriate
location for the database backend in use, relative
to the given :class:_schema.Table
or :class:_expression.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", 'mssql')
.. seealso::
:meth:`_expression.Select.with_statement_hint`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
suffix_with
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 :meth:_expression.HasSuffixes.suffix_with
.
:param *suffixes: textual or :class:_expression.ClauseElement
construct which
will be rendered following the target clause.
:param dialect: Optional string dialect name which will
limit rendering of this suffix to only that dialect.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
prefix_with
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 :meth:_expression.HasPrefixes.prefix_with
.
:param *prefixes: textual or :class:_expression.ClauseElement
construct which
will be rendered following the INSERT, UPDATE, or DELETE
keyword.
:param dialect: optional string dialect name which will
limit rendering of this prefix to only that dialect.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
filter
filter(*criteria: _ColumnExpressionArgument[bool]) -> Self
A synonym for the :meth:_sql.Select.where
method.
filter_by
filter_by(**kwargs: Any) -> Self
apply the given filtering criterion as a WHERE clause to this select.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
from_statement
Apply the columns which this :class:.Select
would select
onto another statement.
This operation is :term:plugin-specific
and will raise a not
supported exception if this :class:_sql.Select
does not select from
plugin-enabled entities.
The statement is typically either a :func:_expression.text
or
:func:_expression.select
construct, and should return the set of
columns appropriate to the entities represented by this
:class:.Select
.
.. seealso::
:ref:`orm_queryguide_selecting_text` - usage examples in the
ORM Querying Guide
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
join
join(
target: _JoinTargetArgument,
onclause: Optional[_OnClauseArgument] = None,
*,
isouter: bool = False,
full: bool = False,
) -> Self
Create a SQL JOIN against this :class:_expression.Select
object's criterion
and apply generatively, returning the newly resulting
:class:_expression.Select
.
E.g.::
stmt = select(user_table).join(address_table, user_table.c.id == address_table.c.user_id)
The above statement generates SQL similar to::
SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id
.. versionchanged:: 1.4 :meth:_expression.Select.join
now creates
a :class:_sql.Join
object between a :class:_sql.FromClause
source that is within the FROM clause of the existing SELECT,
and a given target :class:_sql.FromClause
, and then adds
this :class:_sql.Join
to the FROM clause of the newly generated
SELECT statement. This is completely reworked from the behavior
in 1.3, which would instead create a subquery of the entire
:class:_expression.Select
and then join that subquery to the
target.
This is a backwards incompatible change as the previous behavior
was mostly useless, producing an unnamed subquery rejected by
most databases in any case. The new behavior is modeled after
that of the very successful :meth:_orm.Query.join
method in the
ORM, in order to support the functionality of :class:_orm.Query
being available by using a :class:_sql.Select
object with an
:class:_orm.Session
.
See the notes for this change at :ref:change_select_join
.
:param target: target table to join towards
:param onclause: ON clause of the join. If omitted, an ON clause
is generated automatically based on the :class:_schema.ForeignKey
linkages between the two tables, if one can be unambiguously
determined, otherwise an error is raised.
:param isouter: if True, generate LEFT OUTER join. Same as
:meth:_expression.Select.outerjoin
.
:param full: if True, generate FULL OUTER join.
.. seealso::
:ref:`tutorial_select_join` - in the :doc:`/tutorial/index`
:ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel`
:meth:`_expression.Select.join_from`
:meth:`_expression.Select.outerjoin`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 |
|
outerjoin_from
outerjoin_from(
from_: _FromClauseArgument,
target: _JoinTargetArgument,
onclause: Optional[_OnClauseArgument] = None,
*,
full: bool = False,
) -> Self
Create a SQL LEFT OUTER JOIN against this
:class:_expression.Select
object's criterion and apply generatively,
returning the newly resulting :class:_expression.Select
.
Usage is the same as that of :meth:_selectable.Select.join_from
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
join_from
join_from(
from_: _FromClauseArgument,
target: _JoinTargetArgument,
onclause: Optional[_OnClauseArgument] = None,
*,
isouter: bool = False,
full: bool = False,
) -> Self
Create a SQL JOIN against this :class:_expression.Select
object's criterion
and apply generatively, returning the newly resulting
:class:_expression.Select
.
E.g.::
stmt = select(user_table, address_table).join_from(
user_table, address_table, user_table.c.id == address_table.c.user_id
)
The above statement generates SQL similar to::
SELECT user.id, user.name, address.id, address.email, address.user_id
FROM user JOIN address ON user.id = address.user_id
.. versionadded:: 1.4
:param from_: the left side of the join, will be rendered in the
FROM clause and is roughly equivalent to using the
:meth:.Select.select_from
method.
:param target: target table to join towards
:param onclause: ON clause of the join.
:param isouter: if True, generate LEFT OUTER join. Same as
:meth:_expression.Select.outerjoin
.
:param full: if True, generate FULL OUTER join.
.. seealso::
:ref:`tutorial_select_join` - in the :doc:`/tutorial/index`
:ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel`
:meth:`_expression.Select.join`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 |
|
outerjoin
outerjoin(
target: _JoinTargetArgument,
onclause: Optional[_OnClauseArgument] = None,
*,
full: bool = False,
) -> Self
Create a left outer join.
Parameters are the same as that of :meth:_expression.Select.join
.
.. versionchanged:: 1.4 :meth:_expression.Select.outerjoin
now
creates a :class:_sql.Join
object between a
:class:_sql.FromClause
source that is within the FROM clause of
the existing SELECT, and a given target :class:_sql.FromClause
,
and then adds this :class:_sql.Join
to the FROM clause of the
newly generated SELECT statement. This is completely reworked
from the behavior in 1.3, which would instead create a subquery of
the entire
:class:_expression.Select
and then join that subquery to the
target.
This is a backwards incompatible change as the previous behavior
was mostly useless, producing an unnamed subquery rejected by
most databases in any case. The new behavior is modeled after
that of the very successful :meth:_orm.Query.join
method in the
ORM, in order to support the functionality of :class:_orm.Query
being available by using a :class:_sql.Select
object with an
:class:_orm.Session
.
See the notes for this change at :ref:change_select_join
.
.. seealso::
:ref:`tutorial_select_join` - in the :doc:`/tutorial/index`
:ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel`
:meth:`_expression.Select.join`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
get_final_froms
get_final_froms() -> Sequence[FromClause]
Compute the final displayed list of :class:_expression.FromClause
elements.
This method will run through the full computation required to determine what FROM elements will be displayed in the resulting SELECT statement, including shadowing individual tables with JOIN objects, as well as full computation for ORM use cases including eager loading clauses.
For ORM use, this accessor returns the post compilation
list of FROM objects; this collection will include elements such as
eagerly loaded tables and joins. The objects will not be
ORM enabled and not work as a replacement for the
:meth:_sql.Select.select_froms
collection; additionally, the
method is not well performing for an ORM enabled statement as it
will incur the full ORM construction process.
To retrieve the FROM list that's implied by the "columns" collection
passed to the :class:_sql.Select
originally, use the
:attr:_sql.Select.columns_clause_froms
accessor.
To select from an alternative set of columns while maintaining the
FROM list, use the :meth:_sql.Select.with_only_columns
method and
pass the
:paramref:_sql.Select.with_only_columns.maintain_column_froms
parameter.
.. versionadded:: 1.4.23 - the :meth:_sql.Select.get_final_froms
method replaces the previous :attr:_sql.Select.froms
accessor,
which is deprecated.
.. seealso::
:attr:`_sql.Select.columns_clause_froms`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
add_columns
Return a new :func:_expression.select
construct with
the given entities appended to its columns clause.
E.g.::
my_select = my_select.add_columns(table.c.new_column)
The original expressions in the columns clause remain in place.
To replace the original expressions with new ones, see the method
:meth:_expression.Select.with_only_columns
.
:param *entities: column, table, or other entity expressions to be added to the columns clause
.. seealso::
:meth:`_expression.Select.with_only_columns` - replaces existing
expressions rather than appending.
:ref:`orm_queryguide_select_multiple_entities` - ORM-centric
example
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
column
Return a new :func:_expression.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
:meth:_expression.Select.with_only_columns
for guidelines on adding /replacing the columns of a
:class:_expression.Select
object.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
reduce_columns
Return a new :func:_expression.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
:meth:_expression.Select.set_label_style
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.
:param 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.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
with_only_columns
with_only_columns(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
) -> Select[Tuple[_T0, _T1]]
with_only_columns(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
) -> Select[Tuple[_T0, _T1, _T2]]
with_only_columns(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
) -> Select[Tuple[_T0, _T1, _T2, _T3]]
with_only_columns(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
__ent4: _TypedColumnClauseArgument[_T4],
) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4]]
with_only_columns(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
__ent4: _TypedColumnClauseArgument[_T4],
__ent5: _TypedColumnClauseArgument[_T5],
) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]]
with_only_columns(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
__ent4: _TypedColumnClauseArgument[_T4],
__ent5: _TypedColumnClauseArgument[_T5],
__ent6: _TypedColumnClauseArgument[_T6],
) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]]
with_only_columns(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
__ent4: _TypedColumnClauseArgument[_T4],
__ent5: _TypedColumnClauseArgument[_T5],
__ent6: _TypedColumnClauseArgument[_T6],
__ent7: _TypedColumnClauseArgument[_T7],
) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]]
with_only_columns(
*entities: _ColumnsClauseArgument[Any],
maintain_column_froms: bool = False,
**__kw: Any,
) -> Select[Any]
Return a new :func:_expression.select
construct with its columns
clause replaced with the given entities.
By default, this method is exactly equivalent to as if the original
:func:_expression.select
had been called with the given entities.
E.g. 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)
In this mode of operation, :meth:_sql.Select.with_only_columns
will also dynamically alter the FROM clause of the
statement if it is not explicitly stated.
To maintain the existing set of FROMs including those implied by the
current columns clause, add the
:paramref:_sql.Select.with_only_columns.maintain_column_froms
parameter::
s = select(table1.c.a, table2.c.b)
s = s.with_only_columns(table1.c.a, maintain_column_froms=True)
The above parameter performs a transfer of the effective FROMs
in the columns collection to the :meth:_sql.Select.select_from
method, as though the following were invoked::
s = select(table1.c.a, table2.c.b)
s = s.select_from(table1, table2).with_only_columns(table1.c.a)
The :paramref:_sql.Select.with_only_columns.maintain_column_froms
parameter makes use of the :attr:_sql.Select.columns_clause_froms
collection and performs an operation equivalent to the following::
s = select(table1.c.a, table2.c.b)
s = s.select_from(*s.columns_clause_froms).with_only_columns(table1.c.a)
:param *entities: column expressions to be used.
:param maintain_column_froms: boolean parameter that will ensure the
FROM list implied from the current columns clause will be transferred
to the :meth:_sql.Select.select_from
method first.
.. versionadded:: 1.4.23
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 |
|
where
where(
*whereclause: _ColumnExpressionArgument[bool],
) -> Self
Return a new :func:_expression.select
construct with
the given expression added to
its WHERE clause, joined to the existing clause via AND, if any.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
having
having(*having: _ColumnExpressionArgument[bool]) -> Self
Return a new :func:_expression.select
construct with
the given expression added to
its HAVING clause, joined to the existing clause via AND, if any.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
distinct
distinct(*expr: _ColumnExpressionArgument[Any]) -> Self
Return a new :func:_expression.select
construct which
will apply DISTINCT to its columns clause.
:param *expr: optional column expressions. When present,
the PostgreSQL dialect will render a DISTINCT ON (<expressions>>)
construct.
.. deprecated:: 1.4 Using *expr in other dialects is deprecated
and will raise :class:_exc.CompileError
in a future version.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
select_from
Return a new :func:_expression.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 :class:_schema.Table
or other selectable
will have no effect. Passing a :class:_expression.Join
that refers
to an already present :class:_schema.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 :meth:_expression.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)
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
correlate
correlate(
*fromclauses: Union[
Literal[None, False], _FromClauseArgument
],
) -> Self
Return a new :class:_expression.Select
which will correlate the given FROM
clauses to that of an enclosing :class:_expression.Select
.
Calling this method turns off the :class:_expression.Select
object's
default behavior of "auto-correlation". Normally, FROM elements
which appear in a :class:_expression.Select
that encloses this one via
its :term:WHERE clause
, ORDER BY, HAVING or
:term:columns clause
will be omitted from this
:class:_expression.Select
object's :term:FROM clause
.
Setting an explicit correlation collection using the
:meth:_expression.Select.correlate
method provides a fixed list of FROM objects
that can potentially take place in this process.
When :meth:_expression.Select.correlate
is used to apply specific FROM clauses
for correlation, the FROM elements become candidates for
correlation regardless of how deeply nested this
:class:_expression.Select
object is, relative to an enclosing :class:_expression.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
:class:_expression.Select
.
Multi-level correlation ensures that the link
between enclosed and enclosing :class:_expression.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 :class:_expression.Select
object will correlate
none of its FROM entries, and all will render unconditionally
in the local FROM clause.
:param *fromclauses: one or more :class:.FromClause
or other
FROM-compatible construct such as an ORM mapped entity to become part
of the correlate collection; alternatively pass a single value
None
to remove all existing correlations.
.. seealso::
:meth:`_expression.Select.correlate_except`
:ref:`tutorial_scalar_subquery`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 |
|
correlate_except
correlate_except(
*fromclauses: Union[
Literal[None, False], _FromClauseArgument
],
) -> Self
Return a new :class:_expression.Select
which will omit the given FROM
clauses from the auto-correlation process.
Calling :meth:_expression.Select.correlate_except
turns off the
:class:_expression.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, or no arguments are passed,
the :class:_expression.Select
object will correlate all of its
FROM entries.
:param *fromclauses: a list of one or more
:class:_expression.FromClause
constructs, or other compatible constructs (i.e. ORM-mapped
classes) to become part of the correlate-exception collection.
.. seealso::
:meth:`_expression.Select.correlate`
:ref:`tutorial_scalar_subquery`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
selected_columns
selected_columns() -> ColumnCollection[
str, ColumnElement[Any]
]
A :class:_expression.ColumnCollection
representing the columns that
this SELECT statement or similar construct returns in its result set,
not including :class:_sql.TextClause
constructs.
This collection differs from the :attr:_expression.FromClause.columns
collection of a :class:_expression.FromClause
in that the columns
within this collection cannot be directly nested inside another SELECT
statement; a subquery must be applied first which provides for the
necessary parenthesization required by SQL.
For a :func:_expression.select
construct, the collection here is
exactly what would be rendered inside the "SELECT" statement, and the
:class:_expression.ColumnElement
objects are directly present as they
were given, e.g.::
col1 = column('q', Integer)
col2 = column('p', Integer)
stmt = select(col1, col2)
Above, stmt.selected_columns
would be a collection that contains
the col1
and col2
objects directly. For a statement that is
against a :class:_schema.Table
or other
:class:_expression.FromClause
, the collection will use the
:class:_expression.ColumnElement
objects that are in the
:attr:_expression.FromClause.c
collection of the from element.
A use case for the :attr:_sql.Select.selected_columns
collection is
to allow the existing columns to be referenced when adding additional
criteria, e.g.::
def filter_on_id(my_select, id):
return my_select.where(my_select.selected_columns['id'] == id)
stmt = select(MyModel)
# adds "WHERE id=:param" to the statement
stmt = filter_on_id(stmt, 42)
.. note::
The :attr:`_sql.Select.selected_columns` collection does not
include expressions established in the columns clause using the
:func:`_sql.text` construct; these are silently omitted from the
collection. To use plain textual column expressions inside of a
:class:`_sql.Select` construct, use the :func:`_sql.literal_column`
construct.
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 |
|
union
union(
*other: _SelectStatementForCompoundArgument,
) -> CompoundSelect
Return a SQL UNION
of this select() construct against
the given selectables provided as positional arguments.
:param *other: one or more elements with which to create a UNION.
.. versionchanged:: 1.4.28
multiple elements are now accepted.
:param **kwargs: keyword arguments are forwarded to the constructor
for the newly created :class:_sql.CompoundSelect
object.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
union_all
union_all(
*other: _SelectStatementForCompoundArgument,
) -> CompoundSelect
Return a SQL UNION ALL
of this select() construct against
the given selectables provided as positional arguments.
:param *other: one or more elements with which to create a UNION.
.. versionchanged:: 1.4.28
multiple elements are now accepted.
:param **kwargs: keyword arguments are forwarded to the constructor
for the newly created :class:_sql.CompoundSelect
object.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
except_
except_(
*other: _SelectStatementForCompoundArgument,
) -> CompoundSelect
Return a SQL EXCEPT
of this select() construct against
the given selectable provided as positional arguments.
:param *other: one or more elements with which to create a UNION.
.. versionchanged:: 1.4.28
multiple elements are now accepted.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
except_all
except_all(
*other: _SelectStatementForCompoundArgument,
) -> CompoundSelect
Return a SQL EXCEPT ALL
of this select() construct against
the given selectables provided as positional arguments.
:param *other: one or more elements with which to create a UNION.
.. versionchanged:: 1.4.28
multiple elements are now accepted.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
intersect
intersect(
*other: _SelectStatementForCompoundArgument,
) -> CompoundSelect
Return a SQL INTERSECT
of this select() construct against
the given selectables provided as positional arguments.
:param *other: one or more elements with which to create a UNION.
.. versionchanged:: 1.4.28
multiple elements are now accepted.
:param **kwargs: keyword arguments are forwarded to the constructor
for the newly created :class:_sql.CompoundSelect
object.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
intersect_all
intersect_all(
*other: _SelectStatementForCompoundArgument,
) -> CompoundSelect
Return a SQL INTERSECT ALL
of this select() construct
against the given selectables provided as positional arguments.
:param *other: one or more elements with which to create a UNION.
.. versionchanged:: 1.4.28
multiple elements are now accepted.
:param **kwargs: keyword arguments are forwarded to the constructor
for the newly created :class:_sql.CompoundSelect
object.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
Selectable
Bases: ReturnsRows
Mark a class as being selectable.
inherit_cache
class-attribute
instance-attribute
Indicate if this :class:.HasCacheKey
instance should make use of the
cache key generation scheme used by its immediate superclass.
The attribute defaults to None
, which indicates that a construct has
not yet taken into account whether or not its appropriate for it to
participate in caching; this is functionally equivalent to setting the
value to False
, except that a warning is also emitted.
This flag can be set to True
on a particular class, if the SQL that
corresponds to the object does not change based on attributes which
are local to this class, and not its superclass.
.. seealso::
:ref:`compilerext_caching` - General guideslines for setting the
:attr:`.HasCacheKey.inherit_cache` attribute for third-party or user
defined SQL constructs.
exported_columns
property
A :class:_expression.ColumnCollection
that represents the "exported"
columns of this :class:_expression.ReturnsRows
.
The "exported" columns represent the collection of
:class:_expression.ColumnElement
expressions that are rendered by this SQL
construct. There are primary varieties which are the
"FROM clause columns" of a FROM clause, such as a table, join,
or subquery, the "SELECTed columns", which are the columns in
the "columns clause" of a SELECT statement, and the RETURNING
columns in a DML statement..
.. versionadded:: 1.4
.. seealso::
:attr:`_expression.FromClause.exported_columns`
:attr:`_expression.SelectBase.exported_columns`
memoized_attribute
Bases: memoized_property[_T]
A read-only @property that is only evaluated once.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
memoized_instancemethod
classmethod
Decorate a method memoize its return value.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
unique_params
Return a copy with :func:_expression.bindparam
elements
replaced.
Same functionality as :meth:_expression.ClauseElement.params
,
except adds unique=True
to affected bind parameters so that multiple statements can be
used.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
params
Return a copy with :func:_expression.bindparam
elements
replaced.
Returns a copy of this ClauseElement with
:func:_expression.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)
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
compare
compare(other: ClauseElement, **kw: Any) -> bool
Compare this :class:_expression.ClauseElement
to
the given :class:_expression.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 :class:_expression.ColumnElement
).
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
self_group
self_group(
against: Optional[OperatorType] = None,
) -> ClauseElement
Apply a 'grouping' to this :class:_expression.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 :func:_expression.select
constructs when placed into the FROM clause of another
:func:_expression.select
. (Note that subqueries should be
normally created using the :meth:_expression.Select.alias
method,
as many
platforms require nested SELECT statements to be named).
As expressions are composed together, the application of
:meth: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 :meth:self_group
method of
:class:_expression.ClauseElement
just returns self.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
is_derived_from
is_derived_from(fromclause: Optional[FromClause]) -> bool
Return True
if this :class:.ReturnsRows
is
'derived' from the given :class:.FromClause
.
An example would be an Alias of a Table is derived from that Table.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
lateral
Return a LATERAL alias of this :class:_expression.Selectable
.
The return value is the :class:_expression.Lateral
construct also
provided by the top-level :func:_expression.lateral
function.
.. seealso::
:ref:`tutorial_lateral_correlation` - overview of usage.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
replace_selectable
replace_selectable(old: FromClause, alias: Alias) -> Self
Replace all occurrences of :class:_expression.FromClause
'old' with the given :class:_expression.Alias
object, returning a copy of this :class:_expression.FromClause
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
corresponding_column
corresponding_column(
column: KeyedColumnElement[Any],
require_embedded: bool = False,
) -> Optional[KeyedColumnElement[Any]]
Given a :class:_expression.ColumnElement
, return the exported
:class:_expression.ColumnElement
object from the
:attr:_expression.Selectable.exported_columns
collection of this :class:_expression.Selectable
which corresponds to that
original :class:_expression.ColumnElement
via a common ancestor
column.
:param column: the target :class:_expression.ColumnElement
to be matched.
:param require_embedded: only return corresponding columns for
the given :class:_expression.ColumnElement
, if the given
:class:_expression.ColumnElement
is actually present within a sub-element
of this :class:_expression.Selectable
.
Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this :class:_expression.Selectable
.
.. seealso::
:attr:`_expression.Selectable.exported_columns` - the
:class:`_expression.ColumnCollection`
that is used for the operation.
:meth:`_expression.ColumnCollection.corresponding_column`
- implementation
method.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/selectable.py
UnaryExpression
UnaryExpression(
element: ColumnElement[Any],
operator: Optional[OperatorType] = None,
modifier: Optional[OperatorType] = None,
type_: Optional[_TypeEngineArgument[_T]] = None,
wraps_column_expression: bool = False,
)
Bases: ColumnElement[_T]
Define a 'unary' expression.
A unary expression has a single column expression and an operator. The operator can be placed on the left (where it is called the 'operator') or right (where it is called the 'modifier') of the column expression.
:class:.UnaryExpression
is the basis for several unary operators
including those used by :func:.desc
, :func:.asc
, :func:.distinct
,
:func:.nulls_first
and :func:.nulls_last
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
inherit_cache
class-attribute
instance-attribute
Indicate if this :class:.HasCacheKey
instance should make use of the
cache key generation scheme used by its immediate superclass.
The attribute defaults to None
, which indicates that a construct has
not yet taken into account whether or not its appropriate for it to
participate in caching; this is functionally equivalent to setting the
value to False
, except that a warning is also emitted.
This flag can be set to True
on a particular class, if the SQL that
corresponds to the object does not change based on attributes which
are local to this class, and not its superclass.
.. seealso::
:ref:`compilerext_caching` - General guideslines for setting the
:attr:`.HasCacheKey.inherit_cache` attribute for third-party or user
defined SQL constructs.
timetuple
class-attribute
instance-attribute
Hack, allows datetime objects to be compared on the LHS.
key
class-attribute
instance-attribute
The 'key' that in some circumstances refers to this object in a Python namespace.
This typically refers to the "key" of the column as present in the
.c
collection of a selectable, e.g. sometable.c["somekey"]
would
return a :class:_schema.Column
with a .key
of "somekey".
expression
property
expression: ColumnElement[Any]
Return a column expression.
Part of the inspection interface; returns self.
memoized_attribute
Bases: memoized_property[_T]
A read-only @property that is only evaluated once.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
memoized_instancemethod
classmethod
Decorate a method memoize its return value.
:meta private:
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/util/langhelpers.py
proxy_set
proxy_set() -> FrozenSet[ColumnElement[Any]]
set of all columns we are proxying
as of 2.0 this is explicitly deannotated columns. previously it was effectively deannotated columns but wasn't enforced. annotated columns should basically not go into sets if at all possible because their hashing behavior is very non-performant.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
unique_params
Return a copy with :func:_expression.bindparam
elements
replaced.
Same functionality as :meth:_expression.ClauseElement.params
,
except adds unique=True
to affected bind parameters so that multiple statements can be
used.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
params
Return a copy with :func:_expression.bindparam
elements
replaced.
Returns a copy of this ClauseElement with
:func:_expression.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)
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
compare
compare(other: ClauseElement, **kw: Any) -> bool
Compare this :class:_expression.ClauseElement
to
the given :class:_expression.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 :class:_expression.ColumnElement
).
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
label
Produce a column label, i.e. <columnname> AS <name>
.
This is a shortcut to the :func:_expression.label
function.
If 'name' is None
, an anonymous label name will be generated.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
shares_lineage
shares_lineage(othercolumn: ColumnElement[Any]) -> bool
Return True if the given :class:_expression.ColumnElement
has a common ancestor to this :class:_expression.ColumnElement
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
cast
cast(type_: _TypeEngineArgument[_OPT]) -> Cast[_OPT]
Produce a type cast, i.e. CAST(<expression> AS <type>)
.
This is a shortcut to the :func:_expression.cast
function.
.. seealso::
:ref:`tutorial_casts`
:func:`_expression.cast`
:func:`_expression.type_coerce`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
alias
alias(
selectable: FromClause,
name: Optional[str] = None,
flat: bool = False,
) -> NamedFromClause
Return a named alias of the given :class:.FromClause
.
For :class:.Table
and :class:.Join
objects, the return type is the
:class:_expression.Alias
object. Other kinds of :class:.NamedFromClause
objects may be returned for other kinds of :class:.FromClause
objects.
The named alias represents any :class:_expression.FromClause
with an
alternate name assigned within SQL, typically using the AS
clause when
generated, e.g. SELECT * FROM table AS aliasname
.
Equivalent functionality is available via the
:meth:_expression.FromClause.alias
method available on all :class:_expression.FromClause
objects.
:param selectable: any :class:_expression.FromClause
subclass,
such as a table, select statement, etc.
:param name: string name to be assigned as the alias.
If None
, a 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.
:param flat: Will be passed through to if the given selectable
is an instance of :class:_expression.Join
- see
:meth:_expression.Join.alias
for details.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_selectable_constructors.py
all_
all_(
expr: _ColumnExpressionArgument[_T],
) -> CollectionAggregate[bool]
Produce an ALL expression.
For dialects such as that of PostgreSQL, this operator applies
to usage of the :class:_types.ARRAY
datatype, for that of
MySQL, it may apply to a subquery. e.g.::
# renders on PostgreSQL:
# '5 = ALL (somearray)'
expr = 5 == all_(mytable.c.somearray)
# renders on MySQL:
# '5 = ALL (SELECT value FROM table)'
expr = 5 == all_(select(table.c.value))
Comparison to NULL may work using None
::
None == all_(mytable.c.somearray)
The any_() / all_() operators also feature a special "operand flipping"
behavior such that if any_() / all_() are used on the left side of a
comparison using a standalone operator such as ==
, !=
, etc.
(not including operator methods such as
:meth:_sql.ColumnOperators.is_
) the rendered expression is flipped::
# would render '5 = ALL (column)`
all_(mytable.c.column) == 5
Or with None
, which note will not perform
the usual step of rendering "IS" as is normally the case for NULL::
# would render 'NULL = ALL(somearray)'
all_(mytable.c.somearray) == None
.. versionchanged:: 1.4.26 repaired the use of any_() / all_() comparing to NULL on the right side to be flipped to the left.
The column-level :meth:_sql.ColumnElement.all_
method (not to be
confused with :class:_types.ARRAY
level
:meth:_types.ARRAY.Comparator.all
) is shorthand for
all_(col)
::
5 == mytable.c.somearray.all_()
.. seealso::
:meth:`_sql.ColumnOperators.all_`
:func:`_expression.any_`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
and_
Produce a conjunction of expressions joined by AND
.
E.g.::
from sqlalchemy import and_
stmt = select(users_table).where(
and_(
users_table.c.name == 'wendy',
users_table.c.enrolled == True
)
)
The :func:.and_
conjunction is also available using the
Python &
operator (though note that compound expressions
need to be parenthesized in order to function with Python
operator precedence behavior)::
stmt = select(users_table).where(
(users_table.c.name == 'wendy') &
(users_table.c.enrolled == True)
)
The :func:.and_
operation is also implicit in some cases;
the :meth:_expression.Select.where
method for example can be invoked multiple
times against a statement, which will have the effect of each
clause being combined using :func:.and_
::
stmt = select(users_table).\
where(users_table.c.name == 'wendy').\
where(users_table.c.enrolled == True)
The :func:.and_
construct must be given at least one positional
argument in order to be valid; a :func:.and_
construct with no
arguments is ambiguous. To produce an "empty" or dynamically
generated :func:.and_
expression, from a given list of expressions,
a "default" element of :func:_sql.true
(or just True
) should be
specified::
from sqlalchemy import true
criteria = and_(true(), *expressions)
The above expression will compile to SQL as the expression true
or 1 = 1
, depending on backend, if no other expressions are
present. If expressions are present, then the :func:_sql.true
value
is ignored as it does not affect the outcome of an AND expression that
has other elements.
.. deprecated:: 1.4 The :func:.and_
element now requires that at
least one argument is passed; creating the :func:.and_
construct
with no arguments is deprecated, and will emit a deprecation warning
while continuing to produce a blank SQL string.
.. seealso::
:func:`.or_`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
any_
any_(
expr: _ColumnExpressionArgument[_T],
) -> CollectionAggregate[bool]
Produce an ANY expression.
For dialects such as that of PostgreSQL, this operator applies
to usage of the :class:_types.ARRAY
datatype, for that of
MySQL, it may apply to a subquery. e.g.::
# renders on PostgreSQL:
# '5 = ANY (somearray)'
expr = 5 == any_(mytable.c.somearray)
# renders on MySQL:
# '5 = ANY (SELECT value FROM table)'
expr = 5 == any_(select(table.c.value))
Comparison to NULL may work using None
or :func:_sql.null
::
None == any_(mytable.c.somearray)
The any_() / all_() operators also feature a special "operand flipping"
behavior such that if any_() / all_() are used on the left side of a
comparison using a standalone operator such as ==
, !=
, etc.
(not including operator methods such as
:meth:_sql.ColumnOperators.is_
) the rendered expression is flipped::
# would render '5 = ANY (column)`
any_(mytable.c.column) == 5
Or with None
, which note will not perform
the usual step of rendering "IS" as is normally the case for NULL::
# would render 'NULL = ANY(somearray)'
any_(mytable.c.somearray) == None
.. versionchanged:: 1.4.26 repaired the use of any_() / all_() comparing to NULL on the right side to be flipped to the left.
The column-level :meth:_sql.ColumnElement.any_
method (not to be
confused with :class:_types.ARRAY
level
:meth:_types.ARRAY.Comparator.any
) is shorthand for
any_(col)
::
5 = mytable.c.somearray.any_()
.. seealso::
:meth:`_sql.ColumnOperators.any_`
:func:`_expression.all_`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
asc
asc(
column: _ColumnExpressionOrStrLabelArgument[_T],
) -> UnaryExpression[_T]
Produce an ascending ORDER BY
clause element.
e.g.::
from sqlalchemy import asc
stmt = select(users_table).order_by(asc(users_table.c.name))
will produce SQL as::
SELECT id, name FROM user ORDER BY name ASC
The :func:.asc
function is a standalone version of the
:meth:_expression.ColumnElement.asc
method available on all SQL expressions,
e.g.::
stmt = select(users_table).order_by(users_table.c.name.asc())
:param column: A :class:_expression.ColumnElement
(e.g.
scalar SQL expression)
with which to apply the :func:.asc
operation.
.. seealso::
:func:`.desc`
:func:`.nulls_first`
:func:`.nulls_last`
:meth:`_expression.Select.order_by`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
between
between(
expr: _ColumnExpressionOrLiteralArgument[_T],
lower_bound: Any,
upper_bound: Any,
symmetric: bool = False,
) -> BinaryExpression[bool]
Produce a BETWEEN
predicate clause.
E.g.::
from sqlalchemy import between
stmt = select(users_table).where(between(users_table.c.id, 5, 7))
Would produce SQL resembling::
SELECT id, name FROM user WHERE id BETWEEN :id_1 AND :id_2
The :func:.between
function is a standalone version of the
:meth:_expression.ColumnElement.between
method available on all
SQL expressions, as in::
stmt = select(users_table).where(users_table.c.id.between(5, 7))
All arguments passed to :func:.between
, including the left side
column expression, are coerced from Python scalar values if a
the value is not a :class:_expression.ColumnElement
subclass.
For example,
three fixed values can be compared as in::
print(between(5, 3, 7))
Which would produce::
:param_1 BETWEEN :param_2 AND :param_3
:param expr: a column expression, typically a
:class:_expression.ColumnElement
instance or alternatively a Python scalar expression to be coerced
into a column expression, serving as the left side of the BETWEEN
expression.
:param lower_bound: a column or Python scalar expression serving as the
lower bound of the right side of the BETWEEN
expression.
:param upper_bound: a column or Python scalar expression serving as the
upper bound of the right side of the BETWEEN
expression.
:param symmetric: if True, will render " BETWEEN SYMMETRIC ". Note that not all databases support this syntax.
.. seealso::
:meth:`_expression.ColumnElement.between`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
bindparam
bindparam(
key: Optional[str],
value: Any = NO_ARG,
type_: Optional[_TypeEngineArgument[_T]] = None,
unique: bool = False,
required: Union[bool, Literal[NO_ARG]] = NO_ARG,
quote: Optional[bool] = None,
callable_: Optional[Callable[[], Any]] = None,
expanding: bool = False,
isoutparam: bool = False,
literal_execute: bool = False,
) -> BindParameter[_T]
Produce a "bound expression".
The return value is an instance of :class:.BindParameter
; this
is a :class:_expression.ColumnElement
subclass which represents a so-called
"placeholder" value in a SQL expression, the value of which is
supplied at the point at which the statement in executed against a
database connection.
In SQLAlchemy, the :func:.bindparam
construct has
the ability to carry along the actual value that will be ultimately
used at expression time. In this way, it serves not just as
a "placeholder" for eventual population, but also as a means of
representing so-called "unsafe" values which should not be rendered
directly in a SQL statement, but rather should be passed along
to the :term:DBAPI
as values which need to be correctly escaped
and potentially handled for type-safety.
When using :func:.bindparam
explicitly, the use case is typically
one of traditional deferment of parameters; the :func:.bindparam
construct accepts a name which can then be referred to at execution
time::
from sqlalchemy import bindparam
stmt = select(users_table).\
where(users_table.c.name == bindparam('username'))
The above statement, when rendered, will produce SQL similar to::
SELECT id, name FROM user WHERE name = :username
In order to populate the value of :username
above, the value
would typically be applied at execution time to a method
like :meth:_engine.Connection.execute
::
result = connection.execute(stmt, username='wendy')
Explicit use of :func:.bindparam
is also common when producing
UPDATE or DELETE statements that are to be invoked multiple times,
where the WHERE criterion of the statement is to change on each
invocation, such as::
stmt = (users_table.update().
where(user_table.c.name == bindparam('username')).
values(fullname=bindparam('fullname'))
)
connection.execute(
stmt, [{"username": "wendy", "fullname": "Wendy Smith"},
{"username": "jack", "fullname": "Jack Jones"},
]
)
SQLAlchemy's Core expression system makes wide use of
:func:.bindparam
in an implicit sense. It is typical that Python
literal values passed to virtually all SQL expression functions are
coerced into fixed :func:.bindparam
constructs. For example, given
a comparison operation such as::
expr = users_table.c.name == 'Wendy'
The above expression will produce a :class:.BinaryExpression
construct, where the left side is the :class:_schema.Column
object
representing the name
column, and the right side is a
:class:.BindParameter
representing the literal value::
print(repr(expr.right))
BindParameter('%(4327771088 name)s', 'Wendy', type_=String())
The expression above will render SQL such as::
user.name = :name_1
Where the :name_1
parameter name is an anonymous name. The
actual string Wendy
is not in the rendered string, but is carried
along where it is later used within statement execution. If we
invoke a statement like the following::
stmt = select(users_table).where(users_table.c.name == 'Wendy')
result = connection.execute(stmt)
We would see SQL logging output as::
SELECT "user".id, "user".name
FROM "user"
WHERE "user".name = %(name_1)s
{'name_1': 'Wendy'}
Above, we see that Wendy
is passed as a parameter to the database,
while the placeholder :name_1
is rendered in the appropriate form
for the target database, in this case the PostgreSQL database.
Similarly, :func:.bindparam
is invoked automatically when working
with :term:CRUD
statements as far as the "VALUES" portion is
concerned. The :func:_expression.insert
construct produces an
INSERT
expression which will, at statement execution time, generate
bound placeholders based on the arguments passed, as in::
stmt = users_table.insert()
result = connection.execute(stmt, name='Wendy')
The above will produce SQL output as::
INSERT INTO "user" (name) VALUES (%(name)s)
{'name': 'Wendy'}
The :class:_expression.Insert
construct, at
compilation/execution time, rendered a single :func:.bindparam
mirroring the column name name
as a result of the single name
parameter we passed to the :meth:_engine.Connection.execute
method.
:param key:
the key (e.g. the name) for this bind param.
Will be used in the generated
SQL statement for dialects that use named parameters. This
value may be modified when part of a compilation operation,
if other :class:BindParameter
objects exist with the same
key, or if its length is too long and truncation is
required.
If omitted, an "anonymous" name is generated for the bound parameter;
when given a value to bind, the end result is equivalent to calling upon
the :func:.literal
function with a value to bind, particularly
if the :paramref:.bindparam.unique
parameter is also provided.
:param value:
Initial value for this bind param. Will be used at statement
execution time as the value for this parameter passed to the
DBAPI, if no other value is indicated to the statement execution
method for this particular parameter name. Defaults to None
.
:param callable_: A callable function that takes the place of "value". The function will be called at statement execution time to determine the ultimate value. Used for scenarios where the actual bind value cannot be determined at the point at which the clause construct is created, but embedded bind values are still desirable.
:param type_:
A :class:.TypeEngine
class or instance representing an optional
datatype for this :func:.bindparam
. If not passed, a type
may be determined automatically for the bind, based on the given
value; for example, trivial Python types such as str
,
int
, bool
may result in the :class:.String
, :class:.Integer
or
:class:.Boolean
types being automatically selected.
The type of a :func:.bindparam
is significant especially in that
the type will apply pre-processing to the value before it is
passed to the database. For example, a :func:.bindparam
which
refers to a datetime value, and is specified as holding the
:class:.DateTime
type, may apply conversion needed to the
value (such as stringification on SQLite) before passing the value
to the database.
:param unique:
if True, the key name of this :class:.BindParameter
will be
modified if another :class:.BindParameter
of the same name
already has been located within the containing
expression. This flag is used generally by the internals
when producing so-called "anonymous" bound expressions, it
isn't generally applicable to explicitly-named :func:.bindparam
constructs.
:param required:
If True
, a value is required at execution time. If not passed,
it defaults to True
if neither :paramref:.bindparam.value
or :paramref:.bindparam.callable
were passed. If either of these
parameters are present, then :paramref:.bindparam.required
defaults to False
.
:param quote: True if this parameter name requires quoting and is not currently known as a SQLAlchemy reserved word; this currently only applies to the Oracle backend, where bound names must sometimes be quoted.
:param isoutparam: if True, the parameter should be treated like a stored procedure "OUT" parameter. This applies to backends such as Oracle which support OUT parameters.
:param expanding: if True, this parameter will be treated as an "expanding" parameter at execution time; the parameter value is expected to be a sequence, rather than a scalar value, and the string SQL statement will be transformed on a per-execution basis to accommodate the sequence with a variable number of parameter slots passed to the DBAPI. This is to allow statement caching to be used in conjunction with an IN clause.
.. seealso::
:meth:`.ColumnOperators.in_`
:ref:`baked_in` - with baked queries
.. note:: The "expanding" feature does not support "executemany"- style parameter sets.
.. versionadded:: 1.2
.. versionchanged:: 1.3 the "expanding" bound parameter feature now supports empty lists.
:param literal_execute:
if True, the bound parameter will be rendered in the compile phase
with a special "POSTCOMPILE" token, and the SQLAlchemy compiler will
render the final value of the parameter into the SQL statement at
statement execution time, omitting the value from the parameter
dictionary / list passed to DBAPI cursor.execute()
. This
produces a similar effect as that of using the literal_binds
,
compilation flag, however takes place as the statement is sent to
the DBAPI cursor.execute()
method, rather than when the statement
is compiled. The primary use of this
capability is for rendering LIMIT / OFFSET clauses for database
drivers that can't accommodate for bound parameters in these
contexts, while allowing SQL constructs to be cacheable at the
compilation level.
.. versionadded:: 1.4 Added "post compile" bound parameters
.. seealso::
:ref:`change_4808`.
.. seealso::
:ref:`tutorial_sending_parameters` - in the
:ref:`unified_tutorial`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 |
|
case
case(
*whens: Union[
Tuple[_ColumnExpressionArgument[bool], Any],
Mapping[Any, Any],
],
value: Optional[Any] = None,
else_: Optional[Any] = None,
) -> Case[Any]
Produce a CASE
expression.
The CASE
construct in SQL is a conditional object that
acts somewhat analogously to an "if/then" construct in other
languages. It returns an instance of :class:.Case
.
:func:.case
in its usual form is passed a series of "when"
constructs, that is, a list of conditions and results as tuples::
from sqlalchemy import case
stmt = select(users_table).\
where(
case(
(users_table.c.name == 'wendy', 'W'),
(users_table.c.name == 'jack', 'J'),
else_='E'
)
)
The above statement will produce SQL resembling::
SELECT id, name FROM user
WHERE CASE
WHEN (name = :name_1) THEN :param_1
WHEN (name = :name_2) THEN :param_2
ELSE :param_3
END
When simple equality expressions of several values against a single
parent column are needed, :func:.case
also has a "shorthand" format
used via the
:paramref:.case.value
parameter, which is passed a column
expression to be compared. In this form, the :paramref:.case.whens
parameter is passed as a dictionary containing expressions to be
compared against keyed to result expressions. The statement below is
equivalent to the preceding statement::
stmt = select(users_table).\
where(
case(
{"wendy": "W", "jack": "J"},
value=users_table.c.name,
else_='E'
)
)
The values which are accepted as result values in
:paramref:.case.whens
as well as with :paramref:.case.else_
are
coerced from Python literals into :func:.bindparam
constructs.
SQL expressions, e.g. :class:_expression.ColumnElement
constructs,
are accepted
as well. To coerce a literal string expression into a constant
expression rendered inline, use the :func:_expression.literal_column
construct,
as in::
from sqlalchemy import case, literal_column
case(
(
orderline.c.qty > 100,
literal_column("'greaterthan100'")
),
(
orderline.c.qty > 10,
literal_column("'greaterthan10'")
),
else_=literal_column("'lessthan10'")
)
The above will render the given constants without using bound parameters for the result values (but still for the comparison values), as in::
CASE
WHEN (orderline.qty > :qty_1) THEN 'greaterthan100'
WHEN (orderline.qty > :qty_2) THEN 'greaterthan10'
ELSE 'lessthan10'
END
:param *whens: The criteria to be compared against,
:paramref:.case.whens
accepts two different forms, based on
whether or not :paramref:.case.value
is used.
.. versionchanged:: 1.4 the :func:_sql.case
function now accepts the series of WHEN conditions positionally
In the first form, it accepts multiple 2-tuples passed as positional
arguments; each 2-tuple consists of (<sql expression>, <value>)
,
where the SQL expression is a boolean expression and "value" is a
resulting value, e.g.::
case(
(users_table.c.name == 'wendy', 'W'),
(users_table.c.name == 'jack', 'J')
)
In the second form, it accepts a Python dictionary of comparison
values mapped to a resulting value; this form requires
:paramref:.case.value
to be present, and values will be compared
using the ==
operator, e.g.::
case(
{"wendy": "W", "jack": "J"},
value=users_table.c.name
)
:param value: An optional SQL expression which will be used as a
fixed "comparison point" for candidate values within a dictionary
passed to :paramref:.case.whens
.
:param else_: An optional SQL expression which will be the evaluated
result of the CASE
construct if all expressions within
:paramref:.case.whens
evaluate to false. When omitted, most
databases will produce a result of NULL if none of the "when"
expressions evaluate to true.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 |
|
cast
cast(
expression: _ColumnExpressionOrLiteralArgument[Any],
type_: _TypeEngineArgument[_T],
) -> Cast[_T]
Produce a CAST
expression.
:func:.cast
returns an instance of :class:.Cast
.
E.g.::
from sqlalchemy import cast, Numeric
stmt = select(cast(product_table.c.unit_price, Numeric(10, 4)))
The above statement will produce SQL resembling::
SELECT CAST(unit_price AS NUMERIC(10, 4)) FROM product
The :func:.cast
function performs two distinct functions when
used. The first is that it renders the CAST
expression within
the resulting SQL string. The second is that it associates the given
type (e.g. :class:.TypeEngine
class or instance) with the column
expression on the Python side, which means the expression will take
on the expression operator behavior associated with that type,
as well as the bound-value handling and result-row-handling behavior
of the type.
An alternative to :func:.cast
is the :func:.type_coerce
function.
This function performs the second task of associating an expression
with a specific type, but does not render the CAST
expression
in SQL.
:param expression: A SQL expression, such as a
:class:_expression.ColumnElement
expression or a Python string which will be coerced into a bound
literal value.
:param type_: A :class:.TypeEngine
class or instance indicating
the type to which the CAST
should apply.
.. seealso::
:ref:`tutorial_casts`
:func:`.try_cast` - an alternative to CAST that results in
NULLs when the cast fails, instead of raising an error.
Only supported by some dialects.
:func:`.type_coerce` - an alternative to CAST that coerces the type
on the Python side only, which is often sufficient to generate the
correct SQL and data coercion.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
collate
collate(
expression: _ColumnExpressionArgument[str],
collation: str,
) -> BinaryExpression[str]
Return the clause expression COLLATE collation
.
e.g.::
collate(mycolumn, 'utf8_bin')
produces::
mycolumn COLLATE utf8_bin
The collation expression is also quoted if it is a case sensitive identifier, e.g. contains uppercase characters.
.. versionchanged:: 1.2 quoting is automatically applied to COLLATE expressions if they are case sensitive.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
column
column(
text: str,
type_: Optional[_TypeEngineArgument[_T]] = None,
is_literal: bool = False,
_selectable: Optional[FromClause] = None,
) -> ColumnClause[_T]
Produce a :class:.ColumnClause
object.
The :class:.ColumnClause
is a lightweight analogue to the
:class:_schema.Column
class. The :func:_expression.column
function can
be invoked with just a name alone, as in::
from sqlalchemy import column
id, name = column("id"), column("name")
stmt = select(id, name).select_from("user")
The above statement would produce SQL like::
SELECT id, name FROM user
Once constructed, :func:_expression.column
may be used like any other SQL
expression element such as within :func:_expression.select
constructs::
from sqlalchemy.sql import column
id, name = column("id"), column("name")
stmt = select(id, name).select_from("user")
The text handled by :func:_expression.column
is assumed to be handled
like the name of a database column; if the string contains mixed case,
special characters, or matches a known reserved word on the target
backend, the column expression will render using the quoting
behavior determined by the backend. To produce a textual SQL
expression that is rendered exactly without any quoting,
use :func:_expression.literal_column
instead,
or pass True
as the
value of :paramref:_expression.column.is_literal
. Additionally,
full SQL
statements are best handled using the :func:_expression.text
construct.
:func:_expression.column
can be used in a table-like
fashion by combining it with the :func:.table
function
(which is the lightweight analogue to :class:_schema.Table
) to produce
a working table construct with minimal boilerplate::
from sqlalchemy import table, column, select
user = table("user",
column("id"),
column("name"),
column("description"),
)
stmt = select(user.c.description).where(user.c.name == 'wendy')
A :func:_expression.column
/ :func:.table
construct like that illustrated
above can be created in an
ad-hoc fashion and is not associated with any
:class:_schema.MetaData
, DDL, or events, unlike its
:class:_schema.Table
counterpart.
:param text: the text of the element.
:param type: :class:_types.TypeEngine
object which can associate
this :class:.ColumnClause
with a type.
:param is_literal: if True, the :class:.ColumnClause
is assumed to
be an exact expression that will be delivered to the output with no
quoting rules applied regardless of case sensitive settings. the
:func:_expression.literal_column()
function essentially invokes
:func:_expression.column
while passing is_literal=True
.
.. seealso::
:class:`_schema.Column`
:func:`_expression.literal_column`
:func:`.table`
:func:`_expression.text`
:ref:`tutorial_select_arbitrary_text`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 |
|
cte
Return a new :class:_expression.CTE
,
or Common Table Expression instance.
Please see :meth:_expression.HasCTE.cte
for detail on CTE usage.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_selectable_constructors.py
delete
delete(table: _DMLTableArgument) -> Delete
Construct :class:_expression.Delete
object.
E.g.::
from sqlalchemy import delete
stmt = (
delete(user_table).
where(user_table.c.id == 5)
)
Similar functionality is available via the
:meth:_expression.TableClause.delete
method on
:class:_schema.Table
.
:param table: The table to delete rows from.
.. seealso::
:ref:`tutorial_core_update_delete` - in the :ref:`unified_tutorial`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_dml_constructors.py
desc
desc(
column: _ColumnExpressionOrStrLabelArgument[_T],
) -> UnaryExpression[_T]
Produce a descending ORDER BY
clause element.
e.g.::
from sqlalchemy import desc
stmt = select(users_table).order_by(desc(users_table.c.name))
will produce SQL as::
SELECT id, name FROM user ORDER BY name DESC
The :func:.desc
function is a standalone version of the
:meth:_expression.ColumnElement.desc
method available on all SQL expressions,
e.g.::
stmt = select(users_table).order_by(users_table.c.name.desc())
:param column: A :class:_expression.ColumnElement
(e.g.
scalar SQL expression)
with which to apply the :func:.desc
operation.
.. seealso::
:func:`.asc`
:func:`.nulls_first`
:func:`.nulls_last`
:meth:`_expression.Select.order_by`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
distinct
distinct(
expr: _ColumnExpressionArgument[_T],
) -> UnaryExpression[_T]
Produce an column-expression-level unary DISTINCT
clause.
This applies the DISTINCT
keyword to an individual column
expression, and is typically contained within an aggregate function,
as in::
from sqlalchemy import distinct, func
stmt = select(func.count(distinct(users_table.c.name)))
The above would produce an expression resembling::
SELECT COUNT(DISTINCT name) FROM user
The :func:.distinct
function is also available as a column-level
method, e.g. :meth:_expression.ColumnElement.distinct
, as in::
stmt = select(func.count(users_table.c.name.distinct()))
The :func:.distinct
operator is different from the
:meth:_expression.Select.distinct
method of
:class:_expression.Select
,
which produces a SELECT
statement
with DISTINCT
applied to the result set as a whole,
e.g. a SELECT DISTINCT
expression. See that method for further
information.
.. seealso::
:meth:`_expression.ColumnElement.distinct`
:meth:`_expression.Select.distinct`
:data:`.func`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
except_
except_(
*selects: _SelectStatementForCompoundArgument,
) -> CompoundSelect
Return an EXCEPT
of multiple selectables.
The returned object is an instance of
:class:_expression.CompoundSelect
.
:param *selects:
a list of :class:_expression.Select
instances.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_selectable_constructors.py
except_all
except_all(
*selects: _SelectStatementForCompoundArgument,
) -> CompoundSelect
Return an EXCEPT ALL
of multiple selectables.
The returned object is an instance of
:class:_expression.CompoundSelect
.
:param *selects:
a list of :class:_expression.Select
instances.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_selectable_constructors.py
exists
exists(
__argument: Optional[
Union[
_ColumnsClauseArgument[Any],
SelectBase,
ScalarSelect[Any],
]
] = None,
) -> Exists
Construct a new :class:_expression.Exists
construct.
The :func:_sql.exists
can be invoked by itself to produce an
:class:_sql.Exists
construct, which will accept simple WHERE
criteria::
exists_criteria = exists().where(table1.c.col1 == table2.c.col2)
However, for greater flexibility in constructing the SELECT, an
existing :class:_sql.Select
construct may be converted to an
:class:_sql.Exists
, most conveniently by making use of the
:meth:_sql.SelectBase.exists
method::
exists_criteria = (
select(table2.c.col2).
where(table1.c.col1 == table2.c.col2).
exists()
)
The EXISTS criteria is then used inside of an enclosing SELECT::
stmt = select(table1.c.col1).where(exists_criteria)
The above statement will then be of the form::
SELECT col1 FROM table1 WHERE EXISTS
(SELECT table2.col2 FROM table2 WHERE table2.col2 = table1.col1)
.. seealso::
:ref:`tutorial_exists` - in the :term:`2.0 style` tutorial.
:meth:`_sql.SelectBase.exists` - method to transform a ``SELECT`` to an
``EXISTS`` clause.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_selectable_constructors.py
extract
Return a :class:.Extract
construct.
This is typically available as :func:.extract
as well as func.extract
from the
:data:.func
namespace.
:param field: The field to extract.
:param expr: A column or Python scalar expression serving as the
right side of the EXTRACT
expression.
E.g.::
from sqlalchemy import extract
from sqlalchemy import table, column
logged_table = table("user",
column("id"),
column("date_created"),
)
stmt = select(logged_table.c.id).where(
extract("YEAR", logged_table.c.date_created) == 2021
)
In the above example, the statement is used to select ids from the
database where the YEAR
component matches a specific value.
Similarly, one can also select an extracted component::
stmt = select(
extract("YEAR", logged_table.c.date_created)
).where(logged_table.c.id == 1)
The implementation of EXTRACT
may vary across database backends.
Users are reminded to consult their database documentation.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
false
false() -> False_
Return a :class:.False_
construct.
E.g.:
.. sourcecode:: pycon+sql
>>> from sqlalchemy import false
>>> print(select(t.c.x).where(false()))
{printsql}SELECT x FROM t WHERE false
A backend which does not support true/false constants will render as an expression against 1 or 0:
.. sourcecode:: pycon+sql
>>> print(select(t.c.x).where(false()))
{printsql}SELECT x FROM t WHERE 0 = 1
The :func:.true
and :func:.false
constants also feature
"short circuit" operation within an :func:.and_
or :func:.or_
conjunction:
.. sourcecode:: pycon+sql
>>> print(select(t.c.x).where(or_(t.c.x > 5, true())))
{printsql}SELECT x FROM t WHERE true{stop}
>>> print(select(t.c.x).where(and_(t.c.x > 5, false())))
{printsql}SELECT x FROM t WHERE false{stop}
.. seealso::
:func:`.true`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
funcfilter
funcfilter(
func: FunctionElement[_T],
*criterion: _ColumnExpressionArgument[bool],
) -> FunctionFilter[_T]
Produce a :class:.FunctionFilter
object against a function.
Used against aggregate and window functions, for database backends that support the "FILTER" clause.
E.g.::
from sqlalchemy import funcfilter
funcfilter(func.count(1), MyClass.name == 'some name')
Would produce "COUNT(1) FILTER (WHERE myclass.name = 'some name')".
This function is also available from the :data:~.expression.func
construct itself via the :meth:.FunctionElement.filter
method.
.. seealso::
:ref:`tutorial_functions_within_group` - in the
:ref:`unified_tutorial`
:meth:`.FunctionElement.filter`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
insert
insert(table: _DMLTableArgument) -> Insert
Construct an :class:_expression.Insert
object.
E.g.::
from sqlalchemy import insert
stmt = (
insert(user_table).
values(name='username', fullname='Full Username')
)
Similar functionality is available via the
:meth:_expression.TableClause.insert
method on
:class:_schema.Table
.
.. seealso::
:ref:`tutorial_core_insert` - in the :ref:`unified_tutorial`
:param table: :class:_expression.TableClause
which is the subject of the
insert.
:param values: collection of values to be inserted; see
:meth:_expression.Insert.values
for a description of allowed formats here.
Can be omitted entirely; a :class:_expression.Insert
construct
will also dynamically render the VALUES clause at execution time
based on the parameters passed to :meth:_engine.Connection.execute
.
:param inline: if True, no attempt will be made to retrieve the SQL-generated default values to be provided within the statement; in particular, this allows SQL expressions to be rendered 'inline' within the statement without the need to pre-execute them beforehand; for backends that support "returning", this turns off the "implicit returning" feature for the statement.
If both :paramref:_expression.insert.values
and compile-time bind
parameters are present, the compile-time bind parameters override the
information specified within :paramref:_expression.insert.values
on a
per-key basis.
The keys within :paramref:_expression.Insert.values
can be either
:class:~sqlalchemy.schema.Column
objects or their string
identifiers. Each key may reference one of:
- a literal data value (i.e. string, number, etc.);
- a Column object;
- a SELECT statement.
If a SELECT
statement is specified which references this
INSERT
statement's table, the statement will be correlated
against the INSERT
statement.
.. seealso::
:ref:`tutorial_core_insert` - in the :ref:`unified_tutorial`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_dml_constructors.py
intersect
intersect(
*selects: _SelectStatementForCompoundArgument,
) -> CompoundSelect
Return an INTERSECT
of multiple selectables.
The returned object is an instance of
:class:_expression.CompoundSelect
.
:param *selects:
a list of :class:_expression.Select
instances.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_selectable_constructors.py
intersect_all
intersect_all(
*selects: _SelectStatementForCompoundArgument,
) -> CompoundSelect
Return an INTERSECT ALL
of multiple selectables.
The returned object is an instance of
:class:_expression.CompoundSelect
.
:param *selects:
a list of :class:_expression.Select
instances.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_selectable_constructors.py
join
join(
left: _FromClauseArgument,
right: _FromClauseArgument,
onclause: Optional[_OnClauseArgument] = None,
isouter: bool = False,
full: bool = False,
) -> Join
Produce a :class:_expression.Join
object, given two
:class:_expression.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
:class:_expression.FromClause
object (e.g. such as a
:class:_schema.Table
) using
the :meth:_expression.FromClause.join
method.
:param left: The left side of the join.
:param right: the right side of the join; this is any
:class:_expression.FromClause
object such as a
:class:_schema.Table
object, and
may also be a selectable-compatible object such as an ORM-mapped
class.
:param onclause: a SQL expression representing the ON clause of the
join. If left at None
, :meth:_expression.FromClause.join
will attempt to
join the two tables based on a foreign key relationship.
:param isouter: if True, render a LEFT OUTER JOIN, instead of JOIN.
:param full: if True, render a FULL OUTER JOIN, instead of JOIN.
.. seealso::
:meth:`_expression.FromClause.join` - method form,
based on a given left side.
:class:`_expression.Join` - the type of object produced.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_selectable_constructors.py
label
label(
name: str,
element: _ColumnExpressionArgument[_T],
type_: Optional[_TypeEngineArgument[_T]] = None,
) -> Label[_T]
Return a :class:Label
object for the
given :class:_expression.ColumnElement
.
A label changes the name of an element in the columns clause of a
SELECT
statement, typically via the AS
SQL keyword.
This functionality is more conveniently available via the
:meth:_expression.ColumnElement.label
method on
:class:_expression.ColumnElement
.
:param name: label name
:param obj: a :class:_expression.ColumnElement
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
lambda_stmt
lambda_stmt(
lmb: _StmtLambdaType,
enable_tracking: bool = True,
track_closure_variables: bool = True,
track_on: Optional[object] = None,
global_track_bound_values: bool = True,
track_bound_values: bool = True,
lambda_cache: Optional[_LambdaCacheType] = None,
) -> StatementLambdaElement
Produce a SQL statement that is cached as a lambda.
The Python code object within the lambda is scanned for both Python literals that will become bound parameters as well as closure variables that refer to Core or ORM constructs that may vary. The lambda itself will be invoked only once per particular set of constructs detected.
E.g.::
from sqlalchemy import lambda_stmt
stmt = lambda_stmt(lambda: table.select())
stmt += lambda s: s.where(table.c.id == 5)
result = connection.execute(stmt)
The object returned is an instance of :class:_sql.StatementLambdaElement
.
.. versionadded:: 1.4
:param lmb: a Python function, typically a lambda, which takes no arguments
and returns a SQL expression construct
:param enable_tracking: when False, all scanning of the given lambda for
changes in closure variables or bound parameters is disabled. Use for
a lambda that produces the identical results in all cases with no
parameterization.
:param track_closure_variables: when False, changes in closure variables
within the lambda will not be scanned. Use for a lambda where the
state of its closure variables will never change the SQL structure
returned by the lambda.
:param track_bound_values: when False, bound parameter tracking will
be disabled for the given lambda. Use for a lambda that either does
not produce any bound values, or where the initial bound values never
change.
:param global_track_bound_values: when False, bound parameter tracking
will be disabled for the entire statement including additional links
added via the :meth:_sql.StatementLambdaElement.add_criteria
method.
:param lambda_cache: a dictionary or other mapping-like object where
information about the lambda's Python code as well as the tracked closure
variables in the lambda itself will be stored. Defaults
to a global LRU cache. This cache is independent of the "compiled_cache"
used by the :class:_engine.Connection
object.
.. seealso::
:ref:`engine_lambda_caching`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/lambdas.py
lateral
lateral(
selectable: Union[SelectBase, _FromClauseArgument],
name: Optional[str] = None,
) -> LateralFromClause
Return a :class:_expression.Lateral
object.
:class:_expression.Lateral
is an :class:_expression.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.
.. seealso::
:ref:`tutorial_lateral_correlation` - overview of usage.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_selectable_constructors.py
literal
literal(
value: Any,
type_: _TypeEngineArgument[_T],
literal_execute: bool = False,
) -> BindParameter[_T]
literal(
value: _T,
type_: None = None,
literal_execute: bool = False,
) -> BindParameter[_T]
literal(
value: Any,
type_: Optional[_TypeEngineArgument[Any]] = None,
literal_execute: bool = False,
) -> BindParameter[Any]
Return a literal clause, bound to a bind parameter.
Literal clauses are created automatically when non-
:class:_expression.ClauseElement
objects (such as strings, ints, dates,
etc.) are
used in a comparison operation with a :class:_expression.ColumnElement
subclass,
such as a :class:~sqlalchemy.schema.Column
object. Use this function
to force the generation of a literal clause, which will be created as a
:class:BindParameter
with a bound value.
:param value: the value to be bound. Can be any Python object supported by the underlying DB-API, or is translatable via the given type argument.
:param type_: an optional :class:~sqlalchemy.types.TypeEngine
which will
provide bind-parameter translation for this literal.
:param literal_execute: optional bool, when True, the SQL engine will attempt to render the bound value directly in the SQL statement at execution time rather than providing as a parameter value.
.. versionadded:: 2.0
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
literal_column
literal_column(
text: str,
type_: Optional[_TypeEngineArgument[_T]] = None,
) -> ColumnClause[_T]
Produce a :class:.ColumnClause
object that has the
:paramref:_expression.column.is_literal
flag set to True.
:func:_expression.literal_column
is similar to
:func:_expression.column
, except that
it is more often used as a "standalone" column expression that renders
exactly as stated; while :func:_expression.column
stores a string name that
will be assumed to be part of a table and may be quoted as such,
:func:_expression.literal_column
can be that,
or any other arbitrary column-oriented
expression.
:param text: the text of the expression; can be any SQL expression.
Quoting rules will not be applied. To specify a column-name expression
which should be subject to quoting rules, use the :func:column
function.
:param type_: an optional :class:~sqlalchemy.types.TypeEngine
object which will
provide result-set translation and additional expression semantics for
this column. If left as None
the type will be :class:.NullType
.
.. seealso::
:func:`_expression.column`
:func:`_expression.text`
:ref:`tutorial_select_arbitrary_text`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/elements.py
not_
not_(clause: BinaryExpression[_T]) -> BinaryExpression[_T]
not_(
clause: _ColumnExpressionArgument[_T],
) -> ColumnElement[_T]
not_(
clause: _ColumnExpressionArgument[_T],
) -> ColumnElement[_T]
Return a negation of the given clause, i.e. NOT(clause)
.
The ~
operator is also overloaded on all
:class:_expression.ColumnElement
subclasses to produce the
same result.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
null
null() -> Null
nulls_first
nulls_first(
column: _ColumnExpressionArgument[_T],
) -> UnaryExpression[_T]
Produce the NULLS FIRST
modifier for an ORDER BY
expression.
:func:.nulls_first
is intended to modify the expression produced
by :func:.asc
or :func:.desc
, and indicates how NULL values
should be handled when they are encountered during ordering::
from sqlalchemy import desc, nulls_first
stmt = select(users_table).order_by(
nulls_first(desc(users_table.c.name)))
The SQL expression from the above would resemble::
SELECT id, name FROM user ORDER BY name DESC NULLS FIRST
Like :func:.asc
and :func:.desc
, :func:.nulls_first
is typically
invoked from the column expression itself using
:meth:_expression.ColumnElement.nulls_first
,
rather than as its standalone
function version, as in::
stmt = select(users_table).order_by(
users_table.c.name.desc().nulls_first())
.. versionchanged:: 1.4 :func:.nulls_first
is renamed from
:func:.nullsfirst
in previous releases.
The previous name remains available for backwards compatibility.
.. seealso::
:func:`.asc`
:func:`.desc`
:func:`.nulls_last`
:meth:`_expression.Select.order_by`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
nulls_last
nulls_last(
column: _ColumnExpressionArgument[_T],
) -> UnaryExpression[_T]
Produce the NULLS LAST
modifier for an ORDER BY
expression.
:func:.nulls_last
is intended to modify the expression produced
by :func:.asc
or :func:.desc
, and indicates how NULL values
should be handled when they are encountered during ordering::
from sqlalchemy import desc, nulls_last
stmt = select(users_table).order_by(
nulls_last(desc(users_table.c.name)))
The SQL expression from the above would resemble::
SELECT id, name FROM user ORDER BY name DESC NULLS LAST
Like :func:.asc
and :func:.desc
, :func:.nulls_last
is typically
invoked from the column expression itself using
:meth:_expression.ColumnElement.nulls_last
,
rather than as its standalone
function version, as in::
stmt = select(users_table).order_by(
users_table.c.name.desc().nulls_last())
.. versionchanged:: 1.4 :func:.nulls_last
is renamed from
:func:.nullslast
in previous releases.
The previous name remains available for backwards compatibility.
.. seealso::
:func:`.asc`
:func:`.desc`
:func:`.nulls_first`
:meth:`_expression.Select.order_by`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
or_
Produce a conjunction of expressions joined by OR
.
E.g.::
from sqlalchemy import or_
stmt = select(users_table).where(
or_(
users_table.c.name == 'wendy',
users_table.c.name == 'jack'
)
)
The :func:.or_
conjunction is also available using the
Python |
operator (though note that compound expressions
need to be parenthesized in order to function with Python
operator precedence behavior)::
stmt = select(users_table).where(
(users_table.c.name == 'wendy') |
(users_table.c.name == 'jack')
)
The :func:.or_
construct must be given at least one positional
argument in order to be valid; a :func:.or_
construct with no
arguments is ambiguous. To produce an "empty" or dynamically
generated :func:.or_
expression, from a given list of expressions,
a "default" element of :func:_sql.false
(or just False
) should be
specified::
from sqlalchemy import false
or_criteria = or_(false(), *expressions)
The above expression will compile to SQL as the expression false
or 0 = 1
, depending on backend, if no other expressions are
present. If expressions are present, then the :func:_sql.false
value
is ignored as it does not affect the outcome of an OR expression which
has other elements.
.. deprecated:: 1.4 The :func:.or_
element now requires that at
least one argument is passed; creating the :func:.or_
construct
with no arguments is deprecated, and will emit a deprecation warning
while continuing to produce a blank SQL string.
.. seealso::
:func:`.and_`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
outerjoin
outerjoin(
left: _FromClauseArgument,
right: _FromClauseArgument,
onclause: Optional[_OnClauseArgument] = None,
full: bool = False,
) -> Join
Return an OUTER JOIN
clause element.
The returned object is an instance of :class:_expression.Join
.
Similar functionality is also available via the
:meth:_expression.FromClause.outerjoin
method on any
:class:_expression.FromClause
.
:param left: The left side of the join.
:param right: The right side of the join.
:param onclause: Optional criterion for the ON
clause, is
derived from foreign key relationships established between
left and right otherwise.
To chain joins together, use the :meth:_expression.FromClause.join
or
:meth:_expression.FromClause.outerjoin
methods on the resulting
:class:_expression.Join
object.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_selectable_constructors.py
outparam
outparam(
key: str, type_: Optional[TypeEngine[_T]] = None
) -> BindParameter[_T]
Create an 'OUT' parameter for usage in functions (stored procedures), for databases which support them.
The outparam
can be used like a regular function parameter.
The "output" value will be available from the
:class:~sqlalchemy.engine.CursorResult
object via its out_parameters
attribute, which returns a dictionary containing the values.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
over
over(
element: FunctionElement[_T],
partition_by: Optional[_ByArgument] = None,
order_by: Optional[_ByArgument] = None,
range_: Optional[
Tuple[Optional[int], Optional[int]]
] = None,
rows: Optional[
Tuple[Optional[int], Optional[int]]
] = None,
) -> Over[_T]
Produce an :class:.Over
object against a function.
Used against aggregate or so-called "window" functions, for database backends that support window functions.
:func:_expression.over
is usually called using
the :meth:.FunctionElement.over
method, e.g.::
func.row_number().over(order_by=mytable.c.some_column)
Would produce::
ROW_NUMBER() OVER(ORDER BY some_column)
Ranges are also possible using the :paramref:.expression.over.range_
and :paramref:.expression.over.rows
parameters. These
mutually-exclusive parameters each accept a 2-tuple, which contains
a combination of integers and None::
func.row_number().over(
order_by=my_table.c.some_column, range_=(None, 0))
The above would produce::
ROW_NUMBER() OVER(ORDER BY some_column
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
A value of None
indicates "unbounded", a
value of zero indicates "current row", and negative / positive
integers indicate "preceding" and "following":
-
RANGE BETWEEN 5 PRECEDING AND 10 FOLLOWING::
func.row_number().over(order_by='x', range_=(-5, 10))
-
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW::
func.row_number().over(order_by='x', rows=(None, 0))
-
RANGE BETWEEN 2 PRECEDING AND UNBOUNDED FOLLOWING::
func.row_number().over(order_by='x', range_=(-2, None))
-
RANGE BETWEEN 1 FOLLOWING AND 3 FOLLOWING::
func.row_number().over(order_by='x', range_=(1, 3))
:param element: a :class:.FunctionElement
, :class:.WithinGroup
,
or other compatible construct.
:param partition_by: a column element or string, or a list
of such, that will be used as the PARTITION BY clause
of the OVER construct.
:param order_by: a column element or string, or a list
of such, that will be used as the ORDER BY clause
of the OVER construct.
:param range_: optional range clause for the window. This is a
tuple value which can contain integer values or None
,
and will render a RANGE BETWEEN PRECEDING / FOLLOWING clause.
:param rows: optional rows clause for the window. This is a tuple value which can contain integer values or None, and will render a ROWS BETWEEN PRECEDING / FOLLOWING clause.
This function is also available from the :data:~.expression.func
construct itself via the :meth:.FunctionElement.over
method.
.. seealso::
:ref:`tutorial_window_functions` - in the :ref:`unified_tutorial`
:data:`.expression.func`
:func:`_expression.within_group`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 |
|
select
select(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
) -> Select[Tuple[_T0, _T1]]
select(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
) -> Select[Tuple[_T0, _T1, _T2]]
select(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
) -> Select[Tuple[_T0, _T1, _T2, _T3]]
select(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
__ent4: _TypedColumnClauseArgument[_T4],
) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4]]
select(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
__ent4: _TypedColumnClauseArgument[_T4],
__ent5: _TypedColumnClauseArgument[_T5],
) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]]
select(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
__ent4: _TypedColumnClauseArgument[_T4],
__ent5: _TypedColumnClauseArgument[_T5],
__ent6: _TypedColumnClauseArgument[_T6],
) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]]
select(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
__ent4: _TypedColumnClauseArgument[_T4],
__ent5: _TypedColumnClauseArgument[_T5],
__ent6: _TypedColumnClauseArgument[_T6],
__ent7: _TypedColumnClauseArgument[_T7],
) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]]
select(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
__ent4: _TypedColumnClauseArgument[_T4],
__ent5: _TypedColumnClauseArgument[_T5],
__ent6: _TypedColumnClauseArgument[_T6],
__ent7: _TypedColumnClauseArgument[_T7],
__ent8: _TypedColumnClauseArgument[_T8],
) -> Select[
Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8]
]
select(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
__ent4: _TypedColumnClauseArgument[_T4],
__ent5: _TypedColumnClauseArgument[_T5],
__ent6: _TypedColumnClauseArgument[_T6],
__ent7: _TypedColumnClauseArgument[_T7],
__ent8: _TypedColumnClauseArgument[_T8],
__ent9: _TypedColumnClauseArgument[_T9],
) -> Select[
Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8, _T9]
]
Construct a new :class:_expression.Select
.
.. versionadded:: 1.4 - The :func:_sql.select
function now accepts
column arguments positionally. The top-level :func:_sql.select
function will automatically use the 1.x or 2.x style API based on
the incoming arguments; using :func:_sql.select
from the
sqlalchemy.future
module will enforce that only the 2.x style
constructor is used.
Similar functionality is also available via the
:meth:_expression.FromClause.select
method on any
:class:_expression.FromClause
.
.. seealso::
:ref:`tutorial_selecting_data` - in the :ref:`unified_tutorial`
:param *entities:
Entities to SELECT from. For Core usage, this is typically a series
of :class:_expression.ColumnElement
and / or
:class:_expression.FromClause
objects which will form the columns clause of the resulting
statement. For those objects that are instances of
:class:_expression.FromClause
(typically :class:_schema.Table
or :class:_expression.Alias
objects), the :attr:_expression.FromClause.c
collection is extracted
to form a collection of :class:_expression.ColumnElement
objects.
This parameter will also accept :class:_expression.TextClause
constructs as
given, as well as ORM-mapped classes.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_selectable_constructors.py
table
table(
name: str, *columns: ColumnClause[Any], **kw: Any
) -> TableClause
Produce a new :class:_expression.TableClause
.
The object returned is an instance of
:class:_expression.TableClause
, which
represents the "syntactical" portion of the schema-level
:class:_schema.Table
object.
It may be used to construct lightweight table constructs.
:param name: Name of the table.
:param columns: A collection of :func:_expression.column
constructs.
:param schema: The schema name for this table.
.. versionadded:: 1.3.18 :func:`_expression.table` can now
accept a ``schema`` argument.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_selectable_constructors.py
tablesample
tablesample(
selectable: _FromClauseArgument,
sampling: Union[float, Function[Any]],
name: Optional[str] = None,
seed: Optional[ExpressionElementRole[Any]] = None,
) -> TableSample
Return a :class:_expression.TableSample
object.
:class:_expression.TableSample
is an :class:_expression.Alias
subclass that represents
a table with the TABLESAMPLE clause applied to it.
:func:_expression.tablesample
is also available from the :class:_expression.FromClause
class via the
:meth:_expression.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())
:param sampling: a float
percentage between 0 and 100 or
:class:_functions.Function
.
:param name: optional alias name
:param seed: any real-valued SQL expression. When specified, the REPEATABLE sub-clause is also rendered.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_selectable_constructors.py
text
text(text: str) -> TextClause
Construct a new :class:_expression.TextClause
clause,
representing
a textual SQL string directly.
E.g.::
from sqlalchemy import text
t = text("SELECT * FROM users")
result = connection.execute(t)
The advantages :func:_expression.text
provides over a plain string are
backend-neutral support for bind parameters, per-statement
execution options, as well as
bind parameter and result-column typing behavior, allowing
SQLAlchemy type constructs to play a role when executing
a statement that is specified literally. The construct can also
be provided with a .c
collection of column elements, allowing
it to be embedded in other SQL expression constructs as a subquery.
Bind parameters are specified by name, using the format :name
.
E.g.::
t = text("SELECT * FROM users WHERE id=:user_id")
result = connection.execute(t, user_id=12)
For SQL statements where a colon is required verbatim, as within an inline string, use a backslash to escape::
t = text(r"SELECT * FROM users WHERE name='\:username'")
The :class:_expression.TextClause
construct includes methods which can
provide information about the bound parameters as well as the column
values which would be returned from the textual statement, assuming
it's an executable SELECT type of statement. The
:meth:_expression.TextClause.bindparams
method is used to provide bound
parameter detail, and :meth:_expression.TextClause.columns
method allows
specification of return columns including names and types::
t = text("SELECT * FROM users WHERE id=:user_id").\
bindparams(user_id=7).\
columns(id=Integer, name=String)
for id, name in connection.execute(t):
print(id, name)
The :func:_expression.text
construct is used in cases when
a literal string SQL fragment is specified as part of a larger query,
such as for the WHERE clause of a SELECT statement::
s = select(users.c.id, users.c.name).where(text("id=:user_id"))
result = connection.execute(s, user_id=12)
:func:_expression.text
is also used for the construction
of a full, standalone statement using plain text.
As such, SQLAlchemy refers
to it as an :class:.Executable
object and may be used
like any other statement passed to an .execute()
method.
:param text:
the text of the SQL statement to be created. Use :<param>
to specify bind parameters; they will be compiled to their
engine-specific format.
.. seealso::
:ref:`tutorial_select_arbitrary_text`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 |
|
true
true() -> True_
Return a constant :class:.True_
construct.
E.g.:
.. sourcecode:: pycon+sql
>>> from sqlalchemy import true
>>> print(select(t.c.x).where(true()))
{printsql}SELECT x FROM t WHERE true
A backend which does not support true/false constants will render as an expression against 1 or 0:
.. sourcecode:: pycon+sql
>>> print(select(t.c.x).where(true()))
{printsql}SELECT x FROM t WHERE 1 = 1
The :func:.true
and :func:.false
constants also feature
"short circuit" operation within an :func:.and_
or :func:.or_
conjunction:
.. sourcecode:: pycon+sql
>>> print(select(t.c.x).where(or_(t.c.x > 5, true())))
{printsql}SELECT x FROM t WHERE true{stop}
>>> print(select(t.c.x).where(and_(t.c.x > 5, false())))
{printsql}SELECT x FROM t WHERE false{stop}
.. seealso::
:func:`.false`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
tuple_
tuple_(
*clauses: _ColumnExpressionArgument[Any],
types: Optional[
Sequence[_TypeEngineArgument[Any]]
] = None,
) -> Tuple
Return a :class:.Tuple
.
Main usage is to produce a composite IN construct using
:meth:.ColumnOperators.in_
::
from sqlalchemy import tuple_
tuple_(table.c.col1, table.c.col2).in_(
[(1, 2), (5, 12), (10, 19)]
)
.. versionchanged:: 1.3.6 Added support for SQLite IN tuples.
.. warning::
The composite IN construct is not supported by all backends, and is
currently known to work on PostgreSQL, MySQL, and SQLite.
Unsupported backends will raise a subclass of
:class:`~sqlalchemy.exc.DBAPIError` when such an expression is
invoked.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
type_coerce
type_coerce(
expression: _ColumnExpressionOrLiteralArgument[Any],
type_: _TypeEngineArgument[_T],
) -> TypeCoerce[_T]
Associate a SQL expression with a particular type, without rendering
CAST
.
E.g.::
from sqlalchemy import type_coerce
stmt = select(type_coerce(log_table.date_string, StringDateTime()))
The above construct will produce a :class:.TypeCoerce
object, which
does not modify the rendering in any way on the SQL side, with the
possible exception of a generated label if used in a columns clause
context:
.. sourcecode:: sql
SELECT date_string AS date_string FROM log
When result rows are fetched, the StringDateTime
type processor
will be applied to result rows on behalf of the date_string
column.
.. note:: the :func:.type_coerce
construct does not render any
SQL syntax of its own, including that it does not imply
parenthesization. Please use :meth:.TypeCoerce.self_group
if explicit parenthesization is required.
In order to provide a named label for the expression, use
:meth:_expression.ColumnElement.label
::
stmt = select(
type_coerce(log_table.date_string, StringDateTime()).label('date')
)
A type that features bound-value handling will also have that behavior
take effect when literal values or :func:.bindparam
constructs are
passed to :func:.type_coerce
as targets.
For example, if a type implements the
:meth:.TypeEngine.bind_expression
method or :meth:.TypeEngine.bind_processor
method or equivalent,
these functions will take effect at statement compilation/execution
time when a literal value is passed, as in::
# bound-value handling of MyStringType will be applied to the
# literal value "some string"
stmt = select(type_coerce("some string", MyStringType))
When using :func:.type_coerce
with composed expressions, note that
parenthesis are not applied. If :func:.type_coerce
is being
used in an operator context where the parenthesis normally present from
CAST are necessary, use the :meth:.TypeCoerce.self_group
method:
.. sourcecode:: pycon+sql
>>> some_integer = column("someint", Integer)
>>> some_string = column("somestr", String)
>>> expr = type_coerce(some_integer + 5, String) + some_string
>>> print(expr)
{printsql}someint + :someint_1 || somestr{stop}
>>> expr = type_coerce(some_integer + 5, String).self_group() + some_string
>>> print(expr)
{printsql}(someint + :someint_1) || somestr{stop}
:param expression: A SQL expression, such as a
:class:_expression.ColumnElement
expression or a Python string which will be coerced into a bound
literal value.
:param type_: A :class:.TypeEngine
class or instance indicating
the type to which the expression is coerced.
.. seealso::
:ref:`tutorial_casts`
:func:`.cast`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_elements_constructors.py
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 |
|
union
union(
*selects: _SelectStatementForCompoundArgument,
) -> CompoundSelect
Return a UNION
of multiple selectables.
The returned object is an instance of
:class:_expression.CompoundSelect
.
A similar :func:union()
method is available on all
:class:_expression.FromClause
subclasses.
:param *selects:
a list of :class:_expression.Select
instances.
:param **kwargs:
available keyword arguments are the same as those of
:func:select
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_selectable_constructors.py
union_all
union_all(
*selects: _SelectStatementForCompoundArgument,
) -> CompoundSelect
Return a UNION ALL
of multiple selectables.
The returned object is an instance of
:class:_expression.CompoundSelect
.
A similar :func:union_all()
method is available on all
:class:_expression.FromClause
subclasses.
:param *selects:
a list of :class:_expression.Select
instances.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_selectable_constructors.py
update
update(table: _DMLTableArgument) -> Update
Construct an :class:_expression.Update
object.
E.g.::
from sqlalchemy import update
stmt = (
update(user_table).
where(user_table.c.id == 5).
values(name='user #5')
)
Similar functionality is available via the
:meth:_expression.TableClause.update
method on
:class:_schema.Table
.
:param table: A :class:_schema.Table
object representing the database
table to be updated.
.. seealso::
:ref:`tutorial_core_update_delete` - in the :ref:`unified_tutorial`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_dml_constructors.py
values
values(
*columns: ColumnClause[Any],
name: Optional[str] = None,
literal_binds: bool = False,
) -> Values
Construct a :class:_expression.Values
construct.
The column expressions and the actual data for
:class:_expression.Values
are given in two separate steps. The
constructor receives the column expressions typically as
:func:_expression.column
constructs,
and the data is then passed via the
:meth:_expression.Values.data
method as a list,
which can be called multiple
times to add more data, e.g.::
from sqlalchemy import column
from sqlalchemy import values
value_expr = values(
column('id', Integer),
column('name', String),
name="my_values"
).data(
[(1, 'name1'), (2, 'name2'), (3, 'name3')]
)
:param *columns: column expressions, typically composed using
:func:_expression.column
objects.
:param name: the name for this VALUES construct. If omitted, the VALUES construct will be unnamed in a SQL expression. Different backends may have different requirements here.
:param literal_binds: Defaults to False. Whether or not to render the data values inline in the SQL output, rather than using bound parameters.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/sql/_selectable_constructors.py
within_group
within_group(
element: FunctionElement[_T],
*order_by: _ColumnExpressionArgument[Any],
) -> WithinGroup[_T]
Produce a :class:.WithinGroup
object against a function.
Used against so-called "ordered set aggregate" and "hypothetical
set aggregate" functions, including :class:.percentile_cont
,
:class:.rank
, :class:.dense_rank
, etc.
:func:_expression.within_group
is usually called using
the :meth:.FunctionElement.within_group
method, e.g.::
from sqlalchemy import within_group
stmt = select(
department.c.id,
func.percentile_cont(0.5).within_group(
department.c.salary.desc()
)
)
The above statement would produce SQL similar to
SELECT department.id, percentile_cont(0.5)
WITHIN GROUP (ORDER BY department.salary DESC)
.
:param element: a :class:.FunctionElement
construct, typically
generated by :data:~.expression.func
.
:param *order_by: one or more column elements that will be used
as the ORDER BY clause of the WITHIN GROUP construct.
.. seealso::
:ref:`tutorial_functions_within_group` - in the
:ref:`unified_tutorial`
:data:`.expression.func`
:func:`_expression.over`