The expression API consists of a series of classes each of which represents a
specific lexical element within a SQL string. Composed together
into a larger structure, they form a statement construct that may
be compiled into a string representation that can be passed to a database.
The classes are organized into a hierarchy that begins at the basemost
ClauseElement
class. Key subclasses include ColumnElement
,
which represents the role of any column-based expression
in a SQL statement, such as in the columns clause, WHERE clause, and ORDER BY
clause, and FromClause
, which represents the role of a token that
is placed in the FROM clause of a SELECT statement.
Standalone functions imported from the sqlalchemy
namespace which are
used when building up SQLAlchemy Expression Language constructs.
Object Name | Description |
---|---|
and_(*clauses) |
Produce a conjunction of expressions joined by |
bindparam(key[, value, type_, unique, ...]) |
Produce a “bound expression”. |
case(*whens, **kw) |
Produce a |
cast(expression, type_) |
Produce a |
column(text[, type_, is_literal, _selectable]) |
Produce a |
Represent a ‘custom’ operator. |
|
distinct(expr) |
Produce an column-expression-level unary |
extract(field, expr, **kwargs) |
Return a |
false() |
Return a |
Generate SQL function expressions. |
|
lambda_stmt(lmb[, enable_tracking, track_closure_variables, track_on, ...]) |
Produce a SQL statement that is cached as a lambda. |
literal(value[, type_]) |
Return a literal clause, bound to a bind parameter. |
literal_column(text[, type_]) |
Produce a |
not_(clause) |
Return a negation of the given clause, i.e. |
null() |
Return a constant |
or_(*clauses) |
Produce a conjunction of expressions joined by |
outparam(key[, type_]) |
Create an ‘OUT’ parameter for usage in functions (stored procedures), for databases which support them. |
Represent a SQL identifier combined with quoting preferences. |
|
text(text[, bind]) |
Construct a new |
true() |
Return a constant |
tuple_(*clauses, **kw) |
Return a |
type_coerce(expression, type_) |
Associate a SQL expression with a particular type, without rendering
|
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 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 and_()
operation is also implicit in some cases;
the Select.where()
method for example can be invoked multiple
times against a statement, which will have the effect of each
clause being combined using and_()
:
stmt = select(users_table).\
where(users_table.c.name == 'wendy').\
where(users_table.c.enrolled == True)
The and_()
construct must be given at least one positional
argument in order to be valid; a and_()
construct with no
arguments is ambiguous. To produce an “empty” or dynamically
generated and_()
expression, from a given list of expressions,
a “default” element of True
should be specified:
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 True
value is
ignored as it does not affect the outcome of an AND expression that
has other elements.
Deprecated since version 1.4: The and_()
element now requires that at
least one argument is passed; creating the and_()
construct
with no arguments is deprecated, and will emit a deprecation warning
while continuing to produce a blank SQL string.
See also
Produce a “bound expression”.
The return value is an instance of BindParameter
; this
is a 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 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 DBAPI as values which need to be correctly escaped
and potentially handled for type-safety.
When using bindparam()
explicitly, the use case is typically
one of traditional deferment of parameters; the 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 Connection.execute()
:
result = connection.execute(stmt, username='wendy')
Explicit use of 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
bindparam()
in an implicit sense. It is typical that Python
literal values passed to virtually all SQL expression functions are
coerced into fixed bindparam()
constructs. For example, given
a comparison operation such as:
expr = users_table.c.name == 'Wendy'
The above expression will produce a BinaryExpression
construct, where the left side is the Column
object
representing the name
column, and the right side is a
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, bindparam()
is invoked automatically when working
with CRUD statements as far as the “VALUES” portion is
concerned. The 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 Insert
construct, at
compilation/execution time, rendered a single bindparam()
mirroring the column name name
as a result of the single name
parameter we passed to the Connection.execute()
method.
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 BindParameter
objects exist with the same
key, or if its length is too long and truncation is
required.
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
.
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.
type_¶ –
A TypeEngine
class or instance representing an optional
datatype for this 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 String
, Integer
or
Boolean
types being automatically selected.
The type of a 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 bindparam()
which
refers to a datetime value, and is specified as holding the
DateTime
type, may apply conversion needed to the
value (such as stringification on SQLite) before passing the value
to the database.
unique¶ – if True, the key name of this BindParameter
will be
modified if another 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 bindparam()
constructs.
required¶ – If True
, a value is required at execution time. If not passed,
it defaults to True
if neither bindparam.value
or bindparam.callable
were passed. If either of these
parameters are present, then bindparam.required
defaults to False
.
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.
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.
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.
Note
The “expanding” feature does not support “executemany”- style parameter sets.
New in version 1.2.
Changed in version 1.3: the “expanding” bound parameter feature now supports empty lists.
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.
New in version 1.4: Added “post compile” bound parameters
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 Case
.
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, case()
also has a “shorthand” format
used via the
case.value
parameter, which is passed a column
expression to be compared. In this form, the 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
case.whens
as well as with case.else_
are
coerced from Python literals into bindparam()
constructs.
SQL expressions, e.g. ColumnElement
constructs,
are accepted
as well. To coerce a literal string expression into a constant
expression rendered inline, use the 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
*whens¶ –
The criteria to be compared against,
case.whens
accepts two different forms, based on
whether or not case.value
is used.
Changed in version 1.4: the case()
function now accepts the series of WHEN conditions positionally;
passing the expressions within a list is deprecated.
In the first form, it accepts a list of 2-tuples; 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
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
)
value¶ – An optional SQL expression which will be used as a
fixed “comparison point” for candidate values within a dictionary
passed to case.whens
.
else_¶ – An optional SQL expression which will be the evaluated
result of the CASE
construct if all expressions within
case.whens
evaluate to false. When omitted, most
databases will produce a result of NULL if none of the “when”
expressions evaluate to true.
Produce a CAST
expression.
cast()
returns an instance of 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 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. 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.
Changed in version 0.9.0: cast()
now applies the given type
to the expression such that it takes effect on the bound-value,
e.g. the Python-to-database direction, in addition to the
result handling, e.g. database-to-Python, direction.
An alternative to cast()
is the 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.
expression¶ – A SQL expression, such as a
ColumnElement
expression or a Python string which will be coerced into a bound
literal value.
type_¶ – A TypeEngine
class or instance indicating
the type to which the CAST
should apply.
See also
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.
Produce a ColumnClause
object.
The ColumnClause
is a lightweight analogue to the
Column
class. The 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, column()
may be used like any other SQL
expression element such as within select()
constructs:
from sqlalchemy.sql import column
id, name = column("id"), column("name")
stmt = select(id, name).select_from("user")
The text handled by 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 literal_column()
instead,
or pass True
as the
value of column.is_literal
. Additionally,
full SQL
statements are best handled using the text()
construct.
column()
can be used in a table-like
fashion by combining it with the table()
function
(which is the lightweight analogue to 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 column()
/ table()
construct like that illustrated
above can be created in an
ad-hoc fashion and is not associated with any
MetaData
, DDL, or events, unlike its
Table
counterpart.
Changed in version 1.0.0: column()
can now
be imported from the plain sqlalchemy
namespace like any
other SQL element.
text¶ – the text of the element.
type¶ – TypeEngine
object which can associate
this ColumnClause
with a type.
is_literal¶ – if True, the 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
literal_column()
function essentially invokes
column()
while passing is_literal=True
.
Represent a ‘custom’ operator.
custom_op
is normally instantiated when the
Operators.op()
or Operators.bool_op()
methods
are used to create a custom operator callable. The class can also be
used directly when programmatically constructing expressions. E.g.
to represent the “factorial” operation:
from sqlalchemy.sql import UnaryExpression
from sqlalchemy.sql import operators
from sqlalchemy import Numeric
unary = UnaryExpression(table.c.somecolumn,
modifier=operators.custom_op("!"),
type_=Numeric)
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 distinct()
function is also available as a column-level
method, e.g. ColumnElement.distinct()
, as in:
stmt = select(func.count(users_table.c.name.distinct()))
The distinct()
operator is different from the
Select.distinct()
method of
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.
Return a Extract
construct.
This is typically available as extract()
as well as func.extract
from the
func
namespace.
Return a False_
construct.
E.g.:
>>> from sqlalchemy import false
>>> print(select(t.c.x).where(false()))
SELECT x FROM t WHERE false
A backend which does not support true/false constants will render as an expression against 1 or 0:
>>> print(select(t.c.x).where(false()))
SELECT x FROM t WHERE 0 = 1
The true()
and false()
constants also feature
“short circuit” operation within an and_()
or or_()
conjunction:
>>> print(select(t.c.x).where(or_(t.c.x > 5, true())))
SELECT x FROM t WHERE true
>>> print(select(t.c.x).where(and_(t.c.x > 5, false())))
SELECT x FROM t WHERE false
Changed in version 0.9: true()
and false()
feature
better integrated behavior within conjunctions and on dialects
that don’t support true/false constants.
See also
Generate SQL function expressions.
func
is a special object instance which generates SQL
functions based on name-based attributes, e.g.:
>>> print(func.count(1))
count(:param_1)
The returned object is an instance of Function
, and is a
column-oriented SQL element like any other, and is used in that way:
>>> print(select(func.count(table.c.id)))
SELECT count(sometable.id) FROM sometable
Any name can be given to func
. If the function name is unknown to
SQLAlchemy, it will be rendered exactly as is. For common SQL functions
which SQLAlchemy is aware of, the name may be interpreted as a generic
function which will be compiled appropriately to the target database:
>>> print(func.current_timestamp())
CURRENT_TIMESTAMP
To call functions which are present in dot-separated packages, specify them in the same manner:
>>> print(func.stats.yield_curve(5, 10))
stats.yield_curve(:yield_curve_1, :yield_curve_2)
SQLAlchemy can be made aware of the return type of functions to enable
type-specific lexical and result-based behavior. For example, to ensure
that a string-based function returns a Unicode value and is similarly
treated as a string in expressions, specify
Unicode
as the type:
>>> print(func.my_string(u'hi', type_=Unicode) + ' ' +
... func.my_string(u'there', type_=Unicode))
my_string(:my_string_1) || :my_string_2 || my_string(:my_string_3)
The object returned by a func
call is usually an instance of
Function
.
This object meets the “column” interface, including comparison and labeling
functions. The object can also be passed the Connectable.execute()
method of a Connection
or Engine
,
where it will be
wrapped inside of a SELECT statement first:
print(connection.execute(func.current_timestamp()).scalar())
In a few exception cases, the func
accessor
will redirect a name to a built-in expression such as cast()
or extract()
, as these names have well-known meaning
but are not exactly the same as “functions” from a SQLAlchemy
perspective.
Functions which are interpreted as “generic” functions know how to calculate their return type automatically. For a listing of known generic functions, see SQL and Generic Functions.
Note
The func
construct has only limited support for calling
standalone “stored procedures”, especially those with special
parameterization concerns.
See the section Calling Stored Procedures for details on how to use
the DBAPI-level callproc()
method for fully traditional stored
procedures.
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 StatementLambdaElement
.
New in version 1.4.
lmb¶ – a Python function, typically a lambda, which takes no arguments and returns a SQL expression construct
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.
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.
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.
global_track_bound_values¶ – when False, bound parameter tracking
will be disabled for the entire statement including additional links
added via the StatementLambdaElement.add_criteria()
method.
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 Connection
object.
Return a literal clause, bound to a bind parameter.
Literal clauses are created automatically when non-
ClauseElement
objects (such as strings, ints, dates,
etc.) are
used in a comparison operation with a ColumnElement
subclass,
such as a Column
object. Use this function
to force the generation of a literal clause, which will be created as a
BindParameter
with a bound value.
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.
type_¶ – an optional TypeEngine
which
will provide bind-parameter translation for this literal.
Produce a ColumnClause
object that has the
column.is_literal
flag set to True.
literal_column()
is similar to
column()
, except that
it is more often used as a “standalone” column expression that renders
exactly as stated; while column()
stores a string name that
will be assumed to be part of a table and may be quoted as such,
literal_column()
can be that,
or any other arbitrary column-oriented
expression.
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 column()
function.
type_¶ – an optional TypeEngine
object which will
provide result-set translation and additional expression semantics for
this column. If left as None
the type will be NullType
.
Return a negation of the given clause, i.e. NOT(clause)
.
The ~
operator is also overloaded on all
ColumnElement
subclasses to produce the
same result.
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 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 or_()
construct must be given at least one positional
argument in order to be valid; a or_()
construct with no
arguments is ambiguous. To produce an “empty” or dynamically
generated or_()
expression, from a given list of expressions,
a “default” element of False
should be specified:
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 False
value is
ignored as it does not affect the outcome of an OR expression which
has other elements.
Deprecated since version 1.4: The or_()
element now requires that at
least one argument is passed; creating the or_()
construct
with no arguments is deprecated, and will emit a deprecation warning
while continuing to produce a blank SQL string.
See also
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
CursorResult
object via its out_parameters
attribute, which returns a dictionary containing the values.
Construct a new 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 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("SELECT * FROM users WHERE name='\:username'")
The 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
TextClause.bindparams()
method is used to provide bound
parameter detail, and 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 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)
text()
is also used for the construction
of a full, standalone statement using plain text.
As such, SQLAlchemy refers
to it as an Executable
object, and it supports
the Executable.execution_options()
method. For example,
a text()
construct that should be subject to “autocommit”
can be set explicitly so using the
Connection.execution_options.autocommit
option:
t = text("EXEC my_procedural_thing()").\
execution_options(autocommit=True)
Deprecated since version 1.4: The “autocommit” execution option is deprecated and will be removed in SQLAlchemy 2.0. See Library-level (but not driver level) “Autocommit” removed from both Core and ORM for discussion.
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.
bind¶ –
an optional connection or engine to be used for this text query.
Deprecated since version 1.4: The text.bind
argument is deprecated and will be removed in SQLAlchemy 2.0.
See also
Using Textual SQL - in the Core tutorial
Return a constant True_
construct.
E.g.:
>>> from sqlalchemy import true
>>> print(select(t.c.x).where(true()))
SELECT x FROM t WHERE true
A backend which does not support true/false constants will render as an expression against 1 or 0:
>>> print(select(t.c.x).where(true()))
SELECT x FROM t WHERE 1 = 1
The true()
and false()
constants also feature
“short circuit” operation within an and_()
or or_()
conjunction:
>>> print(select(t.c.x).where(or_(t.c.x > 5, true())))
SELECT x FROM t WHERE true
>>> print(select(t.c.x).where(and_(t.c.x > 5, false())))
SELECT x FROM t WHERE false
Changed in version 0.9: true()
and false()
feature
better integrated behavior within conjunctions and on dialects
that don’t support true/false constants.
See also
Return a Tuple
.
Main usage is to produce a composite IN construct using
ColumnOperators.in_()
from sqlalchemy import tuple_
tuple_(table.c.col1, table.c.col2).in_(
[(1, 2), (5, 12), (10, 19)]
)
Changed in version 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
DBAPIError
when such an expression is
invoked.
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 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:
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 type_coerce()
construct does not render any
SQL syntax of its own, including that it does not imply
parenthesization. Please use TypeCoerce.self_group()
if explicit parenthesization is required.
In order to provide a named label for the expression, use
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 bindparam()
constructs are
passed to type_coerce()
as targets.
For example, if a type implements the
TypeEngine.bind_expression()
method or 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 type_coerce()
with composed expressions, note that
parenthesis are not applied. If type_coerce()
is being
used in an operator context where the parenthesis normally present from
CAST are necessary, use the TypeCoerce.self_group()
method:
>>> some_integer = column("someint", Integer)
>>> some_string = column("somestr", String)
>>> expr = type_coerce(some_integer + 5, String) + some_string
>>> print(expr)
someint + :someint_1 || somestr
>>> expr = type_coerce(some_integer + 5, String).self_group() + some_string
>>> print(expr)
(someint + :someint_1) || somestr
expression¶ – A SQL expression, such as a
ColumnElement
expression or a Python string which will be coerced into a bound
literal value.
type_¶ – A TypeEngine
class or instance indicating
the type to which the expression is coerced.
Represent a SQL identifier combined with quoting preferences.
quoted_name
is a Python unicode/str subclass which
represents a particular identifier name along with a
quote
flag. This quote
flag, when set to
True
or False
, overrides automatic quoting behavior
for this identifier in order to either unconditionally quote
or to not quote the name. If left at its default of None
,
quoting behavior is applied to the identifier on a per-backend basis
based on an examination of the token itself.
A quoted_name
object with quote=True
is also
prevented from being modified in the case of a so-called
“name normalize” option. Certain database backends, such as
Oracle, Firebird, and DB2 “normalize” case-insensitive names
as uppercase. The SQLAlchemy dialects for these backends
convert from SQLAlchemy’s lower-case-means-insensitive convention
to the upper-case-means-insensitive conventions of those backends.
The quote=True
flag here will prevent this conversion from occurring
to support an identifier that’s quoted as all lower case against
such a backend.
The quoted_name
object is normally created automatically
when specifying the name for key schema constructs such as
Table
, Column
, and others.
The class can also be
passed explicitly as the name to any function that receives a name which
can be quoted. Such as to use the Engine.has_table()
method with
an unconditionally quoted name:
from sqlalchemy import create_engine
from sqlalchemy.sql import quoted_name
engine = create_engine("oracle+cx_oracle://some_dsn")
engine.has_table(quoted_name("some_table", True))
The above logic will run the “has table” logic against the Oracle backend,
passing the name exactly as "some_table"
without converting to
upper case.
New in version 0.9.0.
Changed in version 1.2: The quoted_name
construct is now
importable from sqlalchemy.sql
, in addition to the previous
location of sqlalchemy.sql.elements
.
Class signature
class sqlalchemy.sql.expression.quoted_name
(sqlalchemy.util.langhelpers.MemoizedSlots
, builtins.str
)
sqlalchemy.sql.expression.quoted_name.
quote¶whether the string should be unconditionally quoted
Functions listed here are more commonly available as methods from any
ColumnElement
construct, for example, the
label()
function is usually invoked via the
ColumnElement.label()
method.
Object Name | Description |
---|---|
all_(expr) |
Produce an ALL expression. |
any_(expr) |
Produce an ANY expression. |
asc(column) |
Produce an ascending |
between(expr, lower_bound, upper_bound[, symmetric]) |
Produce a |
collate(expression, collation) |
Return the clause |
desc(column) |
Produce a descending |
funcfilter(func, *criterion) |
Produce a |
label(name, element[, type_]) |
Return a |
nulls_first(column) |
Produce the |
nulls_last(column) |
Produce the |
over(element[, partition_by, order_by, range_, ...]) |
Produce an |
within_group(element, *order_by) |
Produce a |
Produce an ALL expression.
This may apply to an array type for some dialects (e.g. postgresql), or to a subquery for others (e.g. mysql). e.g.:
# postgresql '5 = ALL (somearray)'
expr = 5 == all_(mytable.c.somearray)
# mysql '5 = ALL (SELECT value FROM table)'
expr = 5 == all_(select(table.c.value))
The operator is more conveniently available from any
ColumnElement
object that makes use of the
ARRAY
datatype:
expr = mytable.c.somearray.all(5)
Produce an ANY expression.
This may apply to an array type for some dialects (e.g. postgresql), or to a subquery for others (e.g. mysql). e.g.:
# postgresql '5 = ANY (somearray)'
expr = 5 == any_(mytable.c.somearray)
# mysql '5 = ANY (SELECT value FROM table)'
expr = 5 == any_(select(table.c.value))
The operator is more conveniently available from any
ColumnElement
object that makes use of the
ARRAY
datatype:
expr = mytable.c.somearray.any(5)
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 asc()
function is a standalone version of the
ColumnElement.asc()
method available on all SQL expressions,
e.g.:
stmt = select(users_table).order_by(users_table.c.name.asc())
column¶ – A ColumnElement
(e.g.
scalar SQL expression)
with which to apply the asc()
operation.
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 between()
function is a standalone version of the
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 between()
, including the left side
column expression, are coerced from Python scalar values if a
the value is not a 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
expr¶ – a column expression, typically a
ColumnElement
instance or alternatively a Python scalar expression to be coerced
into a column expression, serving as the left side of the BETWEEN
expression.
lower_bound¶ – a column or Python scalar expression serving as the
lower bound of the right side of the BETWEEN
expression.
upper_bound¶ – a column or Python scalar expression serving as the
upper bound of the right side of the BETWEEN
expression.
symmetric¶ –
if True, will render ” BETWEEN SYMMETRIC “. Note that not all databases support this syntax.
New in version 0.9.5.
See also
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.
Changed in version 1.2: quoting is automatically applied to COLLATE expressions if they are case sensitive.
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 desc()
function is a standalone version of the
ColumnElement.desc()
method available on all SQL expressions,
e.g.:
stmt = select(users_table).order_by(users_table.c.name.desc())
column¶ – A ColumnElement
(e.g.
scalar SQL expression)
with which to apply the desc()
operation.
Produce a 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 func
construct itself via the FunctionElement.filter()
method.
New in version 1.0.0.
Return a Label
object for the
given 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
ColumnElement.label()
method on
ColumnElement
.
name¶ – label name
obj¶ – a ColumnElement
.
Produce the NULLS FIRST
modifier for an ORDER BY
expression.
nulls_first()
is intended to modify the expression produced
by asc()
or 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 asc()
and desc()
, nulls_first()
is typically
invoked from the column expression itself using
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())
Changed in version 1.4: nulls_first()
is renamed from
nullsfirst()
in previous releases.
The previous name remains available for backwards compatibility.
Produce the NULLS LAST
modifier for an ORDER BY
expression.
nulls_last()
is intended to modify the expression produced
by asc()
or 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 asc()
and desc()
, nulls_last()
is typically
invoked from the column expression itself using
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())
Changed in version 1.4: nulls_last()
is renamed from
nullslast()
in previous releases.
The previous name remains available for backwards compatibility.
Produce an Over
object against a function.
Used against aggregate or so-called “window” functions, for database backends that support window functions.
over()
is usually called using
the 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 over.range_
and 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))
New in version 1.1: support for RANGE / ROWS within a window
element¶ – a FunctionElement
, WithinGroup
,
or other compatible construct.
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.
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.
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.
New in version 1.1.
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.
New in version 1.1.
This function is also available from the func
construct itself via the FunctionElement.over()
method.
Produce a WithinGroup
object against a function.
Used against so-called “ordered set aggregate” and “hypothetical
set aggregate” functions, including percentile_cont
,
rank
, dense_rank
, etc.
within_group()
is usually called using
the 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)
.
element¶ – a FunctionElement
construct, typically
generated by func
.
*order_by¶ – one or more column elements that will be used as the ORDER BY clause of the WITHIN GROUP construct.
New in version 1.1.
The classes here are generated using the constructors listed at Column Element Foundational Constructors and Column Element Modifier Constructors.
Object Name | Description |
---|---|
Represent an expression that is |
|
Represent a “bound expression”. |
|
Represent a |
|
Represent a |
|
Base class for elements of a programmatically constructed SQL expression. |
|
Describe a list of clauses, separated by an operator. |
|
Represents a column expression from any textual string. |
|
Collection of |
|
Represent a column-oriented SQL expression suitable for usage in the “columns” clause, WHERE clause etc. of a statement. |
|
Defines boolean, comparison, and other operators for
|
|
Establish the ability for a class to have dialect-specific arguments with defaults and constructor validation. |
|
Represent a SQL EXTRACT clause, |
|
Represent the |
|
Represent a function FILTER clause. |
|
Represents a column label (AS). |
|
A SQL construct where the state is stored as an un-invoked lambda. |
|
Represent the NULL keyword in a SQL statement. |
|
Base of comparison and logical operators. |
|
Represent an OVER clause. |
|
Represent a composable SQL statement as a |
|
Represent a literal SQL text fragment. |
|
Represent the |
|
Represent a SQL tuple. |
|
Represent a Python-side type-coercion wrapper. |
|
Define a ‘unary’ expression. |
|
Represent a WITHIN GROUP (ORDER BY) clause. |
|
Mixin that defines a |
Represent an expression that is LEFT <operator> RIGHT
.
A BinaryExpression
is generated automatically
whenever two column expressions are used in a Python binary expression:
>>> from sqlalchemy.sql import column
>>> column('a') + column('b')
<sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0>
>>> print(column('a') + column('b'))
a + b
Class signature
class sqlalchemy.sql.expression.BinaryExpression
(sqlalchemy.sql.expression.ColumnElement
)
sqlalchemy.sql.expression.BinaryExpression.
self_group(against=None)¶Apply a ‘grouping’ to this ClauseElement
.
This method is overridden by subclasses to return a “grouping”
construct, i.e. parenthesis. In particular it’s used by “binary”
expressions to provide a grouping around themselves when placed into a
larger expression, as well as by select()
constructs when placed into the FROM clause of another
select()
. (Note that subqueries should be
normally created using the Select.alias()
method,
as many
platforms require nested SELECT statements to be named).
As expressions are composed together, the application of
self_group()
is automatic - end-user code should never
need to use this method directly. Note that SQLAlchemy’s
clause constructs take operator precedence into account -
so parenthesis might not be needed, for example, in
an expression like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
Represent a “bound expression”.
BindParameter
is invoked explicitly using the
bindparam()
function, as in:
from sqlalchemy import bindparam
stmt = select(users_table).\
where(users_table.c.name == bindparam('username'))
Detailed discussion of how BindParameter
is used is
at bindparam()
.
See also
Class signature
class sqlalchemy.sql.expression.BindParameter
(sqlalchemy.sql.roles.InElementRole
, sqlalchemy.sql.expression.ColumnElement
)
sqlalchemy.sql.expression.BindParameter.
__init__(key, value=symbol('NO_ARG'), type_=None, unique=False, required=symbol('NO_ARG'), quote=None, callable_=None, expanding=False, isoutparam=False, literal_execute=False, _compared_to_operator=None, _compared_to_type=None, _is_crud=False)¶Construct a new BindParameter
object.
This constructor is mirrored as a public API function; see sqlalchemy.sql.expression.bindparam()
for a full usage and argument description.
sqlalchemy.sql.expression.BindParameter.
effective_value¶Return the value of this bound parameter,
taking into account if the callable
parameter
was set.
The callable
value will be evaluated
and returned if present, else value
.
sqlalchemy.sql.expression.BindParameter.
render_literal_execute()¶Produce a copy of this bound parameter that will enable the
BindParameter.literal_execute
flag.
The BindParameter.literal_execute
flag will
have the effect of the parameter rendered in the compiled SQL
string using [POSTCOMPILE]
form, which is a special form that
is converted to be a rendering of the literal value of the parameter
at SQL execution time. The rationale is to support caching
of SQL statement strings that can embed per-statement literal values,
such as LIMIT and OFFSET parameters, in the final SQL string that
is passed to the DBAPI. Dialects in particular may want to use
this method within custom compilation schemes.
New in version 1.4.5.
See also
Class signature
class sqlalchemy.sql.expression.CacheKey
(sqlalchemy.sql.traversals.CacheKey
)
sqlalchemy.sql.expression.CacheKey.
to_offline_string(statement_cache, statement, parameters)¶Generate an “offline string” form of this CacheKey
The “offline string” is basically the string SQL for the
statement plus a repr of the bound parameter values in series.
Whereas the CacheKey
object is dependent on in-memory
identities in order to work as a cache key, the “offline” version
is suitable for a cache that will work for other processes as well.
The given statement_cache
is a dictionary-like object where the
string form of the statement itself will be cached. This dictionary
should be in a longer lived scope in order to reduce the time spent
stringifying statements.
Represent a CASE
expression.
Case
is produced using the case()
factory function,
as in:
from sqlalchemy import case
stmt = select(users_table). where(
case(
(users_table.c.name == 'wendy', 'W'),
(users_table.c.name == 'jack', 'J'),
else_='E'
)
)
Details on Case
usage is at case()
.
See also
Class signature
class sqlalchemy.sql.expression.Case
(sqlalchemy.sql.expression.ColumnElement
)
sqlalchemy.sql.expression.Case.
__init__(*whens, **kw)¶Construct a new Case
object.
This constructor is mirrored as a public API function; see sqlalchemy.sql.expression.case()
for a full usage and argument description.
Represent a CAST
expression.
Cast
is produced using the cast()
factory function,
as in:
from sqlalchemy import cast, Numeric
stmt = select(cast(product_table.c.unit_price, Numeric(10, 4)))
Details on Cast
usage is at cast()
.
See also
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.
Class signature
class sqlalchemy.sql.expression.Cast
(sqlalchemy.sql.expression.WrapsColumnExpression
, sqlalchemy.sql.expression.ColumnElement
)
sqlalchemy.sql.expression.Cast.
__init__(expression, type_)¶Construct a new Cast
object.
This constructor is mirrored as a public API function; see sqlalchemy.sql.expression.cast()
for a full usage and argument description.
Base class for elements of a programmatically constructed SQL expression.
Class signature
class sqlalchemy.sql.expression.ClauseElement
(sqlalchemy.sql.roles.SQLRole
, sqlalchemy.sql.annotation.SupportsWrappingAnnotations
, sqlalchemy.sql.traversals.MemoizedHasCacheKey
, sqlalchemy.sql.traversals.HasCopyInternals
, sqlalchemy.sql.visitors.Traversible
)
sqlalchemy.sql.expression.ClauseElement.
compare(other, **kw)¶Compare this ClauseElement
to
the given ClauseElement
.
Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass compare()
methods and
may be used to modify the criteria for comparison
(see ColumnElement
).
sqlalchemy.sql.expression.ClauseElement.
compile(bind=None, dialect=None, **kw)¶Compile this SQL expression.
The return value is a Compiled
object.
Calling str()
or unicode()
on the returned value will yield a
string representation of the result. The
Compiled
object also can return a
dictionary of bind parameter names and values
using the params
accessor.
bind¶ – An Engine
or Connection
from which a
Compiled
will be acquired. This argument takes precedence over
this ClauseElement
’s bound engine, if any.
column_keys¶ – Used for INSERT and UPDATE statements, a list of
column names which should be present in the VALUES clause of the
compiled statement. If None
, all columns from the target table
object are rendered.
dialect¶ – A Dialect
instance from which a Compiled
will be acquired. This argument takes precedence over the bind
argument as well as this ClauseElement
‘s bound engine,
if any.
compile_kwargs¶ –
optional dictionary of additional parameters
that will be passed through to the compiler within all “visit”
methods. This allows any custom flag to be passed through to
a custom compilation construct, for example. It is also used
for the case of passing the literal_binds
flag through:
from sqlalchemy.sql import table, column, select
t = table('t', column('x'))
s = select(t).where(t.c.x == 5)
print(s.compile(compile_kwargs={"literal_binds": True}))
New in version 0.9.0.
sqlalchemy.sql.expression.ClauseElement.
get_children(omit_attrs=(), **kw)¶inherited from the Traversible.get_children()
method of Traversible
Return immediate child Traversible
elements of this Traversible
.
This is used for visit traversal.
**kw may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level).
A read-only @property that is only evaluated once.
sqlalchemy.sql.expression.ClauseElement.
classmethod memoized_instancemethod(fn)¶inherited from the HasMemoized.memoized_instancemethod()
method of HasMemoized
Decorate a method memoize its return value.
sqlalchemy.sql.expression.ClauseElement.
params(*optionaldict, **kwargs)¶Return a copy with bindparam()
elements
replaced.
Returns a copy of this ClauseElement with
bindparam()
elements replaced with values taken from the given dictionary:
>>> clause = column('x') + bindparam('foo')
>>> print(clause.compile().params)
{'foo':None}
>>> print(clause.params({'foo':7}).compile().params)
{'foo':7}
sqlalchemy.sql.expression.ClauseElement.
self_group(against=None)¶Apply a ‘grouping’ to this ClauseElement
.
This method is overridden by subclasses to return a “grouping”
construct, i.e. parenthesis. In particular it’s used by “binary”
expressions to provide a grouping around themselves when placed into a
larger expression, as well as by select()
constructs when placed into the FROM clause of another
select()
. (Note that subqueries should be
normally created using the Select.alias()
method,
as many
platforms require nested SELECT statements to be named).
As expressions are composed together, the application of
self_group()
is automatic - end-user code should never
need to use this method directly. Note that SQLAlchemy’s
clause constructs take operator precedence into account -
so parenthesis might not be needed, for example, in
an expression like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
sqlalchemy.sql.expression.ClauseElement.
unique_params(*optionaldict, **kwargs)¶Return a copy with bindparam()
elements
replaced.
Same functionality as ClauseElement.params()
,
except adds unique=True
to affected bind parameters so that multiple statements can be
used.
Describe a list of clauses, separated by an operator.
By default, is comma-separated, such as a column listing.
Class signature
class sqlalchemy.sql.expression.ClauseList
(sqlalchemy.sql.roles.InElementRole
, sqlalchemy.sql.roles.OrderByRole
, sqlalchemy.sql.roles.ColumnsClauseRole
, sqlalchemy.sql.roles.DMLColumnRole
, sqlalchemy.sql.expression.ClauseElement
)
sqlalchemy.sql.expression.ClauseList.
self_group(against=None)¶Apply a ‘grouping’ to this ClauseElement
.
This method is overridden by subclasses to return a “grouping”
construct, i.e. parenthesis. In particular it’s used by “binary”
expressions to provide a grouping around themselves when placed into a
larger expression, as well as by select()
constructs when placed into the FROM clause of another
select()
. (Note that subqueries should be
normally created using the Select.alias()
method,
as many
platforms require nested SELECT statements to be named).
As expressions are composed together, the application of
self_group()
is automatic - end-user code should never
need to use this method directly. Note that SQLAlchemy’s
clause constructs take operator precedence into account -
so parenthesis might not be needed, for example, in
an expression like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
Represents a column expression from any textual string.
The ColumnClause
, a lightweight analogue to the
Column
class, is typically invoked using the
column()
function, 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
ColumnClause
is the immediate superclass of the schema-specific
Column
object. While the Column
class has all the
same capabilities as ColumnClause
, the ColumnClause
class is usable by itself in those cases where behavioral requirements
are limited to simple SQL expression generation. The object has none of
the associations with schema-level metadata or with execution-time
behavior that Column
does,
so in that sense is a “lightweight”
version of Column
.
Full details on ColumnClause
usage is at
column()
.
Class signature
class sqlalchemy.sql.expression.ColumnClause
(sqlalchemy.sql.roles.DDLReferredColumnRole
, sqlalchemy.sql.roles.LabeledColumnExprRole
, sqlalchemy.sql.roles.StrAsPlainColumnRole
, sqlalchemy.sql.expression.Immutable
, sqlalchemy.sql.expression.NamedColumn
)
sqlalchemy.sql.expression.ColumnClause.
__init__(text, type_=None, is_literal=False, _selectable=None)¶Construct a new ColumnClause
object.
This constructor is mirrored as a public API function; see sqlalchemy.sql.expression.column()
for a full usage and argument description.
sqlalchemy.sql.expression.ColumnClause.
get_children(column_tables=False, **kw)¶Return immediate child Traversible
elements of this Traversible
.
This is used for visit traversal.
**kw may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level).
Collection of ColumnElement
instances,
typically for
FromClause
objects.
The ColumnCollection
object is most commonly available
as the Table.c
or Table.columns
collection
on the Table
object, introduced at
Accessing Tables and Columns.
The ColumnCollection
has both mapping- and sequence-
like behaviors. A ColumnCollection
usually stores
Column
objects, which are then accessible both via mapping
style access as well as attribute access style.
To access Column
objects using ordinary attribute-style
access, specify the name like any other object attribute, such as below
a column named employee_name
is accessed:
>>> employee_table.c.employee_name
To access columns that have names with special characters or spaces,
index-style access is used, such as below which illustrates a column named
employee ' payment
is accessed:
>>> employee_table.c["employee ' payment"]
As the ColumnCollection
object provides a Python dictionary
interface, common dictionary method names like
ColumnCollection.keys()
, ColumnCollection.values()
,
and ColumnCollection.items()
are available, which means that
database columns that are keyed under these names also need to use indexed
access:
>>> employee_table.c["values"]
The name for which a Column
would be present is normally
that of the Column.key
parameter. In some contexts,
such as a Select
object that uses a label style set
using the Select.set_label_style()
method, a column of a certain
key may instead be represented under a particular label name such
as tablename_columnname
:
>>> from sqlalchemy import select, column, table
>>> from sqlalchemy import LABEL_STYLE_TABLENAME_PLUS_COL
>>> t = table("t", column("c"))
>>> stmt = select(t).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
>>> subq = stmt.subquery()
>>> subq.c.t_c
<sqlalchemy.sql.elements.ColumnClause at 0x7f59dcf04fa0; t_c>
ColumnCollection
also indexes the columns in order and allows
them to be accessible by their integer position:
>>> cc[0]
Column('x', Integer(), table=None)
>>> cc[1]
Column('y', Integer(), table=None)
New in version 1.4: ColumnCollection
allows integer-based
index access to the collection.
Iterating the collection yields the column expressions in order:
>>> list(cc)
[Column('x', Integer(), table=None),
Column('y', Integer(), table=None)]
The base ColumnCollection
object can store
duplicates, which can
mean either two columns with the same key, in which case the column
returned by key access is arbitrary:
>>> x1, x2 = Column('x', Integer), Column('x', Integer)
>>> cc = ColumnCollection(columns=[(x1.name, x1), (x2.name, x2)])
>>> list(cc)
[Column('x', Integer(), table=None),
Column('x', Integer(), table=None)]
>>> cc['x'] is x1
False
>>> cc['x'] is x2
True
Or it can also mean the same column multiple times. These cases are
supported as ColumnCollection
is used to represent the columns in
a SELECT statement which may include duplicates.
A special subclass DedupeColumnCollection
exists which instead
maintains SQLAlchemy’s older behavior of not allowing duplicates; this
collection is used for schema level objects like Table
and
PrimaryKeyConstraint
where this deduping is helpful. The
DedupeColumnCollection
class also has additional mutation methods
as the schema constructs have more use cases that require removal and
replacement of columns.
Changed in version 1.4: ColumnCollection
now stores duplicate
column keys as well as the same column in multiple positions. The
DedupeColumnCollection
class is added to maintain the
former behavior in those cases where deduplication as well as
additional replace/remove operations are needed.
sqlalchemy.sql.expression.ColumnCollection.
add(column, key=None)¶Add a column to this ColumnCollection
.
Note
This method is not normally used by user-facing code, as the
ColumnCollection
is usually part of an existing
object such as a Table
. To add a
Column
to an existing Table
object, use the Table.append_column()
method.
sqlalchemy.sql.expression.ColumnCollection.
as_immutable()¶Return an “immutable” form of this
ColumnCollection
.
sqlalchemy.sql.expression.ColumnCollection.
clear()¶Dictionary clear() is not implemented for
ColumnCollection
.
sqlalchemy.sql.expression.ColumnCollection.
compare(other)¶Compare this ColumnCollection
to another
based on the names of the keys
sqlalchemy.sql.expression.ColumnCollection.
contains_column(col)¶Checks if a column object exists in this collection
sqlalchemy.sql.expression.ColumnCollection.
corresponding_column(column, require_embedded=False)¶Given a ColumnElement
, return the exported
ColumnElement
object from this
ColumnCollection
which corresponds to that original ColumnElement
via a common
ancestor column.
column¶ – the target ColumnElement
to be matched.
require_embedded¶ – only return corresponding columns for
the given ColumnElement
, if the given
ColumnElement
is actually present within a sub-element
of this Selectable
.
Normally the column will match if
it merely shares a common ancestor with one of the exported
columns of this Selectable
.
See also
Selectable.corresponding_column()
- invokes this method
against the collection returned by
Selectable.exported_columns
.
Changed in version 1.4: the implementation for corresponding_column
was moved onto the ColumnCollection
itself.
sqlalchemy.sql.expression.ColumnCollection.
get(key, default=None)¶Get a ColumnClause
or Column
object
based on a string key name from this
ColumnCollection
.
sqlalchemy.sql.expression.ColumnCollection.
items()¶Return a sequence of (key, column) tuples for all columns in this
collection each consisting of a string key name and a
ColumnClause
or
Column
object.
sqlalchemy.sql.expression.ColumnCollection.
keys()¶Return a sequence of string key names for all columns in this collection.
sqlalchemy.sql.expression.ColumnCollection.
remove(column)¶Dictionary remove() is not implemented for
ColumnCollection
.
sqlalchemy.sql.expression.ColumnCollection.
update(iter_)¶Dictionary update() is not implemented for
ColumnCollection
.
sqlalchemy.sql.expression.ColumnCollection.
values()¶Return a sequence of ColumnClause
or
Column
objects for all columns in this
collection.
Represent a column-oriented SQL expression suitable for usage in the “columns” clause, WHERE clause etc. of a statement.
While the most familiar kind of ColumnElement
is the
Column
object, ColumnElement
serves as the basis
for any unit that may be present in a SQL expression, including
the expressions themselves, SQL functions, bound parameters,
literal expressions, keywords such as NULL
, etc.
ColumnElement
is the ultimate base class for all such elements.
A wide variety of SQLAlchemy Core functions work at the SQL expression
level, and are intended to accept instances of
ColumnElement
as
arguments. These functions will typically document that they accept a
“SQL expression” as an argument. What this means in terms of SQLAlchemy
usually refers to an input which is either already in the form of a
ColumnElement
object,
or a value which can be coerced into
one. The coercion rules followed by most, but not all, SQLAlchemy Core
functions with regards to SQL expressions are as follows:
a literal Python value, such as a string, integer or floating point value, boolean, datetime,
Decimal
object, or virtually any other Python object, will be coerced into a “literal bound value”. This generally means that abindparam()
will be produced featuring the given value embedded into the construct; the resultingBindParameter
object is an instance ofColumnElement
. The Python value will ultimately be sent to the DBAPI at execution time as a parameterized argument to theexecute()
orexecutemany()
methods, after SQLAlchemy type-specific converters (e.g. those provided by any associatedTypeEngine
objects) are applied to the value.any special object value, typically ORM-level constructs, which feature an accessor called
__clause_element__()
. The Core expression system looks for this method when an object of otherwise unknown type is passed to a function that is looking to coerce the argument into aColumnElement
and sometimes aSelectBase
expression. It is used within the ORM to convert from ORM-specific objects like mapped classes and mapped attributes into Core expression objects.The Python
None
value is typically interpreted asNULL
, which in SQLAlchemy Core produces an instance ofnull()
.
A ColumnElement
provides the ability to generate new
ColumnElement
objects using Python expressions. This means that Python operators
such as ==
, !=
and <
are overloaded to mimic SQL operations,
and allow the instantiation of further ColumnElement
instances
which are composed from other, more fundamental
ColumnElement
objects. For example, two ColumnClause
objects can be added
together with the addition operator +
to produce
a BinaryExpression
.
Both ColumnClause
and BinaryExpression
are subclasses
of ColumnElement
:
>>> from sqlalchemy.sql import column
>>> column('a') + column('b')
<sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0>
>>> print(column('a') + column('b'))
a + b
Class signature
class sqlalchemy.sql.expression.ColumnElement
(sqlalchemy.sql.roles.ColumnArgumentOrKeyRole
, sqlalchemy.sql.roles.StatementOptionRole
, sqlalchemy.sql.roles.WhereHavingRole
, sqlalchemy.sql.roles.BinaryElementRole
, sqlalchemy.sql.roles.OrderByRole
, sqlalchemy.sql.roles.ColumnsClauseRole
, sqlalchemy.sql.roles.LimitOffsetRole
, sqlalchemy.sql.roles.DMLColumnRole
, sqlalchemy.sql.roles.DDLConstraintColumnRole
, sqlalchemy.sql.roles.DDLExpressionRole
, sqlalchemy.sql.expression.ColumnOperators
, sqlalchemy.sql.expression.ClauseElement
)
sqlalchemy.sql.expression.ColumnElement.
__eq__(other)¶inherited from the sqlalchemy.sql.expression.ColumnOperators.__eq__
method of ColumnOperators
Implement the ==
operator.
In a column context, produces the clause a = b
.
If the target is None
, produces a IS NULL
.
sqlalchemy.sql.expression.ColumnElement.
__le__(other)¶inherited from the sqlalchemy.sql.expression.ColumnOperators.__le__
method of ColumnOperators
Implement the <=
operator.
In a column context, produces the clause a <= b
.
sqlalchemy.sql.expression.ColumnElement.
__lt__(other)¶inherited from the sqlalchemy.sql.expression.ColumnOperators.__lt__
method of ColumnOperators
Implement the <
operator.
In a column context, produces the clause a < b
.
sqlalchemy.sql.expression.ColumnElement.
__ne__(other)¶inherited from the sqlalchemy.sql.expression.ColumnOperators.__ne__
method of ColumnOperators
Implement the !=
operator.
In a column context, produces the clause a != b
.
If the target is None
, produces a IS NOT NULL
.
sqlalchemy.sql.expression.ColumnElement.
all_()¶inherited from the ColumnOperators.all_()
method of ColumnOperators
Produce a all_()
clause against the
parent object.
This operator is only appropriate against a scalar subquery object, or for some backends an column expression that is against the ARRAY type, e.g.:
# postgresql '5 = ALL (somearray)'
expr = 5 == mytable.c.somearray.all_()
# mysql '5 = ALL (SELECT value FROM table)'
expr = 5 == select(table.c.value).scalar_subquery().all_()
New in version 1.1.
sqlalchemy.sql.expression.ColumnElement.
allows_lambda = True¶sqlalchemy.sql.expression.ColumnElement.
anon_key_label¶Deprecated since version 1.4: The ColumnElement.anon_key_label
attribute is now private, and the public accessor is deprecated.
sqlalchemy.sql.expression.ColumnElement.
anon_label¶Deprecated since version 1.4: The ColumnElement.anon_label
attribute is now private, and the public accessor is deprecated.
sqlalchemy.sql.expression.ColumnElement.
any_()¶inherited from the ColumnOperators.any_()
method of ColumnOperators
Produce a any_()
clause against the
parent object.
This operator is only appropriate against a scalar subquery object, or for some backends an column expression that is against the ARRAY type, e.g.:
# postgresql '5 = ANY (somearray)'
expr = 5 == mytable.c.somearray.any_()
# mysql '5 = ANY (SELECT value FROM table)'
expr = 5 == select(table.c.value).scalar_subquery().any_()
New in version 1.1.
sqlalchemy.sql.expression.ColumnElement.
asc()¶inherited from the ColumnOperators.asc()
method of ColumnOperators
Produce a asc()
clause against the
parent object.
sqlalchemy.sql.expression.ColumnElement.
base_columns¶sqlalchemy.sql.expression.ColumnElement.
between(cleft, cright, symmetric=False)¶inherited from the ColumnOperators.between()
method of ColumnOperators
Produce a between()
clause against
the parent object, given the lower and upper range.
sqlalchemy.sql.expression.ColumnElement.
bind = None¶sqlalchemy.sql.expression.ColumnElement.
bool_op(opstring, precedence=0)¶inherited from the Operators.bool_op()
method of Operators
Return a custom boolean operator.
This method is shorthand for calling
Operators.op()
and passing the
Operators.op.is_comparison
flag with True.
See also
sqlalchemy.sql.expression.ColumnElement.
cast(type_)¶Produce a type cast, i.e. CAST(<expression> AS <type>)
.
This is a shortcut to the cast()
function.
New in version 1.0.7.
sqlalchemy.sql.expression.ColumnElement.
collate(collation)¶inherited from the ColumnOperators.collate()
method of ColumnOperators
Produce a collate()
clause against
the parent object, given the collation string.
See also
sqlalchemy.sql.expression.ColumnElement.
comparator¶sqlalchemy.sql.expression.ColumnElement.
compare(other, **kw)¶inherited from the ClauseElement.compare()
method of ClauseElement
Compare this ClauseElement
to
the given ClauseElement
.
Subclasses should override the default behavior, which is a straight identity comparison.
**kw are arguments consumed by subclass compare()
methods and
may be used to modify the criteria for comparison
(see ColumnElement
).
sqlalchemy.sql.expression.ColumnElement.
compile(bind=None, dialect=None, **kw)¶inherited from the ClauseElement.compile()
method of ClauseElement
Compile this SQL expression.
The return value is a Compiled
object.
Calling str()
or unicode()
on the returned value will yield a
string representation of the result. The
Compiled
object also can return a
dictionary of bind parameter names and values
using the params
accessor.
bind¶ – An Engine
or Connection
from which a
Compiled
will be acquired. This argument takes precedence over
this ClauseElement
’s bound engine, if any.
column_keys¶ – Used for INSERT and UPDATE statements, a list of
column names which should be present in the VALUES clause of the
compiled statement. If None
, all columns from the target table
object are rendered.
dialect¶ – A Dialect
instance from which a Compiled
will be acquired. This argument takes precedence over the bind
argument as well as this ClauseElement
‘s bound engine,
if any.
compile_kwargs¶ –
optional dictionary of additional parameters
that will be passed through to the compiler within all “visit”
methods. This allows any custom flag to be passed through to
a custom compilation construct, for example. It is also used
for the case of passing the literal_binds
flag through:
from sqlalchemy.sql import table, column, select
t = table('t', column('x'))
s = select(t).where(t.c.x == 5)
print(s.compile(compile_kwargs={"literal_binds": True}))
New in version 0.9.0.
sqlalchemy.sql.expression.ColumnElement.
concat(other)¶inherited from the ColumnOperators.concat()
method of ColumnOperators
Implement the ‘concat’ operator.
In a column context, produces the clause a || b
,
or uses the concat()
operator on MySQL.
sqlalchemy.sql.expression.ColumnElement.
contains(other, **kwargs)¶inherited from the ColumnOperators.contains()
method of ColumnOperators
Implement the ‘contains’ operator.
Produces a LIKE expression that tests against a match for the middle of a string value:
column LIKE '%' || <other> || '%'
E.g.:
stmt = select(sometable).\
where(sometable.c.column.contains("foobar"))
Since the operator uses LIKE
, wildcard characters
"%"
and "_"
that are present inside the <other> expression
will behave like wildcards as well. For literal string
values, the ColumnOperators.contains.autoescape
flag
may be set to True
to apply escaping to occurrences of these
characters within the string value so that they match as themselves
and not as wildcard characters. Alternatively, the
ColumnOperators.contains.escape
parameter will establish
a given character as an escape character which can be of use when
the target expression is not a literal string.
other¶ – expression to be compared. This is usually a plain
string value, but can also be an arbitrary SQL expression. LIKE
wildcard characters %
and _
are not escaped by default unless
the ColumnOperators.contains.autoescape
flag is
set to True.
autoescape¶ –
boolean; when True, establishes an escape character
within the LIKE expression, then applies it to all occurrences of
"%"
, "_"
and the escape character itself within the
comparison value, which is assumed to be a literal string and not a
SQL expression.
An expression such as:
somecolumn.contains("foo%bar", autoescape=True)
Will render as:
somecolumn LIKE '%' || :param || '%' ESCAPE '/'
With the value of :param
as "foo/%bar"
.
escape¶ –
a character which when given will render with the
ESCAPE
keyword to establish that character as the escape
character. This character can then be placed preceding occurrences
of %
and _
to allow them to act as themselves and not
wildcard characters.
An expression such as:
somecolumn.contains("foo/%bar", escape="^")
Will render as:
somecolumn LIKE '%' || :param || '%' ESCAPE '^'
The parameter may also be combined with
ColumnOperators.contains.autoescape
:
somecolumn.contains("foo%bar^bat", escape="^", autoescape=True)
Where above, the given literal parameter will be converted to
"foo^%bar^^bat"
before being passed to the database.
sqlalchemy.sql.expression.ColumnElement.
desc()¶inherited from the ColumnOperators.desc()
method of ColumnOperators
Produce a desc()
clause against the
parent object.
sqlalchemy.sql.expression.ColumnElement.
description = None¶sqlalchemy.sql.expression.ColumnElement.
distinct()¶inherited from the ColumnOperators.distinct()
method of ColumnOperators
Produce a distinct()
clause against the
parent object.
sqlalchemy.sql.expression.ColumnElement.
endswith(other, **kwargs)¶inherited from the ColumnOperators.endswith()
method of ColumnOperators
Implement the ‘endswith’ operator.
Produces a LIKE expression that tests against a match for the end of a string value:
column LIKE '%' || <other>
E.g.:
stmt = select(sometable).\
where(sometable.c.column.endswith("foobar"))
Since the operator uses LIKE
, wildcard characters
"%"
and "_"
that are present inside the <other> expression
will behave like wildcards as well. For literal string
values, the ColumnOperators.endswith.autoescape
flag
may be set to True
to apply escaping to occurrences of these
characters within the string value so that they match as themselves
and not as wildcard characters. Alternatively, the
ColumnOperators.endswith.escape
parameter will establish
a given character as an escape character which can be of use when
the target expression is not a literal string.
other¶ – expression to be compared. This is usually a plain
string value, but can also be an arbitrary SQL expression. LIKE
wildcard characters %
and _
are not escaped by default unless
the ColumnOperators.endswith.autoescape
flag is
set to True.
autoescape¶ –
boolean; when True, establishes an escape character
within the LIKE expression, then applies it to all occurrences of
"%"
, "_"
and the escape character itself within the
comparison value, which is assumed to be a literal string and not a
SQL expression.
An expression such as:
somecolumn.endswith("foo%bar", autoescape=True)
Will render as:
somecolumn LIKE '%' || :param ESCAPE '/'
With the value of :param
as "foo/%bar"
.
escape¶ –
a character which when given will render with the
ESCAPE
keyword to establish that character as the escape
character. This character can then be placed preceding occurrences
of %
and _
to allow them to act as themselves and not
wildcard characters.
An expression such as:
somecolumn.endswith("foo/%bar", escape="^")
Will render as:
somecolumn LIKE '%' || :param ESCAPE '^'
The parameter may also be combined with
ColumnOperators.endswith.autoescape
:
somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)
Where above, the given literal parameter will be converted to
"foo^%bar^^bat"
before being passed to the database.
sqlalchemy.sql.expression.ColumnElement.
entity_namespace¶inherited from the ClauseElement.entity_namespace
attribute of ClauseElement
sqlalchemy.sql.expression.ColumnElement.
expression¶Return a column expression.
Part of the inspection interface; returns self.
sqlalchemy.sql.expression.ColumnElement.
foreign_keys = []¶sqlalchemy.sql.expression.ColumnElement.
get_children(omit_attrs=(), **kw)¶inherited from the Traversible.get_children()
method of Traversible
Return immediate child Traversible
elements of this Traversible
.
This is used for visit traversal.
**kw may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level).
sqlalchemy.sql.expression.ColumnElement.
ilike(other, escape=None)¶inherited from the ColumnOperators.ilike()
method of ColumnOperators
Implement the ilike
operator, e.g. case insensitive LIKE.
In a column context, produces an expression either of the form:
lower(a) LIKE lower(other)
Or on backends that support the ILIKE operator:
a ILIKE other
E.g.:
stmt = select(sometable).\
where(sometable.c.column.ilike("%foobar%"))
See also
sqlalchemy.sql.expression.ColumnElement.
in_(other)¶inherited from the ColumnOperators.in_()
method of ColumnOperators
Implement the in
operator.
In a column context, produces the clause column IN <other>
.
The given parameter other
may be:
A list of literal values, e.g.:
stmt.where(column.in_([1, 2, 3]))
In this calling form, the list of items is converted to a set of bound parameters the same length as the list given:
WHERE COL IN (?, ?, ?)
A list of tuples may be provided if the comparison is against a
tuple_()
containing multiple expressions:
from sqlalchemy import tuple_
stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)]))
An empty list, e.g.:
stmt.where(column.in_([]))
In this calling form, the expression renders an “empty set” expression. These expressions are tailored to individual backends and are generally trying to get an empty SELECT statement as a subquery. Such as on SQLite, the expression is:
WHERE col IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)
Changed in version 1.4: empty IN expressions now use an execution-time generated SELECT subquery in all cases.
A bound parameter, e.g. bindparam()
, may be used if it
includes the bindparam.expanding
flag:
stmt.where(column.in_(bindparam('value', expanding=True)))
In this calling form, the expression renders a special non-SQL placeholder expression that looks like:
WHERE COL IN ([EXPANDING_value])
This placeholder expression is intercepted at statement execution time to be converted into the variable number of bound parameter form illustrated earlier. If the statement were executed as:
connection.execute(stmt, {"value": [1, 2, 3]})
The database would be passed a bound parameter for each value:
WHERE COL IN (?, ?, ?)
New in version 1.2: added “expanding” bound parameters
If an empty list is passed, a special “empty list” expression, which is specific to the database in use, is rendered. On SQLite this would be:
WHERE COL IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)
New in version 1.3: “expanding” bound parameters now support empty lists
a select()
construct, which is usually a
correlated scalar select:
stmt.where(
column.in_(
select(othertable.c.y).
where(table.c.x == othertable.c.x)
)
)
In this calling form, ColumnOperators.in_()
renders as given:
WHERE COL IN (SELECT othertable.y
FROM othertable WHERE othertable.x = table.x)
other¶ – a list of literals, a select()
construct, or a bindparam()
construct that includes the
bindparam.expanding
flag set to True.
sqlalchemy.sql.expression.ColumnElement.
is_(other)¶inherited from the ColumnOperators.is_()
method of ColumnOperators
Implement the IS
operator.
Normally, IS
is generated automatically when comparing to a
value of None
, which resolves to NULL
. However, explicit
usage of IS
may be desirable if comparing to boolean values
on certain platforms.
See also
sqlalchemy.sql.expression.ColumnElement.
is_clause_element = True¶sqlalchemy.sql.expression.ColumnElement.
is_distinct_from(other)¶inherited from the ColumnOperators.is_distinct_from()
method of ColumnOperators
Implement the IS DISTINCT FROM
operator.
Renders “a IS DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS NOT b”.
New in version 1.1.
sqlalchemy.sql.expression.ColumnElement.
is_not(other)¶inherited from the ColumnOperators.is_not()
method of ColumnOperators
Implement the IS NOT
operator.
Normally, IS NOT
is generated automatically when comparing to a
value of None
, which resolves to NULL
. However, explicit
usage of IS NOT
may be desirable if comparing to boolean values
on certain platforms.
Changed in version 1.4: The is_not()
operator is renamed from
isnot()
in previous releases. The previous name remains
available for backwards compatibility.
See also
sqlalchemy.sql.expression.ColumnElement.
is_not_distinct_from(other)¶inherited from the ColumnOperators.is_not_distinct_from()
method of ColumnOperators
Implement the IS NOT DISTINCT FROM
operator.
Renders “a IS NOT DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS b”.
Changed in version 1.4: The is_not_distinct_from()
operator is
renamed from isnot_distinct_from()
in previous releases.
The previous name remains available for backwards compatibility.
New in version 1.1.
sqlalchemy.sql.expression.ColumnElement.
is_selectable = False¶sqlalchemy.sql.expression.ColumnElement.
isnot(other)¶inherited from the ColumnOperators.isnot()
method of ColumnOperators
Implement the IS NOT
operator.
Normally, IS NOT
is generated automatically when comparing to a
value of None
, which resolves to NULL
. However, explicit
usage of IS NOT
may be desirable if comparing to boolean values
on certain platforms.
Changed in version 1.4: The is_not()
operator is renamed from
isnot()
in previous releases. The previous name remains
available for backwards compatibility.
See also
sqlalchemy.sql.expression.ColumnElement.
isnot_distinct_from(other)¶inherited from the ColumnOperators.isnot_distinct_from()
method of ColumnOperators
Implement the IS NOT DISTINCT FROM
operator.
Renders “a IS NOT DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS b”.
Changed in version 1.4: The is_not_distinct_from()
operator is
renamed from isnot_distinct_from()
in previous releases.
The previous name remains available for backwards compatibility.
New in version 1.1.
sqlalchemy.sql.expression.ColumnElement.
key = None¶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 Column
with a .key
of “somekey”.
sqlalchemy.sql.expression.ColumnElement.
label(name)¶Produce a column label, i.e. <columnname> AS <name>
.
This is a shortcut to the label()
function.
If ‘name’ is None
, an anonymous label name will be generated.
sqlalchemy.sql.expression.ColumnElement.
like(other, escape=None)¶inherited from the ColumnOperators.like()
method of ColumnOperators
Implement the like
operator.
In a column context, produces the expression:
a LIKE other
E.g.:
stmt = select(sometable).\
where(sometable.c.column.like("%foobar%"))
See also
sqlalchemy.sql.expression.ColumnElement.
match(other, **kwargs)¶inherited from the ColumnOperators.match()
method of ColumnOperators
Implements a database-specific ‘match’ operator.
ColumnOperators.match()
attempts to resolve to
a MATCH-like function or operator provided by the backend.
Examples include:
PostgreSQL - renders x @@ to_tsquery(y)
MySQL - renders MATCH (x) AGAINST (y IN BOOLEAN MODE)
See also
match
- MySQL specific construct with
additional features.
Oracle - renders CONTAINS(x, y)
other backends may provide special implementations.
Backends without any special implementation will emit the operator as “MATCH”. This is compatible with SQLite, for example.
A read-only @property that is only evaluated once.
sqlalchemy.sql.expression.ColumnElement.
classmethod memoized_instancemethod(fn)¶inherited from the HasMemoized.memoized_instancemethod()
method of HasMemoized
Decorate a method memoize its return value.
sqlalchemy.sql.expression.ColumnElement.
not_ilike(other, escape=None)¶inherited from the ColumnOperators.not_ilike()
method of ColumnOperators
implement the NOT ILIKE
operator.
This is equivalent to using negation with
ColumnOperators.ilike()
, i.e. ~x.ilike(y)
.
Changed in version 1.4: The not_ilike()
operator is renamed from
notilike()
in previous releases. The previous name remains
available for backwards compatibility.
See also
sqlalchemy.sql.expression.ColumnElement.
not_in(other)¶inherited from the ColumnOperators.not_in()
method of ColumnOperators
implement the NOT IN
operator.
This is equivalent to using negation with
ColumnOperators.in_()
, i.e. ~x.in_(y)
.
In the case that other
is an empty sequence, the compiler
produces an “empty not in” expression. This defaults to the
expression “1 = 1” to produce true in all cases. The
create_engine.empty_in_strategy
may be used to
alter this behavior.
Changed in version 1.4: The not_in()
operator is renamed from
notin_()
in previous releases. The previous name remains
available for backwards compatibility.
Changed in version 1.2: The ColumnOperators.in_()
and
ColumnOperators.not_in()
operators
now produce a “static” expression for an empty IN sequence
by default.
See also
sqlalchemy.sql.expression.ColumnElement.
not_like(other, escape=None)¶inherited from the ColumnOperators.not_like()
method of ColumnOperators
implement the NOT LIKE
operator.
This is equivalent to using negation with
ColumnOperators.like()
, i.e. ~x.like(y)
.
Changed in version 1.4: The not_like()
operator is renamed from
notlike()
in previous releases. The previous name remains
available for backwards compatibility.
See also
sqlalchemy.sql.expression.ColumnElement.
notilike(other, escape=None)¶inherited from the ColumnOperators.notilike()
method of ColumnOperators
implement the NOT ILIKE
operator.
This is equivalent to using negation with
ColumnOperators.ilike()
, i.e. ~x.ilike(y)
.
Changed in version 1.4: The not_ilike()
operator is renamed from
notilike()
in previous releases. The previous name remains
available for backwards compatibility.
See also
sqlalchemy.sql.expression.ColumnElement.
notin_(other)¶inherited from the ColumnOperators.notin_()
method of ColumnOperators
implement the NOT IN
operator.
This is equivalent to using negation with
ColumnOperators.in_()
, i.e. ~x.in_(y)
.
In the case that other
is an empty sequence, the compiler
produces an “empty not in” expression. This defaults to the
expression “1 = 1” to produce true in all cases. The
create_engine.empty_in_strategy
may be used to
alter this behavior.
Changed in version 1.4: The not_in()
operator is renamed from
notin_()
in previous releases. The previous name remains
available for backwards compatibility.
Changed in version 1.2: The ColumnOperators.in_()
and
ColumnOperators.not_in()
operators
now produce a “static” expression for an empty IN sequence
by default.
See also
sqlalchemy.sql.expression.ColumnElement.
notlike(other, escape=None)¶inherited from the ColumnOperators.notlike()
method of ColumnOperators
implement the NOT LIKE
operator.
This is equivalent to using negation with
ColumnOperators.like()
, i.e. ~x.like(y)
.
Changed in version 1.4: The not_like()
operator is renamed from
notlike()
in previous releases. The previous name remains
available for backwards compatibility.
See also
sqlalchemy.sql.expression.ColumnElement.
nulls_first()¶inherited from the ColumnOperators.nulls_first()
method of ColumnOperators
Produce a nulls_first()
clause against the
parent object.
Changed in version 1.4: The nulls_first()
operator is
renamed from nullsfirst()
in previous releases.
The previous name remains available for backwards compatibility.
sqlalchemy.sql.expression.ColumnElement.
nulls_last()¶inherited from the ColumnOperators.nulls_last()
method of ColumnOperators
Produce a nulls_last()
clause against the
parent object.
Changed in version 1.4: The nulls_last()
operator is
renamed from nullslast()
in previous releases.
The previous name remains available for backwards compatibility.
sqlalchemy.sql.expression.ColumnElement.
nullsfirst()¶inherited from the ColumnOperators.nullsfirst()
method of ColumnOperators
Produce a nulls_first()
clause against the
parent object.
Changed in version 1.4: The nulls_first()
operator is
renamed from nullsfirst()
in previous releases.
The previous name remains available for backwards compatibility.
sqlalchemy.sql.expression.ColumnElement.
nullslast()¶inherited from the ColumnOperators.nullslast()
method of ColumnOperators
Produce a nulls_last()
clause against the
parent object.
Changed in version 1.4: The nulls_last()
operator is
renamed from nullslast()
in previous releases.
The previous name remains available for backwards compatibility.
sqlalchemy.sql.expression.ColumnElement.
op(opstring, precedence=0, is_comparison=False, return_type=None)¶inherited from the Operators.op()
method of Operators
Produce a generic operator function.
e.g.:
somecolumn.op("*")(5)
produces:
somecolumn * 5
This function can also be used to make bitwise operators explicit. For example:
somecolumn.op('&')(0xff)
is a bitwise AND of the value in somecolumn
.
operator¶ – a string which will be output as the infix operator between this element and the expression passed to the generated function.
precedence¶ – precedence to apply to the operator, when
parenthesizing expressions. A lower number will cause the expression
to be parenthesized when applied against another operator with
higher precedence. The default value of 0
is lower than all
operators except for the comma (,
) and AS
operators.
A value of 100 will be higher or equal to all operators, and -100
will be lower than or equal to all operators.
is_comparison¶ –
if True, the operator will be considered as a
“comparison” operator, that is which evaluates to a boolean
true/false value, like ==
, >
, etc. This flag should be set
so that ORM relationships can establish that the operator is a
comparison operator when used in a custom join condition.
New in version 0.9.2: - added the
Operators.op.is_comparison
flag.
return_type¶ – a TypeEngine
class or object that will
force the return type of an expression produced by this operator
to be of that type. By default, operators that specify
Operators.op.is_comparison
will resolve to
Boolean
, and those that do not will be of the same
type as the left-hand operand.
sqlalchemy.sql.expression.ColumnElement.
operate(op, *other, **kwargs)¶Operate on an argument.
This is the lowest level of operation, raises
NotImplementedError
by default.
Overriding this on a subclass can allow common
behavior to be applied to all operations.
For example, overriding ColumnOperators
to apply func.lower()
to the left and right
side:
class MyComparator(ColumnOperators):
def operate(self, op, other):
return op(func.lower(self), func.lower(other))
op¶ – Operator callable.
*other¶ – the ‘other’ side of the operation. Will be a single scalar for most operations.
**kwargs¶ – modifiers. These may be passed by special
operators such as ColumnOperators.contains()
.
sqlalchemy.sql.expression.ColumnElement.
params(*optionaldict, **kwargs)¶inherited from the ClauseElement.params()
method of ClauseElement
Return a copy with bindparam()
elements
replaced.
Returns a copy of this ClauseElement with
bindparam()
elements replaced with values taken from the given dictionary:
>>> clause = column('x') + bindparam('foo')
>>> print(clause.compile().params)
{'foo':None}
>>> print(clause.params({'foo':7}).compile().params)
{'foo':7}
sqlalchemy.sql.expression.ColumnElement.
primary_key = False¶sqlalchemy.sql.expression.ColumnElement.
proxy_set¶sqlalchemy.sql.expression.ColumnElement.
regexp_match(pattern, flags=None)¶inherited from the ColumnOperators.regexp_match()
method of ColumnOperators
Implements a database-specific ‘regexp match’ operator.
E.g.:
stmt = select(table.c.some_column).where(
table.c.some_column.regexp_match('^(b|c)')
)
ColumnOperators.regexp_match()
attempts to resolve to
a REGEXP-like function or operator provided by the backend, however
the specific regular expression syntax and flags available are
not backend agnostic.
Examples include:
PostgreSQL - renders x ~ y
or x !~ y
when negated.
Oracle - renders REGEXP_LIKE(x, y)
SQLite - uses SQLite’s REGEXP
placeholder operator and calls into
the Python re.match()
builtin.
other backends may provide special implementations.
Backends without any special implementation will emit the operator as “REGEXP” or “NOT REGEXP”. This is compatible with SQLite and MySQL, for example.
Regular expression support is currently implemented for Oracle, PostgreSQL, MySQL and MariaDB. Partial support is available for SQLite. Support among third-party dialects may vary.
pattern¶ – The regular expression pattern string or column clause.
flags¶ – Any regular expression string flags to apply. Flags
tend to be backend specific. It can be a string or a column clause.
Some backends, like PostgreSQL and MariaDB, may alternatively
specify the flags as part of the pattern.
When using the ignore case flag ‘i’ in PostgreSQL, the ignore case
regexp match operator ~*
or !~*
will be used.
New in version 1.4.
See also
sqlalchemy.sql.expression.ColumnElement.
regexp_replace(pattern, replacement, flags=None)¶inherited from the ColumnOperators.regexp_replace()
method of ColumnOperators
Implements a database-specific ‘regexp replace’ operator.
E.g.:
stmt = select(
table.c.some_column.regexp_replace(
'b(..)',
'XY',
flags='g'
)
)
ColumnOperators.regexp_replace()
attempts to resolve to
a REGEXP_REPLACE-like function provided by the backend, that
usually emit the function REGEXP_REPLACE()
. However,
the specific regular expression syntax and flags available are
not backend agnostic.
Regular expression replacement support is currently implemented for Oracle, PostgreSQL, MySQL 8 or greater and MariaDB. Support among third-party dialects may vary.
pattern¶ – The regular expression pattern string or column clause.
pattern¶ – The replacement string or column clause.
flags¶ – Any regular expression string flags to apply. Flags tend to be backend specific. It can be a string or a column clause. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern.
New in version 1.4.
See also
sqlalchemy.sql.expression.ColumnElement.
reverse_operate(op, other, **kwargs)¶Reverse operate on an argument.
Usage is the same as operate()
.
sqlalchemy.sql.expression.ColumnElement.
self_group(against=None)¶Apply a ‘grouping’ to this ClauseElement
.
This method is overridden by subclasses to return a “grouping”
construct, i.e. parenthesis. In particular it’s used by “binary”
expressions to provide a grouping around themselves when placed into a
larger expression, as well as by select()
constructs when placed into the FROM clause of another
select()
. (Note that subqueries should be
normally created using the Select.alias()
method,
as many
platforms require nested SELECT statements to be named).
As expressions are composed together, the application of
self_group()
is automatic - end-user code should never
need to use this method directly. Note that SQLAlchemy’s
clause constructs take operator precedence into account -
so parenthesis might not be needed, for example, in
an expression like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
sqlalchemy.sql.expression.ColumnElement.
shares_lineage(othercolumn)¶Return True if the given ColumnElement
has a common ancestor to this ColumnElement
.
sqlalchemy.sql.expression.ColumnElement.
startswith(other, **kwargs)¶inherited from the ColumnOperators.startswith()
method of ColumnOperators
Implement the startswith
operator.
Produces a LIKE expression that tests against a match for the start of a string value:
column LIKE <other> || '%'
E.g.:
stmt = select(sometable).\
where(sometable.c.column.startswith("foobar"))
Since the operator uses LIKE
, wildcard characters
"%"
and "_"
that are present inside the <other> expression
will behave like wildcards as well. For literal string
values, the ColumnOperators.startswith.autoescape
flag
may be set to True
to apply escaping to occurrences of these
characters within the string value so that they match as themselves
and not as wildcard characters. Alternatively, the
ColumnOperators.startswith.escape
parameter will establish
a given character as an escape character which can be of use when
the target expression is not a literal string.
other¶ – expression to be compared. This is usually a plain
string value, but can also be an arbitrary SQL expression. LIKE
wildcard characters %
and _
are not escaped by default unless
the ColumnOperators.startswith.autoescape
flag is
set to True.
autoescape¶ –
boolean; when True, establishes an escape character
within the LIKE expression, then applies it to all occurrences of
"%"
, "_"
and the escape character itself within the
comparison value, which is assumed to be a literal string and not a
SQL expression.
An expression such as:
somecolumn.startswith("foo%bar", autoescape=True)
Will render as:
somecolumn LIKE :param || '%' ESCAPE '/'
With the value of :param
as "foo/%bar"
.
escape¶ –
a character which when given will render with the
ESCAPE
keyword to establish that character as the escape
character. This character can then be placed preceding occurrences
of %
and _
to allow them to act as themselves and not
wildcard characters.
An expression such as:
somecolumn.startswith("foo/%bar", escape="^")
Will render as:
somecolumn LIKE :param || '%' ESCAPE '^'
The parameter may also be combined with
ColumnOperators.startswith.autoescape
:
somecolumn.startswith("foo%bar^bat", escape="^", autoescape=True)
Where above, the given literal parameter will be converted to
"foo^%bar^^bat"
before being passed to the database.
sqlalchemy.sql.expression.ColumnElement.
stringify_dialect = 'default'¶sqlalchemy.sql.expression.ColumnElement.
supports_execution = False¶sqlalchemy.sql.expression.ColumnElement.
timetuple = None¶inherited from the ColumnOperators.timetuple
attribute of ColumnOperators
Hack, allows datetime objects to be compared on the LHS.
sqlalchemy.sql.expression.ColumnElement.
type¶sqlalchemy.sql.expression.ColumnElement.
unique_params(*optionaldict, **kwargs)¶inherited from the ClauseElement.unique_params()
method of ClauseElement
Return a copy with bindparam()
elements
replaced.
Same functionality as ClauseElement.params()
,
except adds unique=True
to affected bind parameters so that multiple statements can be
used.
sqlalchemy.sql.expression.ColumnElement.
uses_inspection = True¶Defines boolean, comparison, and other operators for
ColumnElement
expressions.
By default, all methods call down to
operate()
or reverse_operate()
,
passing in the appropriate operator function from the
Python builtin operator
module or
a SQLAlchemy-specific operator function from
sqlalchemy.expression.operators
. For example
the __eq__
function:
def __eq__(self, other):
return self.operate(operators.eq, other)
Where operators.eq
is essentially:
def eq(a, b):
return a == b
The core column expression unit ColumnElement
overrides Operators.operate()
and others
to return further ColumnElement
constructs,
so that the ==
operation above is replaced by a clause
construct.
Class signature
class sqlalchemy.sql.expression.ColumnOperators
(sqlalchemy.sql.expression.Operators
)
sqlalchemy.sql.expression.ColumnOperators.
__add__(other)¶Implement the +
operator.
In a column context, produces the clause a + b
if the parent object has non-string affinity.
If the parent object has a string affinity,
produces the concatenation operator, a || b
-
see ColumnOperators.concat()
.
sqlalchemy.sql.expression.ColumnOperators.
__and__(other)¶inherited from the sqlalchemy.sql.expression.Operators.__and__
method of Operators
Implement the &
operator.
When used with SQL expressions, results in an
AND operation, equivalent to
and_()
, that is:
a & b
is equivalent to:
from sqlalchemy import and_
and_(a, b)
Care should be taken when using &
regarding
operator precedence; the &
operator has the highest precedence.
The operands should be enclosed in parenthesis if they contain
further sub expressions:
(a == 2) & (b == 4)
sqlalchemy.sql.expression.ColumnOperators.
__div__(other)¶Implement the /
operator.
In a column context, produces the clause a / b
.
sqlalchemy.sql.expression.ColumnOperators.
__eq__(other)¶Implement the ==
operator.
In a column context, produces the clause a = b
.
If the target is None
, produces a IS NULL
.
sqlalchemy.sql.expression.ColumnOperators.
__ge__(other)¶Implement the >=
operator.
In a column context, produces the clause a >= b
.
sqlalchemy.sql.expression.ColumnOperators.
__getitem__(index)¶Implement the [] operator.
This can be used by some database-specific types such as PostgreSQL ARRAY and HSTORE.
sqlalchemy.sql.expression.ColumnOperators.
__gt__(other)¶Implement the >
operator.
In a column context, produces the clause a > b
.
sqlalchemy.sql.expression.ColumnOperators.
__hash__()¶Return hash(self).
sqlalchemy.sql.expression.ColumnOperators.
__invert__()¶inherited from the sqlalchemy.sql.expression.Operators.__invert__
method of Operators
Implement the ~
operator.
When used with SQL expressions, results in a
NOT operation, equivalent to
not_()
, that is:
~a
is equivalent to:
from sqlalchemy import not_
not_(a)
sqlalchemy.sql.expression.ColumnOperators.
__le__(other)¶Implement the <=
operator.
In a column context, produces the clause a <= b
.
sqlalchemy.sql.expression.ColumnOperators.
__lshift__(other)¶implement the << operator.
Not used by SQLAlchemy core, this is provided for custom operator systems which want to use << as an extension point.
sqlalchemy.sql.expression.ColumnOperators.
__lt__(other)¶Implement the <
operator.
In a column context, produces the clause a < b
.
sqlalchemy.sql.expression.ColumnOperators.
__mod__(other)¶Implement the %
operator.
In a column context, produces the clause a % b
.
sqlalchemy.sql.expression.ColumnOperators.
__mul__(other)¶Implement the *
operator.
In a column context, produces the clause a * b
.
sqlalchemy.sql.expression.ColumnOperators.
__ne__(other)¶Implement the !=
operator.
In a column context, produces the clause a != b
.
If the target is None
, produces a IS NOT NULL
.
sqlalchemy.sql.expression.ColumnOperators.
__neg__()¶Implement the -
operator.
In a column context, produces the clause -a
.
sqlalchemy.sql.expression.ColumnOperators.
__or__(other)¶inherited from the sqlalchemy.sql.expression.Operators.__or__
method of Operators
Implement the |
operator.
When used with SQL expressions, results in an
OR operation, equivalent to
or_()
, that is:
a | b
is equivalent to:
from sqlalchemy import or_
or_(a, b)
Care should be taken when using |
regarding
operator precedence; the |
operator has the highest precedence.
The operands should be enclosed in parenthesis if they contain
further sub expressions:
(a == 2) | (b == 4)
sqlalchemy.sql.expression.ColumnOperators.
__radd__(other)¶Implement the +
operator in reverse.
sqlalchemy.sql.expression.ColumnOperators.
__rdiv__(other)¶Implement the /
operator in reverse.
sqlalchemy.sql.expression.ColumnOperators.
__rmod__(other)¶Implement the %
operator in reverse.
sqlalchemy.sql.expression.ColumnOperators.
__rmul__(other)¶Implement the *
operator in reverse.
sqlalchemy.sql.expression.ColumnOperators.
__rshift__(other)¶implement the >> operator.
Not used by SQLAlchemy core, this is provided for custom operator systems which want to use >> as an extension point.
sqlalchemy.sql.expression.ColumnOperators.
__rsub__(other)¶Implement the -
operator in reverse.
sqlalchemy.sql.expression.ColumnOperators.
__rtruediv__(other)¶Implement the //
operator in reverse.
sqlalchemy.sql.expression.ColumnOperators.
__sub__(other)¶Implement the -
operator.
In a column context, produces the clause a - b
.
sqlalchemy.sql.expression.ColumnOperators.
__truediv__(other)¶Implement the //
operator.
In a column context, produces the clause a / b
.
sqlalchemy.sql.expression.ColumnOperators.
all_()¶Produce a all_()
clause against the
parent object.
This operator is only appropriate against a scalar subquery object, or for some backends an column expression that is against the ARRAY type, e.g.:
# postgresql '5 = ALL (somearray)'
expr = 5 == mytable.c.somearray.all_()
# mysql '5 = ALL (SELECT value FROM table)'
expr = 5 == select(table.c.value).scalar_subquery().all_()
New in version 1.1.
sqlalchemy.sql.expression.ColumnOperators.
any_()¶Produce a any_()
clause against the
parent object.
This operator is only appropriate against a scalar subquery object, or for some backends an column expression that is against the ARRAY type, e.g.:
# postgresql '5 = ANY (somearray)'
expr = 5 == mytable.c.somearray.any_()
# mysql '5 = ANY (SELECT value FROM table)'
expr = 5 == select(table.c.value).scalar_subquery().any_()
New in version 1.1.
sqlalchemy.sql.expression.ColumnOperators.
asc()¶Produce a asc()
clause against the
parent object.
sqlalchemy.sql.expression.ColumnOperators.
between(cleft, cright, symmetric=False)¶Produce a between()
clause against
the parent object, given the lower and upper range.
sqlalchemy.sql.expression.ColumnOperators.
bool_op(opstring, precedence=0)¶inherited from the Operators.bool_op()
method of Operators
Return a custom boolean operator.
This method is shorthand for calling
Operators.op()
and passing the
Operators.op.is_comparison
flag with True.
See also
sqlalchemy.sql.expression.ColumnOperators.
collate(collation)¶Produce a collate()
clause against
the parent object, given the collation string.
See also
sqlalchemy.sql.expression.ColumnOperators.
concat(other)¶Implement the ‘concat’ operator.
In a column context, produces the clause a || b
,
or uses the concat()
operator on MySQL.
sqlalchemy.sql.expression.ColumnOperators.
contains(other, **kwargs)¶Implement the ‘contains’ operator.
Produces a LIKE expression that tests against a match for the middle of a string value:
column LIKE '%' || <other> || '%'
E.g.:
stmt = select(sometable).\
where(sometable.c.column.contains("foobar"))
Since the operator uses LIKE
, wildcard characters
"%"
and "_"
that are present inside the <other> expression
will behave like wildcards as well. For literal string
values, the ColumnOperators.contains.autoescape
flag
may be set to True
to apply escaping to occurrences of these
characters within the string value so that they match as themselves
and not as wildcard characters. Alternatively, the
ColumnOperators.contains.escape
parameter will establish
a given character as an escape character which can be of use when
the target expression is not a literal string.
other¶ – expression to be compared. This is usually a plain
string value, but can also be an arbitrary SQL expression. LIKE
wildcard characters %
and _
are not escaped by default unless
the ColumnOperators.contains.autoescape
flag is
set to True.
autoescape¶ –
boolean; when True, establishes an escape character
within the LIKE expression, then applies it to all occurrences of
"%"
, "_"
and the escape character itself within the
comparison value, which is assumed to be a literal string and not a
SQL expression.
An expression such as:
somecolumn.contains("foo%bar", autoescape=True)
Will render as:
somecolumn LIKE '%' || :param || '%' ESCAPE '/'
With the value of :param
as "foo/%bar"
.
escape¶ –
a character which when given will render with the
ESCAPE
keyword to establish that character as the escape
character. This character can then be placed preceding occurrences
of %
and _
to allow them to act as themselves and not
wildcard characters.
An expression such as:
somecolumn.contains("foo/%bar", escape="^")
Will render as:
somecolumn LIKE '%' || :param || '%' ESCAPE '^'
The parameter may also be combined with
ColumnOperators.contains.autoescape
:
somecolumn.contains("foo%bar^bat", escape="^", autoescape=True)
Where above, the given literal parameter will be converted to
"foo^%bar^^bat"
before being passed to the database.
sqlalchemy.sql.expression.ColumnOperators.
desc()¶Produce a desc()
clause against the
parent object.
sqlalchemy.sql.expression.ColumnOperators.
distinct()¶Produce a distinct()
clause against the
parent object.
sqlalchemy.sql.expression.ColumnOperators.
endswith(other, **kwargs)¶Implement the ‘endswith’ operator.
Produces a LIKE expression that tests against a match for the end of a string value:
column LIKE '%' || <other>
E.g.:
stmt = select(sometable).\
where(sometable.c.column.endswith("foobar"))
Since the operator uses LIKE
, wildcard characters
"%"
and "_"
that are present inside the <other> expression
will behave like wildcards as well. For literal string
values, the ColumnOperators.endswith.autoescape
flag
may be set to True
to apply escaping to occurrences of these
characters within the string value so that they match as themselves
and not as wildcard characters. Alternatively, the
ColumnOperators.endswith.escape
parameter will establish
a given character as an escape character which can be of use when
the target expression is not a literal string.
other¶ – expression to be compared. This is usually a plain
string value, but can also be an arbitrary SQL expression. LIKE
wildcard characters %
and _
are not escaped by default unless
the ColumnOperators.endswith.autoescape
flag is
set to True.
autoescape¶ –
boolean; when True, establishes an escape character
within the LIKE expression, then applies it to all occurrences of
"%"
, "_"
and the escape character itself within the
comparison value, which is assumed to be a literal string and not a
SQL expression.
An expression such as:
somecolumn.endswith("foo%bar", autoescape=True)
Will render as:
somecolumn LIKE '%' || :param ESCAPE '/'
With the value of :param
as "foo/%bar"
.
escape¶ –
a character which when given will render with the
ESCAPE
keyword to establish that character as the escape
character. This character can then be placed preceding occurrences
of %
and _
to allow them to act as themselves and not
wildcard characters.
An expression such as:
somecolumn.endswith("foo/%bar", escape="^")
Will render as:
somecolumn LIKE '%' || :param ESCAPE '^'
The parameter may also be combined with
ColumnOperators.endswith.autoescape
:
somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)
Where above, the given literal parameter will be converted to
"foo^%bar^^bat"
before being passed to the database.
sqlalchemy.sql.expression.ColumnOperators.
ilike(other, escape=None)¶Implement the ilike
operator, e.g. case insensitive LIKE.
In a column context, produces an expression either of the form:
lower(a) LIKE lower(other)
Or on backends that support the ILIKE operator:
a ILIKE other
E.g.:
stmt = select(sometable).\
where(sometable.c.column.ilike("%foobar%"))
See also
sqlalchemy.sql.expression.ColumnOperators.
in_(other)¶Implement the in
operator.
In a column context, produces the clause column IN <other>
.
The given parameter other
may be:
A list of literal values, e.g.:
stmt.where(column.in_([1, 2, 3]))
In this calling form, the list of items is converted to a set of bound parameters the same length as the list given:
WHERE COL IN (?, ?, ?)
A list of tuples may be provided if the comparison is against a
tuple_()
containing multiple expressions:
from sqlalchemy import tuple_
stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)]))
An empty list, e.g.:
stmt.where(column.in_([]))
In this calling form, the expression renders an “empty set” expression. These expressions are tailored to individual backends and are generally trying to get an empty SELECT statement as a subquery. Such as on SQLite, the expression is:
WHERE col IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)
Changed in version 1.4: empty IN expressions now use an execution-time generated SELECT subquery in all cases.
A bound parameter, e.g. bindparam()
, may be used if it
includes the bindparam.expanding
flag:
stmt.where(column.in_(bindparam('value', expanding=True)))
In this calling form, the expression renders a special non-SQL placeholder expression that looks like:
WHERE COL IN ([EXPANDING_value])
This placeholder expression is intercepted at statement execution time to be converted into the variable number of bound parameter form illustrated earlier. If the statement were executed as:
connection.execute(stmt, {"value": [1, 2, 3]})
The database would be passed a bound parameter for each value:
WHERE COL IN (?, ?, ?)
New in version 1.2: added “expanding” bound parameters
If an empty list is passed, a special “empty list” expression, which is specific to the database in use, is rendered. On SQLite this would be:
WHERE COL IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)
New in version 1.3: “expanding” bound parameters now support empty lists
a select()
construct, which is usually a
correlated scalar select:
stmt.where(
column.in_(
select(othertable.c.y).
where(table.c.x == othertable.c.x)
)
)
In this calling form, ColumnOperators.in_()
renders as given:
WHERE COL IN (SELECT othertable.y
FROM othertable WHERE othertable.x = table.x)
other¶ – a list of literals, a select()
construct, or a bindparam()
construct that includes the
bindparam.expanding
flag set to True.
sqlalchemy.sql.expression.ColumnOperators.
is_(other)¶Implement the IS
operator.
Normally, IS
is generated automatically when comparing to a
value of None
, which resolves to NULL
. However, explicit
usage of IS
may be desirable if comparing to boolean values
on certain platforms.
See also
sqlalchemy.sql.expression.ColumnOperators.
is_distinct_from(other)¶Implement the IS DISTINCT FROM
operator.
Renders “a IS DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS NOT b”.
New in version 1.1.
sqlalchemy.sql.expression.ColumnOperators.
is_not(other)¶Implement the IS NOT
operator.
Normally, IS NOT
is generated automatically when comparing to a
value of None
, which resolves to NULL
. However, explicit
usage of IS NOT
may be desirable if comparing to boolean values
on certain platforms.
Changed in version 1.4: The is_not()
operator is renamed from
isnot()
in previous releases. The previous name remains
available for backwards compatibility.
See also
sqlalchemy.sql.expression.ColumnOperators.
is_not_distinct_from(other)¶Implement the IS NOT DISTINCT FROM
operator.
Renders “a IS NOT DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS b”.
Changed in version 1.4: The is_not_distinct_from()
operator is
renamed from isnot_distinct_from()
in previous releases.
The previous name remains available for backwards compatibility.
New in version 1.1.
sqlalchemy.sql.expression.ColumnOperators.
isnot(other)¶Implement the IS NOT
operator.
Normally, IS NOT
is generated automatically when comparing to a
value of None
, which resolves to NULL
. However, explicit
usage of IS NOT
may be desirable if comparing to boolean values
on certain platforms.
Changed in version 1.4: The is_not()
operator is renamed from
isnot()
in previous releases. The previous name remains
available for backwards compatibility.
See also
sqlalchemy.sql.expression.ColumnOperators.
isnot_distinct_from(other)¶Implement the IS NOT DISTINCT FROM
operator.
Renders “a IS NOT DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS b”.
Changed in version 1.4: The is_not_distinct_from()
operator is
renamed from isnot_distinct_from()
in previous releases.
The previous name remains available for backwards compatibility.
New in version 1.1.
sqlalchemy.sql.expression.ColumnOperators.
like(other, escape=None)¶Implement the like
operator.
In a column context, produces the expression:
a LIKE other
E.g.:
stmt = select(sometable).\
where(sometable.c.column.like("%foobar%"))
See also
sqlalchemy.sql.expression.ColumnOperators.
match(other, **kwargs)¶Implements a database-specific ‘match’ operator.
ColumnOperators.match()
attempts to resolve to
a MATCH-like function or operator provided by the backend.
Examples include:
PostgreSQL - renders x @@ to_tsquery(y)
MySQL - renders MATCH (x) AGAINST (y IN BOOLEAN MODE)
See also
match
- MySQL specific construct with
additional features.
Oracle - renders CONTAINS(x, y)
other backends may provide special implementations.
Backends without any special implementation will emit the operator as “MATCH”. This is compatible with SQLite, for example.
sqlalchemy.sql.expression.ColumnOperators.
not_ilike(other, escape=None)¶implement the NOT ILIKE
operator.
This is equivalent to using negation with
ColumnOperators.ilike()
, i.e. ~x.ilike(y)
.
Changed in version 1.4: The not_ilike()
operator is renamed from
notilike()
in previous releases. The previous name remains
available for backwards compatibility.
See also
sqlalchemy.sql.expression.ColumnOperators.
not_in(other)¶implement the NOT IN
operator.
This is equivalent to using negation with
ColumnOperators.in_()
, i.e. ~x.in_(y)
.
In the case that other
is an empty sequence, the compiler
produces an “empty not in” expression. This defaults to the
expression “1 = 1” to produce true in all cases. The
create_engine.empty_in_strategy
may be used to
alter this behavior.
Changed in version 1.4: The not_in()
operator is renamed from
notin_()
in previous releases. The previous name remains
available for backwards compatibility.
Changed in version 1.2: The ColumnOperators.in_()
and
ColumnOperators.not_in()
operators
now produce a “static” expression for an empty IN sequence
by default.
See also
sqlalchemy.sql.expression.ColumnOperators.
not_like(other, escape=None)¶implement the NOT LIKE
operator.
This is equivalent to using negation with
ColumnOperators.like()
, i.e. ~x.like(y)
.
Changed in version 1.4: The not_like()
operator is renamed from
notlike()
in previous releases. The previous name remains
available for backwards compatibility.
See also
sqlalchemy.sql.expression.ColumnOperators.
notilike(other, escape=None)¶implement the NOT ILIKE
operator.
This is equivalent to using negation with
ColumnOperators.ilike()
, i.e. ~x.ilike(y)
.
Changed in version 1.4: The not_ilike()
operator is renamed from
notilike()
in previous releases. The previous name remains
available for backwards compatibility.
See also
sqlalchemy.sql.expression.ColumnOperators.
notin_(other)¶implement the NOT IN
operator.
This is equivalent to using negation with
ColumnOperators.in_()
, i.e. ~x.in_(y)
.
In the case that other
is an empty sequence, the compiler
produces an “empty not in” expression. This defaults to the
expression “1 = 1” to produce true in all cases. The
create_engine.empty_in_strategy
may be used to
alter this behavior.
Changed in version 1.4: The not_in()
operator is renamed from
notin_()
in previous releases. The previous name remains
available for backwards compatibility.
Changed in version 1.2: The ColumnOperators.in_()
and
ColumnOperators.not_in()
operators
now produce a “static” expression for an empty IN sequence
by default.
See also
sqlalchemy.sql.expression.ColumnOperators.
notlike(other, escape=None)¶implement the NOT LIKE
operator.
This is equivalent to using negation with
ColumnOperators.like()
, i.e. ~x.like(y)
.
Changed in version 1.4: The not_like()
operator is renamed from
notlike()
in previous releases. The previous name remains
available for backwards compatibility.
See also
sqlalchemy.sql.expression.ColumnOperators.
nulls_first()¶Produce a nulls_first()
clause against the
parent object.
Changed in version 1.4: The nulls_first()
operator is
renamed from nullsfirst()
in previous releases.
The previous name remains available for backwards compatibility.
sqlalchemy.sql.expression.ColumnOperators.
nulls_last()¶Produce a nulls_last()
clause against the
parent object.
Changed in version 1.4: The nulls_last()
operator is
renamed from nullslast()
in previous releases.
The previous name remains available for backwards compatibility.
sqlalchemy.sql.expression.ColumnOperators.
nullsfirst()¶Produce a nulls_first()
clause against the
parent object.
Changed in version 1.4: The nulls_first()
operator is
renamed from nullsfirst()
in previous releases.
The previous name remains available for backwards compatibility.
sqlalchemy.sql.expression.ColumnOperators.
nullslast()¶Produce a nulls_last()
clause against the
parent object.
Changed in version 1.4: The nulls_last()
operator is
renamed from nullslast()
in previous releases.
The previous name remains available for backwards compatibility.
sqlalchemy.sql.expression.ColumnOperators.
op(opstring, precedence=0, is_comparison=False, return_type=None)¶inherited from the Operators.op()
method of Operators
Produce a generic operator function.
e.g.:
somecolumn.op("*")(5)
produces:
somecolumn * 5
This function can also be used to make bitwise operators explicit. For example:
somecolumn.op('&')(0xff)
is a bitwise AND of the value in somecolumn
.
operator¶ – a string which will be output as the infix operator between this element and the expression passed to the generated function.
precedence¶ – precedence to apply to the operator, when
parenthesizing expressions. A lower number will cause the expression
to be parenthesized when applied against another operator with
higher precedence. The default value of 0
is lower than all
operators except for the comma (,
) and AS
operators.
A value of 100 will be higher or equal to all operators, and -100
will be lower than or equal to all operators.
is_comparison¶ –
if True, the operator will be considered as a
“comparison” operator, that is which evaluates to a boolean
true/false value, like ==
, >
, etc. This flag should be set
so that ORM relationships can establish that the operator is a
comparison operator when used in a custom join condition.
New in version 0.9.2: - added the
Operators.op.is_comparison
flag.
return_type¶ – a TypeEngine
class or object that will
force the return type of an expression produced by this operator
to be of that type. By default, operators that specify
Operators.op.is_comparison
will resolve to
Boolean
, and those that do not will be of the same
type as the left-hand operand.
sqlalchemy.sql.expression.ColumnOperators.
operate(op, *other, **kwargs)¶inherited from the Operators.operate()
method of Operators
Operate on an argument.
This is the lowest level of operation, raises
NotImplementedError
by default.
Overriding this on a subclass can allow common
behavior to be applied to all operations.
For example, overriding ColumnOperators
to apply func.lower()
to the left and right
side:
class MyComparator(ColumnOperators):
def operate(self, op, other):
return op(func.lower(self), func.lower(other))
op¶ – Operator callable.
*other¶ – the ‘other’ side of the operation. Will be a single scalar for most operations.
**kwargs¶ – modifiers. These may be passed by special
operators such as ColumnOperators.contains()
.
sqlalchemy.sql.expression.ColumnOperators.
regexp_match(pattern, flags=None)¶Implements a database-specific ‘regexp match’ operator.
E.g.:
stmt = select(table.c.some_column).where(
table.c.some_column.regexp_match('^(b|c)')
)
ColumnOperators.regexp_match()
attempts to resolve to
a REGEXP-like function or operator provided by the backend, however
the specific regular expression syntax and flags available are
not backend agnostic.
Examples include:
PostgreSQL - renders x ~ y
or x !~ y
when negated.
Oracle - renders REGEXP_LIKE(x, y)
SQLite - uses SQLite’s REGEXP
placeholder operator and calls into
the Python re.match()
builtin.
other backends may provide special implementations.
Backends without any special implementation will emit the operator as “REGEXP” or “NOT REGEXP”. This is compatible with SQLite and MySQL, for example.
Regular expression support is currently implemented for Oracle, PostgreSQL, MySQL and MariaDB. Partial support is available for SQLite. Support among third-party dialects may vary.
pattern¶ – The regular expression pattern string or column clause.
flags¶ – Any regular expression string flags to apply. Flags
tend to be backend specific. It can be a string or a column clause.
Some backends, like PostgreSQL and MariaDB, may alternatively
specify the flags as part of the pattern.
When using the ignore case flag ‘i’ in PostgreSQL, the ignore case
regexp match operator ~*
or !~*
will be used.
New in version 1.4.
See also
sqlalchemy.sql.expression.ColumnOperators.
regexp_replace(pattern, replacement, flags=None)¶Implements a database-specific ‘regexp replace’ operator.
E.g.:
stmt = select(
table.c.some_column.regexp_replace(
'b(..)',
'XY',
flags='g'
)
)
ColumnOperators.regexp_replace()
attempts to resolve to
a REGEXP_REPLACE-like function provided by the backend, that
usually emit the function REGEXP_REPLACE()
. However,
the specific regular expression syntax and flags available are
not backend agnostic.
Regular expression replacement support is currently implemented for Oracle, PostgreSQL, MySQL 8 or greater and MariaDB. Support among third-party dialects may vary.
pattern¶ – The regular expression pattern string or column clause.
pattern¶ – The replacement string or column clause.
flags¶ – Any regular expression string flags to apply. Flags tend to be backend specific. It can be a string or a column clause. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern.
New in version 1.4.
See also
sqlalchemy.sql.expression.ColumnOperators.
reverse_operate(op, other, **kwargs)¶inherited from the Operators.reverse_operate()
method of Operators
Reverse operate on an argument.
Usage is the same as operate()
.
sqlalchemy.sql.expression.ColumnOperators.
startswith(other, **kwargs)¶Implement the startswith
operator.
Produces a LIKE expression that tests against a match for the start of a string value:
column LIKE <other> || '%'
E.g.:
stmt = select(sometable).\
where(sometable.c.column.startswith("foobar"))
Since the operator uses LIKE
, wildcard characters
"%"
and "_"
that are present inside the <other> expression
will behave like wildcards as well. For literal string
values, the ColumnOperators.startswith.autoescape
flag
may be set to True
to apply escaping to occurrences of these
characters within the string value so that they match as themselves
and not as wildcard characters. Alternatively, the
ColumnOperators.startswith.escape
parameter will establish
a given character as an escape character which can be of use when
the target expression is not a literal string.
other¶ – expression to be compared. This is usually a plain
string value, but can also be an arbitrary SQL expression. LIKE
wildcard characters %
and _
are not escaped by default unless
the ColumnOperators.startswith.autoescape
flag is
set to True.
autoescape¶ –
boolean; when True, establishes an escape character
within the LIKE expression, then applies it to all occurrences of
"%"
, "_"
and the escape character itself within the
comparison value, which is assumed to be a literal string and not a
SQL expression.
An expression such as:
somecolumn.startswith("foo%bar", autoescape=True)
Will render as:
somecolumn LIKE :param || '%' ESCAPE '/'
With the value of :param
as "foo/%bar"
.
escape¶ –
a character which when given will render with the
ESCAPE
keyword to establish that character as the escape
character. This character can then be placed preceding occurrences
of %
and _
to allow them to act as themselves and not
wildcard characters.
An expression such as:
somecolumn.startswith("foo/%bar", escape="^")
Will render as:
somecolumn LIKE :param || '%' ESCAPE '^'
The parameter may also be combined with
ColumnOperators.startswith.autoescape
:
somecolumn.startswith("foo%bar^bat", escape="^", autoescape=True)
Where above, the given literal parameter will be converted to
"foo^%bar^^bat"
before being passed to the database.
sqlalchemy.sql.expression.ColumnOperators.
timetuple = None¶Hack, allows datetime objects to be compared on the LHS.
Establish the ability for a class to have dialect-specific arguments with defaults and constructor validation.
The DialectKWArgs
interacts with the
DefaultDialect.construct_arguments
present on a dialect.
See also
sqlalchemy.sql.base.DialectKWArgs.
classmethod argument_for(dialect_name, argument_name, default)¶Add a new kind of dialect-specific keyword argument for this class.
E.g.:
Index.argument_for("mydialect", "length", None)
some_index = Index('a', 'b', mydialect_length=5)
The DialectKWArgs.argument_for()
method is a per-argument
way adding extra arguments to the
DefaultDialect.construct_arguments
dictionary. This
dictionary provides a list of argument names accepted by various
schema-level constructs on behalf of a dialect.
New dialects should typically specify this dictionary all at once as a data member of the dialect class. The use case for ad-hoc addition of argument names is typically for end-user code that is also using a custom compilation scheme which consumes the additional arguments.
dialect_name¶ – name of a dialect. The dialect must be
locatable, else a NoSuchModuleError
is raised. The
dialect must also include an existing
DefaultDialect.construct_arguments
collection, indicating
that it participates in the keyword-argument validation and default
system, else ArgumentError
is raised. If the dialect does
not include this collection, then any keyword argument can be
specified on behalf of this dialect already. All dialects packaged
within SQLAlchemy include this collection, however for third party
dialects, support may vary.
argument_name¶ – name of the parameter.
default¶ – default value of the parameter.
New in version 0.9.4.
sqlalchemy.sql.base.DialectKWArgs.
dialect_kwargs¶A collection of keyword arguments specified as dialect-specific options to this construct.
The arguments are present here in their original <dialect>_<kwarg>
format. Only arguments that were actually passed are included;
unlike the DialectKWArgs.dialect_options
collection, which
contains all options known by this dialect including defaults.
The collection is also writable; keys are accepted of the
form <dialect>_<kwarg>
where the value will be assembled
into the list of options.
New in version 0.9.2.
Changed in version 0.9.4: The DialectKWArgs.dialect_kwargs
collection is now writable.
See also
DialectKWArgs.dialect_options
- nested dictionary form
sqlalchemy.sql.base.DialectKWArgs.
dialect_options¶A collection of keyword arguments specified as dialect-specific options to this construct.
This is a two-level nested registry, keyed to <dialect_name>
and <argument_name>
. For example, the postgresql_where
argument would be locatable as:
arg = my_object.dialect_options['postgresql']['where']
New in version 0.9.2.
See also
DialectKWArgs.dialect_kwargs
- flat dictionary form
sqlalchemy.sql.base.DialectKWArgs.
kwargs¶A synonym for DialectKWArgs.dialect_kwargs
.
Represent a SQL EXTRACT clause, extract(field FROM expr)
.
Class signature
class sqlalchemy.sql.expression.Extract
(sqlalchemy.sql.expression.ColumnElement
)
sqlalchemy.sql.expression.Extract.
__init__(field, expr, **kwargs)¶Construct a new Extract
object.
This constructor is mirrored as a public API function; see sqlalchemy.sql.expression.extract()
for a full usage and argument description.
Represent the false
keyword, or equivalent, in a SQL statement.
False_
is accessed as a constant via the
false()
function.
Class signature
class sqlalchemy.sql.expression.False_
(sqlalchemy.sql.expression.SingletonConstant
, sqlalchemy.sql.roles.ConstExprRole
, sqlalchemy.sql.expression.ColumnElement
)
Represent a function FILTER clause.
This is a special operator against aggregate and window functions, which controls which rows are passed to it. It’s supported only by certain database backends.
Invocation of FunctionFilter
is via
FunctionElement.filter()
:
func.count(1).filter(True)
New in version 1.0.0.
See also
Class signature
class sqlalchemy.sql.expression.FunctionFilter
(sqlalchemy.sql.expression.ColumnElement
)
sqlalchemy.sql.expression.FunctionFilter.
__init__(func, *criterion)¶Construct a new FunctionFilter
object.
This constructor is mirrored as a public API function; see sqlalchemy.sql.expression.funcfilter()
for a full usage and argument description.
sqlalchemy.sql.expression.FunctionFilter.
filter(*criterion)¶Produce an additional FILTER against the function.
This method adds additional criteria to the initial criteria
set up by FunctionElement.filter()
.
Multiple criteria are joined together at SQL render time
via AND
.
sqlalchemy.sql.expression.FunctionFilter.
over(partition_by=None, order_by=None, range_=None, rows=None)¶Produce an OVER clause against this filtered function.
Used against aggregate or so-called “window” functions, for database backends that support window functions.
The expression:
func.rank().filter(MyClass.y > 5).over(order_by='x')
is shorthand for:
from sqlalchemy import over, funcfilter
over(funcfilter(func.rank(), MyClass.y > 5), order_by='x')
See over()
for a full description.
sqlalchemy.sql.expression.FunctionFilter.
self_group(against=None)¶Apply a ‘grouping’ to this ClauseElement
.
This method is overridden by subclasses to return a “grouping”
construct, i.e. parenthesis. In particular it’s used by “binary”
expressions to provide a grouping around themselves when placed into a
larger expression, as well as by select()
constructs when placed into the FROM clause of another
select()
. (Note that subqueries should be
normally created using the Select.alias()
method,
as many
platforms require nested SELECT statements to be named).
As expressions are composed together, the application of
self_group()
is automatic - end-user code should never
need to use this method directly. Note that SQLAlchemy’s
clause constructs take operator precedence into account -
so parenthesis might not be needed, for example, in
an expression like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
Represents a column label (AS).
Represent a label, as typically applied to any column-level
element using the AS
sql keyword.
Class signature
class sqlalchemy.sql.expression.Label
(sqlalchemy.sql.roles.LabeledColumnExprRole
, sqlalchemy.sql.expression.ColumnElement
)
sqlalchemy.sql.expression.Label.
__init__(name, element, type_=None)¶Construct a new Label
object.
This constructor is mirrored as a public API function; see sqlalchemy.sql.expression.label()
for a full usage and argument description.
sqlalchemy.sql.expression.Label.
foreign_keys¶sqlalchemy.sql.expression.Label.
primary_key¶sqlalchemy.sql.expression.Label.
self_group(against=None)¶Apply a ‘grouping’ to this ClauseElement
.
This method is overridden by subclasses to return a “grouping”
construct, i.e. parenthesis. In particular it’s used by “binary”
expressions to provide a grouping around themselves when placed into a
larger expression, as well as by select()
constructs when placed into the FROM clause of another
select()
. (Note that subqueries should be
normally created using the Select.alias()
method,
as many
platforms require nested SELECT statements to be named).
As expressions are composed together, the application of
self_group()
is automatic - end-user code should never
need to use this method directly. Note that SQLAlchemy’s
clause constructs take operator precedence into account -
so parenthesis might not be needed, for example, in
an expression like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
A SQL construct where the state is stored as an un-invoked lambda.
The LambdaElement
is produced transparently whenever
passing lambda expressions into SQL constructs, such as:
stmt = select(table).where(lambda: table.c.col == parameter)
The LambdaElement
is the base of the
StatementLambdaElement
which represents a full statement
within a lambda.
New in version 1.4.
Class signature
class sqlalchemy.sql.expression.LambdaElement
(sqlalchemy.sql.expression.ClauseElement
)
Represent the NULL keyword in a SQL statement.
Null
is accessed as a constant via the
null()
function.
Class signature
class sqlalchemy.sql.expression.Null
(sqlalchemy.sql.expression.SingletonConstant
, sqlalchemy.sql.roles.ConstExprRole
, sqlalchemy.sql.expression.ColumnElement
)
Base of comparison and logical operators.
Implements base methods
Operators.operate()
and
Operators.reverse_operate()
, as well as
Operators.__and__()
,
Operators.__or__()
,
Operators.__invert__()
.
Usually is used via its most common subclass
ColumnOperators
.
sqlalchemy.sql.expression.Operators.
__and__(other)¶Implement the &
operator.
When used with SQL expressions, results in an
AND operation, equivalent to
and_()
, that is:
a & b
is equivalent to:
from sqlalchemy import and_
and_(a, b)
Care should be taken when using &
regarding
operator precedence; the &
operator has the highest precedence.
The operands should be enclosed in parenthesis if they contain
further sub expressions:
(a == 2) & (b == 4)
sqlalchemy.sql.expression.Operators.
__invert__()¶Implement the ~
operator.
When used with SQL expressions, results in a
NOT operation, equivalent to
not_()
, that is:
~a
is equivalent to:
from sqlalchemy import not_
not_(a)
sqlalchemy.sql.expression.Operators.
__or__(other)¶Implement the |
operator.
When used with SQL expressions, results in an
OR operation, equivalent to
or_()
, that is:
a | b
is equivalent to:
from sqlalchemy import or_
or_(a, b)
Care should be taken when using |
regarding
operator precedence; the |
operator has the highest precedence.
The operands should be enclosed in parenthesis if they contain
further sub expressions:
(a == 2) | (b == 4)
sqlalchemy.sql.expression.Operators.
bool_op(opstring, precedence=0)¶Return a custom boolean operator.
This method is shorthand for calling
Operators.op()
and passing the
Operators.op.is_comparison
flag with True.
See also
sqlalchemy.sql.expression.Operators.
op(opstring, precedence=0, is_comparison=False, return_type=None)¶Produce a generic operator function.
e.g.:
somecolumn.op("*")(5)
produces:
somecolumn * 5
This function can also be used to make bitwise operators explicit. For example:
somecolumn.op('&')(0xff)
is a bitwise AND of the value in somecolumn
.
operator¶ – a string which will be output as the infix operator between this element and the expression passed to the generated function.
precedence¶ – precedence to apply to the operator, when
parenthesizing expressions. A lower number will cause the expression
to be parenthesized when applied against another operator with
higher precedence. The default value of 0
is lower than all
operators except for the comma (,
) and AS
operators.
A value of 100 will be higher or equal to all operators, and -100
will be lower than or equal to all operators.
is_comparison¶ –
if True, the operator will be considered as a
“comparison” operator, that is which evaluates to a boolean
true/false value, like ==
, >
, etc. This flag should be set
so that ORM relationships can establish that the operator is a
comparison operator when used in a custom join condition.
New in version 0.9.2: - added the
Operators.op.is_comparison
flag.
return_type¶ – a TypeEngine
class or object that will
force the return type of an expression produced by this operator
to be of that type. By default, operators that specify
Operators.op.is_comparison
will resolve to
Boolean
, and those that do not will be of the same
type as the left-hand operand.
sqlalchemy.sql.expression.Operators.
operate(op, *other, **kwargs)¶Operate on an argument.
This is the lowest level of operation, raises
NotImplementedError
by default.
Overriding this on a subclass can allow common
behavior to be applied to all operations.
For example, overriding ColumnOperators
to apply func.lower()
to the left and right
side:
class MyComparator(ColumnOperators):
def operate(self, op, other):
return op(func.lower(self), func.lower(other))
op¶ – Operator callable.
*other¶ – the ‘other’ side of the operation. Will be a single scalar for most operations.
**kwargs¶ – modifiers. These may be passed by special
operators such as ColumnOperators.contains()
.
sqlalchemy.sql.expression.Operators.
reverse_operate(op, other, **kwargs)¶Reverse operate on an argument.
Usage is the same as operate()
.
Represent an OVER clause.
This is a special operator against a so-called “window” function, as well as any aggregate function, which produces results relative to the result set itself. Most modern SQL backends now support window functions.
Class signature
class sqlalchemy.sql.expression.Over
(sqlalchemy.sql.expression.ColumnElement
)
sqlalchemy.sql.expression.Over.
__init__(element, partition_by=None, order_by=None, range_=None, rows=None)¶Construct a new Over
object.
This constructor is mirrored as a public API function; see sqlalchemy.sql.expression.over()
for a full usage and argument description.
sqlalchemy.sql.expression.Over.
element = None¶The underlying expression object to which this Over
object refers towards.
Represent a composable SQL statement as a LambdaElement
.
The StatementLambdaElement
is constructed using the
lambda_stmt()
function:
from sqlalchemy import lambda_stmt
stmt = lambda_stmt(lambda: select(table))
Once constructed, additional criteria can be built onto the statement by adding subsequent lambdas, which accept the existing statement object as a single parameter:
stmt += lambda s: s.where(table.c.col == parameter)
New in version 1.4.
Class signature
class sqlalchemy.sql.expression.StatementLambdaElement
(sqlalchemy.sql.roles.AllowsLambdaRole
, sqlalchemy.sql.lambdas.LambdaElement
)
sqlalchemy.sql.expression.StatementLambdaElement.
add_criteria(other, enable_tracking=True, track_on=None, track_closure_variables=True, track_bound_values=True)¶Add new criteria to this StatementLambdaElement
.
E.g.:
>>> def my_stmt(parameter):
... stmt = lambda_stmt(
... lambda: select(table.c.x, table.c.y),
... )
... stmt = stmt.add_criteria(
... lambda: table.c.x > parameter
... )
... return stmt
The StatementLambdaElement.add_criteria()
method is
equivalent to using the Python addition operator to add a new
lambda, except that additional arguments may be added including
track_closure_values
and track_on
:
>>> def my_stmt(self, foo):
... stmt = lambda_stmt(
... lambda: select(func.max(foo.x, foo.y)),
... track_closure_variables=False
... )
... stmt = stmt.add_criteria(
... lambda: self.where_criteria,
... track_on=[self]
... )
... return stmt
See lambda_stmt()
for a description of the parameters
accepted.
sqlalchemy.sql.expression.StatementLambdaElement.
spoil()¶Return a new StatementLambdaElement
that will run
all lambdas unconditionally each time.
Represent a literal SQL text fragment.
E.g.:
from sqlalchemy import text
t = text("SELECT * FROM users")
result = connection.execute(t)
The TextClause
construct is produced using the
text()
function; see that function for full documentation.
See also
Class signature
class sqlalchemy.sql.expression.TextClause
(sqlalchemy.sql.roles.DDLConstraintColumnRole
, sqlalchemy.sql.roles.DDLExpressionRole
, sqlalchemy.sql.roles.StatementOptionRole
, sqlalchemy.sql.roles.WhereHavingRole
, sqlalchemy.sql.roles.OrderByRole
, sqlalchemy.sql.roles.FromClauseRole
, sqlalchemy.sql.roles.SelectStatementRole
, sqlalchemy.sql.roles.BinaryElementRole
, sqlalchemy.sql.roles.InElementRole
, sqlalchemy.sql.expression.Executable
, sqlalchemy.sql.expression.ClauseElement
)
sqlalchemy.sql.expression.TextClause.
bindparams(*binds, **names_to_values)¶Establish the values and/or types of bound parameters within
this TextClause
construct.
Given a text construct such as:
from sqlalchemy import text
stmt = text("SELECT id, name FROM user WHERE name=:name "
"AND timestamp=:timestamp")
the TextClause.bindparams()
method can be used to establish
the initial value of :name
and :timestamp
,
using simple keyword arguments:
stmt = stmt.bindparams(name='jack',
timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))
Where above, new BindParameter
objects
will be generated with the names name
and timestamp
, and
values of jack
and datetime.datetime(2012, 10, 8, 15, 12, 5)
,
respectively. The types will be
inferred from the values given, in this case String
and
DateTime
.
When specific typing behavior is needed, the positional *binds
argument can be used in which to specify bindparam()
constructs
directly. These constructs must include at least the key
argument, then an optional value and type:
from sqlalchemy import bindparam
stmt = stmt.bindparams(
bindparam('name', value='jack', type_=String),
bindparam('timestamp', type_=DateTime)
)
Above, we specified the type of DateTime
for the
timestamp
bind, and the type of String
for the name
bind. In the case of name
we also set the default value of
"jack"
.
Additional bound parameters can be supplied at statement execution time, e.g.:
result = connection.execute(stmt,
timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))
The TextClause.bindparams()
method can be called repeatedly,
where it will re-use existing BindParameter
objects to add
new information. For example, we can call
TextClause.bindparams()
first with typing information, and a
second time with value information, and it will be combined:
stmt = text("SELECT id, name FROM user WHERE name=:name "
"AND timestamp=:timestamp")
stmt = stmt.bindparams(
bindparam('name', type_=String),
bindparam('timestamp', type_=DateTime)
)
stmt = stmt.bindparams(
name='jack',
timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)
)
The TextClause.bindparams()
method also supports the concept of
unique bound parameters. These are parameters that are
“uniquified” on name at statement compilation time, so that multiple
text()
constructs may be combined together without the names
conflicting. To use this feature, specify the
BindParameter.unique
flag on each bindparam()
object:
stmt1 = text("select id from table where name=:name").bindparams(
bindparam("name", value='name1', unique=True)
)
stmt2 = text("select id from table where name=:name").bindparams(
bindparam("name", value='name2', unique=True)
)
union = union_all(
stmt1.columns(column("id")),
stmt2.columns(column("id"))
)
The above statement will render as:
select id from table where name=:name_1
UNION ALL select id from table where name=:name_2
New in version 1.3.11: Added support for the
BindParameter.unique
flag to work with
text()
constructs.
sqlalchemy.sql.expression.TextClause.
columns(*cols, **types)¶Turn this TextClause
object into a
TextualSelect
object that serves the same role as a SELECT
statement.
The TextualSelect
is part of the
SelectBase
hierarchy and can be embedded into another statement by using the
TextualSelect.subquery()
method to produce a
Subquery
object, which can then be SELECTed from.
This function essentially bridges the gap between an entirely textual SELECT statement and the SQL expression language concept of a “selectable”:
from sqlalchemy.sql import column, text
stmt = text("SELECT id, name FROM some_table")
stmt = stmt.columns(column('id'), column('name')).subquery('st')
stmt = select(mytable).\
select_from(
mytable.join(stmt, mytable.c.name == stmt.c.name)
).where(stmt.c.id > 5)
Above, we pass a series of column()
elements to the
TextClause.columns()
method positionally. These
column()
elements now become first class elements upon the
TextualSelect.selected_columns
column collection,
which then
become part of the Subquery.c
collection after
TextualSelect.subquery()
is invoked.
The column expressions we pass to
TextClause.columns()
may
also be typed; when we do so, these TypeEngine
objects become
the effective return type of the column, so that SQLAlchemy’s
result-set-processing systems may be used on the return values.
This is often needed for types such as date or boolean types, as well
as for unicode processing on some dialect configurations:
stmt = text("SELECT id, name, timestamp FROM some_table")
stmt = stmt.columns(
column('id', Integer),
column('name', Unicode),
column('timestamp', DateTime)
)
for id, name, timestamp in connection.execute(stmt):
print(id, name, timestamp)
As a shortcut to the above syntax, keyword arguments referring to types alone may be used, if only type conversion is needed:
stmt = text("SELECT id, name, timestamp FROM some_table")
stmt = stmt.columns(
id=Integer,
name=Unicode,
timestamp=DateTime
)
for id, name, timestamp in connection.execute(stmt):
print(id, name, timestamp)
The positional form of TextClause.columns()
also provides the
unique feature of positional column targeting, which is
particularly useful when using the ORM with complex textual queries. If
we specify the columns from our model to
TextClause.columns()
,
the result set will match to those columns positionally, meaning the
name or origin of the column in the textual SQL doesn’t matter:
stmt = text("SELECT users.id, addresses.id, users.id, "
"users.name, addresses.email_address AS email "
"FROM users JOIN addresses ON users.id=addresses.user_id "
"WHERE users.id = 1").columns(
User.id,
Address.id,
Address.user_id,
User.name,
Address.email_address
)
query = session.query(User).from_statement(stmt).options(
contains_eager(User.addresses))
New in version 1.1: the TextClause.columns()
method now
offers positional column targeting in the result set when
the column expressions are passed purely positionally.
The TextClause.columns()
method provides a direct
route to calling FromClause.subquery()
as well as
SelectBase.cte()
against a textual SELECT statement:
stmt = stmt.columns(id=Integer, name=String).cte('st')
stmt = select(sometable).where(sometable.c.id == stmt.c.id)
*cols¶ – A series of ColumnElement
objects,
typically
Column
objects from a Table
or ORM level
column-mapped attributes, representing a set of columns that this
textual string will SELECT from.
**types¶ – A mapping of string names to TypeEngine
type objects indicating the datatypes to use for names that are
SELECTed from the textual string. Prefer to use the *cols
argument as it also indicates positional ordering.
sqlalchemy.sql.expression.TextClause.
self_group(against=None)¶Apply a ‘grouping’ to this ClauseElement
.
This method is overridden by subclasses to return a “grouping”
construct, i.e. parenthesis. In particular it’s used by “binary”
expressions to provide a grouping around themselves when placed into a
larger expression, as well as by select()
constructs when placed into the FROM clause of another
select()
. (Note that subqueries should be
normally created using the Select.alias()
method,
as many
platforms require nested SELECT statements to be named).
As expressions are composed together, the application of
self_group()
is automatic - end-user code should never
need to use this method directly. Note that SQLAlchemy’s
clause constructs take operator precedence into account -
so parenthesis might not be needed, for example, in
an expression like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
Represent a SQL tuple.
Class signature
class sqlalchemy.sql.expression.Tuple
(sqlalchemy.sql.expression.ClauseList
, sqlalchemy.sql.expression.ColumnElement
)
sqlalchemy.sql.expression.Tuple.
__init__(*clauses, **kw)¶Construct a new Tuple
object.
This constructor is mirrored as a public API function; see sqlalchemy.sql.expression.tuple_()
for a full usage and argument description.
sqlalchemy.sql.expression.Tuple.
self_group(against=None)¶Apply a ‘grouping’ to this ClauseElement
.
This method is overridden by subclasses to return a “grouping”
construct, i.e. parenthesis. In particular it’s used by “binary”
expressions to provide a grouping around themselves when placed into a
larger expression, as well as by select()
constructs when placed into the FROM clause of another
select()
. (Note that subqueries should be
normally created using the Select.alias()
method,
as many
platforms require nested SELECT statements to be named).
As expressions are composed together, the application of
self_group()
is automatic - end-user code should never
need to use this method directly. Note that SQLAlchemy’s
clause constructs take operator precedence into account -
so parenthesis might not be needed, for example, in
an expression like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
Represent a WITHIN GROUP (ORDER BY) clause.
This is a special operator against so-called
“ordered set aggregate” and “hypothetical
set aggregate” functions, including percentile_cont()
,
rank()
, dense_rank()
, etc.
It’s supported only by certain database backends, such as PostgreSQL, Oracle and MS SQL Server.
The WithinGroup
construct extracts its type from the
method FunctionElement.within_group_type()
. If this returns
None
, the function’s .type
is used.
Class signature
class sqlalchemy.sql.expression.WithinGroup
(sqlalchemy.sql.expression.ColumnElement
)
sqlalchemy.sql.expression.WithinGroup.
__init__(element, *order_by)¶Construct a new WithinGroup
object.
This constructor is mirrored as a public API function; see sqlalchemy.sql.expression.within_group()
for a full usage and argument description.
sqlalchemy.sql.expression.WithinGroup.
over(partition_by=None, order_by=None, range_=None, rows=None)¶Produce an OVER clause against this WithinGroup
construct.
This function has the same signature as that of
FunctionElement.over()
.
Mixin that defines a ColumnElement
as a wrapper with special
labeling behavior for an expression that already has a name.
New in version 1.4.
Represent the true
keyword, or equivalent, in a SQL statement.
True_
is accessed as a constant via the
true()
function.
Class signature
class sqlalchemy.sql.expression.True_
(sqlalchemy.sql.expression.SingletonConstant
, sqlalchemy.sql.roles.ConstExprRole
, sqlalchemy.sql.expression.ColumnElement
)
Represent a Python-side type-coercion wrapper.
TypeCoerce
supplies the type_coerce()
function; see that function for usage details.
Changed in version 1.1: The type_coerce()
function now produces
a persistent TypeCoerce
wrapper object rather than
translating the given object in place.
Class signature
class sqlalchemy.sql.expression.TypeCoerce
(sqlalchemy.sql.expression.WrapsColumnExpression
, sqlalchemy.sql.expression.ColumnElement
)
sqlalchemy.sql.expression.TypeCoerce.
__init__(expression, type_)¶Construct a new TypeCoerce
object.
This constructor is mirrored as a public API function; see sqlalchemy.sql.expression.type_coerce()
for a full usage and argument description.
sqlalchemy.sql.expression.TypeCoerce.
self_group(against=None)¶Apply a ‘grouping’ to this ClauseElement
.
This method is overridden by subclasses to return a “grouping”
construct, i.e. parenthesis. In particular it’s used by “binary”
expressions to provide a grouping around themselves when placed into a
larger expression, as well as by select()
constructs when placed into the FROM clause of another
select()
. (Note that subqueries should be
normally created using the Select.alias()
method,
as many
platforms require nested SELECT statements to be named).
As expressions are composed together, the application of
self_group()
is automatic - end-user code should never
need to use this method directly. Note that SQLAlchemy’s
clause constructs take operator precedence into account -
so parenthesis might not be needed, for example, in
an expression like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
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.
UnaryExpression
is the basis for several unary operators
including those used by desc()
, asc()
, distinct()
,
nulls_first()
and nulls_last()
.
Class signature
class sqlalchemy.sql.expression.UnaryExpression
(sqlalchemy.sql.expression.ColumnElement
)
sqlalchemy.sql.expression.UnaryExpression.
self_group(against=None)¶Apply a ‘grouping’ to this ClauseElement
.
This method is overridden by subclasses to return a “grouping”
construct, i.e. parenthesis. In particular it’s used by “binary”
expressions to provide a grouping around themselves when placed into a
larger expression, as well as by select()
constructs when placed into the FROM clause of another
select()
. (Note that subqueries should be
normally created using the Select.alias()
method,
as many
platforms require nested SELECT statements to be named).
As expressions are composed together, the application of
self_group()
is automatic - end-user code should never
need to use this method directly. Note that SQLAlchemy’s
clause constructs take operator precedence into account -
so parenthesis might not be needed, for example, in
an expression like x OR (y AND z)
- AND takes precedence
over OR.
The base self_group()
method of
ClauseElement
just returns self.
flambé! the dragon and The Alchemist image designs created and generously donated by Rotem Yaari.
Created using Sphinx 4.1.2.