The most fundamental part of the SQL expression API are the “column elements”, which allow for basic SQL expression support. The core of all SQL expression constructs is the ClauseElement, which is the base for several sub-branches. The ColumnElement class is the fundamental unit used to construct any kind of typed SQL expression.
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)
See also
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())
Parameters: | 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
Parameters: |
|
---|
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 contruct, 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.
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 list of “when” contructs, 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
Parameters: |
|
---|
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 result-row-handling behavior of the type.
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.
Parameters: |
|
---|
See also
type_coerce() - Python-side type coercion without emitting CAST.
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.sql 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.sql import table, column
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 schema.MetaData, DDL, or events, unlike its Table counterpart.
Parameters: |
|
---|
Return the clause expression COLLATE collation.
e.g.:
collate(mycolumn, 'utf8_bin')
produces:
mycolumn COLLATE utf8_bin
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())
Parameters: | column¶ – A ColumnElement (e.g. scalar SQL expression) with which to apply the desc() operation. |
---|
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 the clause extract(field FROM expr).
Return a False_ object, which compiles to false, or the boolean equivalent for the target dialect.
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 element 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 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.
New in version 0.8: func can return non-function expression constructs for common quasi-functional names like cast() and extract().
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.
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 label() method on ColumnElement.
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.
Parameters: |
|
---|
Return a textual column expression, as would be in the columns clause of a SELECT statement.
The object returned supports further expressions in the same way as any other column object, including comparison, math and string operations. The type_ parameter is important to determine proper expression behavior (such as, ‘+’ means string concatenation or numerical addition based on the type).
Parameters: |
|
---|
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 the NULLS FIRST modifier for an ORDER BY expression.
nullsfirst() 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, nullsfirst
stmt = select([users_table]).\
order_by(nullsfirst(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(), nullsfirst() is typically invoked from the column expression itself using ColumnElement.nullsfirst(), rather than as its standalone function version, as in:
stmt = select([users_table]).\
order_by(users_table.c.name.desc().nullsfirst())
Produce the NULLS LAST modifier for an ORDER BY expression.
nullslast() 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, nullslast
stmt = select([users_table]).\
order_by(nullslast(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(), nullslast() is typically invoked from the column expression itself using ColumnElement.nullslast(), rather than as its standalone function version, as in:
stmt = select([users_table]).\
order_by(users_table.c.name.desc().nullslast())
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')
)
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 ResultProxy object via its out_parameters attribute, which returns a dictionary containing the values.
Produce an OVER clause against a function.
Used against aggregate or so-called “window” functions, for database backends that support window functions.
E.g.:
from sqlalchemy import over
over(func.row_number(), order_by='x')
Would produce “ROW_NUMBER() OVER(ORDER BY x)”.
Parameters: |
|
---|
This function is also available from the func construct itself via the FunctionElement.over() method.
New in version 0.7.
Create a SQL construct that is represented by a literal string.
E.g.:
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.
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'")
To invoke SQLAlchemy typing logic for bind parameters, the bindparams list allows specification of bindparam() constructs which specify the type for a given name:
t = text("SELECT id FROM users WHERE updated_at>:updated",
bindparams=[bindparam('updated', DateTime())]
)
Typing during result row processing is also an important concern. Result column types are specified using the typemap dictionary, where the keys match the names of columns. These names are taken from what the DBAPI returns as cursor.description:
t = text("SELECT id, name FROM users",
typemap={
'id':Integer,
'name':Unicode
}
)
The text() construct is used internally for most cases when a literal string is specified for part of a larger query, such as within select(), update(), insert() or delete(). In those cases, the same bind parameter syntax is applied:
s = select([users.c.id, users.c.name]).where("id=:user_id")
result = connection.execute(s, user_id=12)
Using text() explicitly usually implies the construction of a full, standalone statement. 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)
Note that SQLAlchemy’s usual “autocommit” behavior applies to text() constructs - that is, statements which begin with a phrase such as INSERT, UPDATE, DELETE, or a variety of other phrases specific to certain backends, will be eligible for autocommit if no transaction is in progress.
Parameters: |
|
---|
Return a True_ object, which compiles to true, or the boolean equivalent for the target dialect.
Return a SQL tuple.
Main usage is to produce a composite IN construct:
tuple_(table.c.col1, table.c.col2).in_(
[(1, 2), (5, 12), (10, 19)]
)
Warning
The composite IN construct is not supported by all backends, and is currently known to work on Postgresql and MySQL, but not 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 SQL that is usually otherwise unaffected by the type_coerce() call:
SELECT date_string FROM log
However, when result rows are fetched, the StringDateTime type will be applied to result rows on behalf of the date_string column.
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 compliation/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)])
type_coerce() is similar to the cast() function, except that it does not render the CAST expression in the resulting statement; the bind-side behavior of type_coerce() is also not present in cast() until SQLAlchemy version 0.9.0.
Parameters: |
|
---|
See also
Bases: sqlalchemy.sql.expression.ColumnElement
Represent an expression that is LEFT <operator> RIGHT.
A BinaryExpression is generated automatically whenever two column expressions are used in a Python binary expresion:
>>> from sqlalchemy.sql import column
>>> column('a') + column('b')
<sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0>
>>> print column('a') + column('b')
a + b
Compare this BinaryExpression against the given BinaryExpression.
Bases: sqlalchemy.sql.expression.ColumnElement
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
Construct a BindParameter.
Parameters: |
|
---|
Compare this BindParameter to the given clause.
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.
Bases: sqlalchemy.sql.expression.ColumnElement
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
Bases: sqlalchemy.sql.expression.ColumnElement
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
Bases: sqlalchemy.sql.visitors.Visitable
Base class for elements of a programmatically constructed SQL expression.
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)
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.
Parameters: |
|
---|
Return immediate child elements of this ClauseElement.
This is used for visit traversal.
**kwargs may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level).
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}
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.
Return a copy with bindparam() elements replaced.
Same functionality as params(), except adds unique=True to affected bind parameters so that multiple statements can be used.
Bases: sqlalchemy.sql.expression.ClauseElement
Describe a list of clauses, separated by an operator.
By default, is comma-separated, such as a column listing.
Compare this ClauseList to the given ClauseList, including a comparison of all the clause items.
Bases: sqlalchemy.sql.expression.Immutable, sqlalchemy.sql.expression.ColumnElement
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.sql 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().
Bases: sqlalchemy.util._collections.OrderedProperties
An ordered dictionary that stores a list of ColumnElement instances.
Overrides the __eq__() method to produce SQL clauses between sets of correlated columns.
Add a column to this collection.
The key attribute of the column will be used as the hash key for this dictionary.
add the given column to this collection, removing unaliased versions of this column as well as existing columns with the same key.
e.g.:
t = Table('sometable', metadata, Column('col1', Integer)) t.columns.replace(Column('col1', Integer, key='columnone'))will remove the original ‘col1’ from the collection, and add the new column under the name ‘columnname’.
Used by schema.Column to override columns during table reflection.
Bases: sqlalchemy.sql.expression.ClauseElement, sqlalchemy.sql.operators.ColumnOperators
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 a bindparam() will be produced featuring the given value embedded into the construct; the resulting BindParameter object is an instance of ColumnElement. The Python value will ultimately be sent to the DBAPI at execution time as a paramterized argument to the execute() or executemany() methods, after SQLAlchemy type-specific converters (e.g. those provided by any associated TypeEngine objects) are applied to the value.
- any special object value, typically ORM-level constructs, which feature a method 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 a ColumnElement expression. The __clause_element__() method, if present, should return a ColumnElement instance. The primary use of __clause_element__() within SQLAlchemy is that of class-bound attributes on ORM-mapped classes; a User class which contains a mapped attribute named .name will have a method User.name.__clause_element__() which when invoked returns the Column called name associated with the mapped table.
- The Python None value is typically interpreted as NULL, which in SQLAlchemy Core produces an instance of null().
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
Implement the == operator.
In a column context, produces the clause a = b. If the target is None, produces a IS NULL.
x.__init__(...) initializes x; see help(type(x)) for signature
Implement the <= operator.
In a column context, produces the clause a <= b.
Implement the < operator.
In a column context, produces the clause a < b.
Implement the != operator.
In a column context, produces the clause a != b. If the target is None, produces a IS NOT NULL.
provides a constant ‘anonymous label’ for this ColumnElement.
This is a label() expression which will be named at compile time. The same label() is returned each time anon_label is called so that expressions can reference anon_label multiple times, producing the same label name at compile time.
the compiler uses this function automatically at compile time for expressions that are known to be ‘unnamed’ like binary expressions and function calls.
Produce a asc() clause against the parent object.
Produce a between() clause against the parent object, given the lower and upper range.
Produce a collate() clause against the parent object, given the collation string.
Compare this ColumnElement to another.
Special arguments understood:
Parameters: |
|
---|
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.
Parameters: |
|
---|
Implement the ‘concat’ operator.
In a column context, produces the clause a || b, or uses the concat() operator on MySQL.
Implement the ‘contains’ operator.
In a column context, produces the clause LIKE '%<other>%'
Produce a desc() clause against the parent object.
Produce a distinct() clause against the parent object.
Implement the ‘endswith’ operator.
In a column context, produces the clause LIKE '%<other>'
Return a column expression.
Part of the inspection interface; returns self.
Return immediate child elements of this ClauseElement.
This is used for visit traversal.
**kwargs may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level).
Implement the ilike operator.
In a column context, produces the clause a ILIKE other.
E.g.:
select([sometable]).where(sometable.c.column.ilike("%foobar%"))
Parameters: |
---|
See also
Implement the in operator.
In a column context, produces the clause a IN other. “other” may be a tuple/list of column expressions, or a select() construct.
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.
New in version 0.7.9.
See also
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.
New in version 0.7.9.
See also
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.
Implement the like operator.
In a column context, produces the clause a LIKE other.
E.g.:
select([sometable]).where(sometable.c.column.like("%foobar%"))
Parameters: |
---|
See also
Implements a database-specific ‘match’ operator.
match() attempts to resolve to a MATCH-like function or operator provided by the backend. Examples include:
implement the NOT ILIKE operator.
This is equivalent to using negation with ColumnOperators.ilike(), i.e. ~x.ilike(y).
New in version 0.8.
See also
implement the NOT IN operator.
This is equivalent to using negation with ColumnOperators.in_(), i.e. ~x.in_(y).
New in version 0.8.
See also
implement the NOT LIKE operator.
This is equivalent to using negation with ColumnOperators.like(), i.e. ~x.like(y).
New in version 0.8.
See also
Produce a nullsfirst() clause against the parent object.
Produce a nullslast() clause against the parent object.
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.
Parameters: |
|
---|
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}
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.
Return True if the given ColumnElement has a common ancestor to this ColumnElement.
Implement the startwith operator.
In a column context, produces the clause LIKE '<other>%'
Return a copy with bindparam() elements replaced.
Same functionality as params(), except adds unique=True to affected bind parameters so that multiple statements can be used.
Bases: sqlalchemy.sql.operators.Operators
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.
See also:
Redefining and Creating New Operators
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().
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)
x.__delattr__(‘name’) <==> del x.name
Implement the / operator.
In a column context, produces the clause a / b.
Implement the == operator.
In a column context, produces the clause a = b. If the target is None, produces a IS NULL.
default object formatter
Implement the >= operator.
In a column context, produces the clause a >= b.
x.__getattribute__(‘name’) <==> x.name
Implement the [] operator.
This can be used by some database-specific types such as Postgresql ARRAY and HSTORE.
Implement the > operator.
In a column context, produces the clause a > b.
x.__hash__() <==> hash(x)
x.__init__(...) initializes x; see help(type(x)) for signature
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)
Implement the <= operator.
In a column context, produces the clause a <= b.
implement the << operator.
Not used by SQLAlchemy core, this is provided for custom operator systems which want to use << as an extension point.
Implement the < operator.
In a column context, produces the clause a < b.
Implement the % operator.
In a column context, produces the clause a % b.
Implement the * operator.
In a column context, produces the clause a * b.
Implement the != operator.
In a column context, produces the clause a != b. If the target is None, produces a IS NOT NULL.
Implement the - operator.
In a column context, produces the clause -a.
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)
Implement the + operator in reverse.
Implement the / operator in reverse.
helper for pickle
helper for pickle
x.__repr__() <==> repr(x)
Implement the * operator in reverse.
implement the >> operator.
Not used by SQLAlchemy core, this is provided for custom operator systems which want to use >> as an extension point.
Implement the - operator in reverse.
Implement the // operator in reverse.
x.__setattr__(‘name’, value) <==> x.name = value
size of object in memory, in bytes
x.__str__() <==> str(x)
Implement the - operator.
In a column context, produces the clause a - b.
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
Implement the // operator.
In a column context, produces the clause a / b.
list of weak references to the object (if defined)
Produce a between() clause against the parent object, given the lower and upper range.
Produce a collate() clause against the parent object, given the collation string.
Implement the ‘concat’ operator.
In a column context, produces the clause a || b, or uses the concat() operator on MySQL.
Implement the ‘contains’ operator.
In a column context, produces the clause LIKE '%<other>%'
Produce a distinct() clause against the parent object.
Implement the ‘endswith’ operator.
In a column context, produces the clause LIKE '%<other>'
Implement the ilike operator.
In a column context, produces the clause a ILIKE other.
E.g.:
select([sometable]).where(sometable.c.column.ilike("%foobar%"))
Parameters: |
---|
See also
Implement the in operator.
In a column context, produces the clause a IN other. “other” may be a tuple/list of column expressions, or a select() construct.
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.
New in version 0.7.9.
See also
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.
New in version 0.7.9.
See also
Implement the like operator.
In a column context, produces the clause a LIKE other.
E.g.:
select([sometable]).where(sometable.c.column.like("%foobar%"))
Parameters: |
---|
See also
Implements a database-specific ‘match’ operator.
match() attempts to resolve to a MATCH-like function or operator provided by the backend. Examples include:
implement the NOT ILIKE operator.
This is equivalent to using negation with ColumnOperators.ilike(), i.e. ~x.ilike(y).
New in version 0.8.
See also
implement the NOT IN operator.
This is equivalent to using negation with ColumnOperators.in_(), i.e. ~x.in_(y).
New in version 0.8.
See also
implement the NOT LIKE operator.
This is equivalent to using negation with ColumnOperators.like(), i.e. ~x.like(y).
New in version 0.8.
See also
Produce a nullsfirst() clause against the parent object.
Produce a nullslast() clause against the parent object.
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.
Parameters: |
|
---|
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))
Parameters: |
---|
Reverse operate on an argument.
Usage is the same as operate().
Implement the startwith operator.
In a column context, produces the clause LIKE '<other>%'
Hack, allows datetime objects to be compared on the LHS.
Bases: sqlalchemy.sql.expression.ColumnElement
Represent the false keyword in a SQL statement.
Public constructor is the false() function.
Bases: sqlalchemy.sql.expression.ColumnElement
Represents a column label (AS).
Represent a label, as typically applied to any column-level element using the AS sql keyword.
This object is constructed from the label() module level function as well as the label() method available on all ColumnElement subclasses.
Bases: sqlalchemy.sql.expression.ColumnElement
Represent the NULL keyword in a SQL statement.
Public constructor is the null() function.
Bases: sqlalchemy.sql.expression.ColumnElement
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. It’s supported only by certain database backends.
Bases: sqlalchemy.sql.expression.Executable, sqlalchemy.sql.expression.ClauseElement
Represent a literal SQL text fragment.
Public constructor is the text() function.
Bases: sqlalchemy.sql.expression.ClauseList, sqlalchemy.sql.expression.ColumnElement
Represent a SQL tuple.
Return a Tuple.
Main usage is to produce a composite IN construct:
from sqlalchemy import tuple_
tuple_(table.c.col1, table.c.col2).in_(
[(1, 2), (5, 12), (10, 19)]
)
Warning
The composite IN construct is not supported by all backends, and is currently known to work on Postgresql and MySQL, but not SQLite. Unsupported backends will raise a subclass of DBAPIError when such an expression is invoked.
Bases: sqlalchemy.sql.expression.ColumnElement
Represent the true keyword in a SQL statement.
Public constructor is the true() function.
Represent a ‘custom’ operator.
custom_op is normally instantitated when the ColumnOperators.op() method is 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)
Base of comparison and logical operators.
Implements base methods operate() and reverse_operate(), as well as __and__(), __or__(), __invert__().
Usually is used via its most common subclass ColumnOperators.
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)
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)
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)
list of weak references to the object (if defined)
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.
Parameters: |
|
---|
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))
Parameters: |
---|
Reverse operate on an argument.
Usage is the same as operate().
Bases: sqlalchemy.sql.expression.ColumnElement
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.
Compare this UnaryExpression against the given ClauseElement.