The expression package uses functions to construct SQL expressions. The return value of each function is an object instance which is a subclass of ClauseElement.
Return an Alias object.
An Alias represents any FromClause with an alternate name assigned within SQL, typically using the AS clause when generated, e.g. SELECT * FROM table AS aliasname.
Similar functionality is available via the alias() method available on all FromClause subclasses.
- selectable
- any FromClause subclass, such as a table, select statement, etc..
- alias
- string name to be assigned as the alias. If None, a random name will be generated.
Join a list of clauses together using the AND operator.
The & operator is also overloaded on all _CompareMixin subclasses to produce the same result.
Return an ascending ORDER BY clause element.
e.g.:
order_by = [asc(table1.mycol)]
Return a BETWEEN predicate clause.
Equivalent of SQL clausetest BETWEEN clauseleft AND clauseright.
The between() method on all _CompareMixin subclasses provides similar functionality.
Create a bind parameter clause with the given key.
Produce a CASE statement.
The expressions used for THEN and ELSE, when specified as strings, will be interpreted as bound values. To specify textual SQL expressions for these, use the literal_column(<string>) or text(<string>) construct.
The expressions used for the WHEN criterion may only be literal strings when “value” is present, i.e. CASE table.somecol WHEN “x” THEN “y”. Otherwise, literal strings are not accepted in this position, and either the text(<string>) or literal(<string>) constructs must be used to interpret raw string values.
Usage examples:
case([(orderline.c.qty > 100, item.c.specialprice),
(orderline.c.qty > 10, item.c.bulkprice)
], else_=item.c.regularprice)
case(value=emp.c.type, whens={
'engineer': emp.c.salary * 1.1,
'manager': emp.c.salary * 3,
})
Using literal_column(), to allow for databases that do not support bind parameters in the then clause. The type can be specified which determines the type of the case() construct overall:
case([(orderline.c.qty > 100, literal_column("'greaterthan100'", String)),
(orderline.c.qty > 10, literal_column("'greaterthan10'", String))
], else_=literal_column("'lethan10'", String))
Return a CAST function.
Equivalent of SQL CAST(clause AS totype).
Use with a TypeEngine subclass, i.e:
cast(table.c.unit_price * table.c.qty, Numeric(10,4))
or:
cast(table.c.timestamp, DATE)
Return a textual column clause, as would be in the columns clause of a SELECT statement.
The object returned is an instance of ColumnClause, which represents the “syntactical” portion of the schema-level Column object.
Return a Delete clause element.
Similar functionality is available via the delete() method on Table.
Parameters: |
|
---|
Return a descending ORDER BY clause element.
e.g.:
order_by = [desc(table1.mycol)]
Return an EXCEPT of multiple selectables.
The returned object is an instance of CompoundSelect.
Return an EXCEPT ALL of multiple selectables.
The returned object is an instance of CompoundSelect.
Return an EXISTS clause as applied to a Select object.
Calling styles are of the following forms:
# use on an existing select()
s = select([table.c.col1]).where(table.c.col2==5)
s = exists(s)
# construct a select() at once
exists(['*'], **select_arguments).where(criterion)
# columns argument is optional, generates "EXISTS (SELECT *)"
# by default.
exists().where(table.c.col2==5)
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)
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)
Functions which are interpreted as “generic” functions know how to calculate their return type automatically. For a listing of known generic functions, see Generic Functions.
Return an Insert clause element.
Similar functionality is available via the insert() method on Table.
Parameters: |
|
---|
If both values and compile-time bind parameters are present, the compile-time bind parameters override the information specified within values on a per-key basis.
The keys within values can be either Column objects or their string identifiers. Each key may reference one of:
If a SELECT statement is specified which references this INSERT statement’s table, the statement will be correlated against the INSERT statement.
Return an INTERSECT of multiple selectables.
The returned object is an instance of CompoundSelect.
Return an INTERSECT ALL of multiple selectables.
The returned object is an instance of CompoundSelect.
Return a JOIN clause element (regular inner join).
The returned object is an instance of Join.
Similar functionality is also available via the join() method on any FromClause.
To chain joins together, use the join() or outerjoin() methods on the resulting Join object.
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 _CompareMixin subclass, such as a Column object. Use this function to force the generation of a literal clause, which will be created as a _BindParamClause 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).
Return a negation of the given clause, i.e. NOT(clause).
The ~ operator is also overloaded on all _CompareMixin subclasses to produce the same result.
Join a list of clauses together using the OR operator.
The | operator is also overloaded on all _CompareMixin subclasses to produce the same result.
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.
Return an OUTER JOIN clause element.
The returned object is an instance of Join.
Similar functionality is also available via the outerjoin() method on any FromClause.
To chain joins together, use the join() or outerjoin() methods on the resulting Join object.
Returns a SELECT clause element.
Similar functionality is also available via the select() method on any FromClause.
The returned object is an instance of Select.
All arguments which accept ClauseElement arguments also accept string arguments, which will be converted as appropriate into either text() or literal_column() constructs.
A list of ClauseElement objects, typically ColumnElement objects or subclasses, which will form the columns clause of the resulting statement. For all members which are instances of Selectable, the individual ColumnElement members of the Selectable will be added individually to the columns clause. For example, specifying a Table instance will result in all the contained Column objects within to be added to the columns clause.
This argument is not present on the form of select() available on Table.
Additional parameters include:
Return an Alias object derived from a Select.
*args, **kwargs
all other arguments are delivered to the select() function.
Return a TableClause object.
This is a primitive version of the Table object, which is a subclass of this object.
Create literal text to be inserted into a query.
When constructing a query from a select(), update(), insert() or delete(), using plain strings for argument values will usually result in text objects being created automatically. Use this function when creating textual clauses outside of other ClauseElement objects, or optionally wherever plain text is to be used.
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)]
)
Return a UNION of multiple selectables.
The returned object is an instance of CompoundSelect.
A similar union() method is available on all FromClause subclasses.
Return a UNION ALL of multiple selectables.
The returned object is an instance of CompoundSelect.
A similar union_all() method is available on all FromClause subclasses.
Return an Update clause element.
Similar functionality is available via the update() method on Table.
Parameters: |
|
---|
If both values and compile-time bind parameters are present, the compile-time bind parameters override the information specified within values on a per-key basis.
The keys within values can be either Column objects or their string identifiers. Each key may reference one of:
If a SELECT statement is specified which references this UPDATE statement’s table, the statement will be correlated against the UPDATE statement.
Bases: sqlalchemy.sql.expression.FromClause
Represents an table or selectable alias (AS).
Represents an alias, as typically applied to any table or sub-select within a SQL statement using the AS keyword (or without the keyword on certain databases such as Oracle).
This object is constructed from the alias() module level function as well as the alias() method available on all FromClause subclasses.
Bases: sqlalchemy.sql.expression.ColumnElement
Represent a bind parameter.
Public constructor is the bindparam() function.
Construct a _BindParamClause.
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() elments 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}
Return a copy with bindparam() elments replaced.
Same functionality as params(), except adds unique=True to affected bind parameters so that multiple statements can be used.
Bases: sqlalchemy.sql.expression._Immutable, sqlalchemy.sql.expression.ColumnElement
Represents a generic column expression from any textual string.
This includes columns associated with tables, aliases and select statements, but also any arbitrary text. May or may not be bound to an underlying Selectable. ColumnClause is usually created publically via the column() function or the literal_column() function.
Bases: sqlalchemy.util.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.expression._CompareMixin
Represent an element that is usable within the “column clause” portion of a SELECT statement.
This includes columns associated with tables, aliases, and subqueries, expressions, function calls, SQL keywords such as NULL, literals, etc. ColumnElement is the ultimate base class for all such elements.
ColumnElement supports the ability to be a proxy element, which indicates that the ColumnElement may be associated with a Selectable which was derived from another Selectable. An example of a “derived” Selectable is an Alias of a Table.
A ColumnElement, by subclassing the _CompareMixin mixin class, provides the ability to generate new ClauseElement objects using Python expressions. See the _CompareMixin docstring for more details.
Compare this ColumnElement to another.
Special arguments understood:
Parameters: |
|
---|
Bases: sqlalchemy.sql.expression.ColumnOperators
Defines comparison and math operations for ClauseElement instances.
Produce a column label, i.e. <columnname> AS <name>.
if ‘name’ is None, an anonymous label name will be generated.
Produce a MATCH clause, i.e. MATCH '<other>'
The allowed contents of other are database backend specific.
produce a generic operator function.
e.g.:
somecolumn.op("*")(5)
produces:
somecolumn * 5
Parameter: | operator – a string which will be output as the infix operator between this ClauseElement and the expression passed to the generated function. |
---|
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.
Defines comparison and math operations.
Bases: sqlalchemy.sql.expression._SelectBaseMixin, sqlalchemy.sql.expression.FromClause
Forms the basis of UNION, UNION ALL, and other SELECT-based set operations.
Bases: sqlalchemy.sql.expression._UpdateBase
Represent a DELETE construct.
The Delete object is created using the delete() function.
Bases: sqlalchemy.sql.expression._Generative
Mark a ClauseElement as supporting execution.
Executable is a superclass for all “statement” types of objects, including select(), delete(), update(), insert(), text().
Set non-SQL options for the statement which take effect during execution.
Current options include:
autocommit - when True, a COMMIT will be invoked after execution when executed in ‘autocommit’ mode, i.e. when an explicit transaction is not begun on the connection. Note that DBAPI connections by default are always in a transaction - SQLAlchemy uses rules applied to different kinds of statements to determine if COMMIT will be invoked in order to provide its “autocommit” feature. Typically, all INSERT/UPDATE/DELETE statements as well as CREATE/DROP statements have autocommit behavior enabled; SELECT constructs do not. Use this option when invokving a SELECT or other specific SQL construct where COMMIT is desired (typically when calling stored procedures and such).
stream_results - indicate to the dialect that results should be “streamed” and not pre-buffered, if possible. This is a limitation of many DBAPIs. The flag is currently understood only by the psycopg2 dialect.
compiled_cache - a dictionary where Compiled objects will be cached when the Connection compiles a clause expression into a dialect- and parameter-specific Compiled object. It is the user’s responsibility to manage the size of this dictionary, which will have keys corresponding to the dialect, clause element, the column names within the VALUES or SET clause of an INSERT or UPDATE, as well as the “batch” mode for an INSERT or UPDATE statement. The format of this dictionary is not guaranteed to stay the same in future releases.
This option is usually more appropriate to use via the sqlalchemy.engine.base.Connection.execution_options() method of Connection, rather than upon individual statement objects, though the effect is the same.
See also:
Bases: sqlalchemy.sql.expression.Executable, sqlalchemy.sql.expression.ColumnElement, sqlalchemy.sql.expression.FromClause
Base for SQL function-oriented constructs.
Bases: sqlalchemy.sql.expression.FunctionElement
Describe a named SQL function.
Bases: sqlalchemy.sql.expression.Selectable
Represent an element that can be used within the FROM clause of a SELECT statement.
return an alias of this FromClause.
For table objects, this has the effect of the table being rendered as tablename AS aliasname in a SELECT statement. For select objects, the effect is that of creating a named subquery, i.e. (select ...) AS aliasname. The alias() method is the general way to create a “subquery” out of an existing SELECT.
The name parameter is optional, and if left blank an “anonymous” name will be generated at compile time, guaranteed to be unique against other anonymous constructs used in the same statement.
Given a ColumnElement, return the exported ColumnElement object from this Selectable which corresponds to that original Column via a common anscestor column.
Parameters: |
|
---|
a brief description of this FromClause.
Used primarily for error message formatting.
Return True if this FromClause is ‘derived’ from the given FromClause.
An example would be an Alias of a Table is derived from that Table.
Bases: sqlalchemy.sql.expression._ValuesBase
Represent an INSERT construct.
The Insert object is created using the insert() function.
Add a word or expression between INSERT and INTO. Generative.
If multiple prefixes are supplied, they will be separated with spaces.
specify the VALUES clause for an INSERT statement, or the SET clause for an UPDATE.
- **kwargs
- key=<somevalue> arguments
- *args
- A single dictionary can be sent as the first positional argument. This allows non-string based keys, such as Column objects, to be used.
Bases: sqlalchemy.sql.expression.FromClause
represent a JOIN construct between two FromClause elements.
The public constructor function for Join is the module-level join() function, as well as the join() method available off all FromClause subclasses.
Create a Select out of this Join clause and return an Alias of it.
The Select is not correlating.
Create a Select from this Join.
Parameters: |
|
---|
Bases: sqlalchemy.sql.expression._SelectBaseMixin, sqlalchemy.sql.expression.FromClause
Represents a SELECT statement.
Select statements support appendable clauses, as well as the ability to execute themselves and return a result set.
Construct a Select object.
The public constructor for Select is the select() function; see that function for argument descriptions.
Additional generative and mutator methods are available on the _SelectBaseMixin superclass.
append the given expression to this select() construct’s HAVING criterion.
The expression will be joined to existing HAVING criterion via AND.
append the given expression to this select() construct’s WHERE criterion.
The expression will be joined to existing WHERE criterion via AND.
return a new select() construct which will correlate the given FROM clauses to that of an enclosing select(), if a match is found.
By “match”, the given fromclause must be present in this select’s list of FROM objects and also present in an enclosing select’s list of FROM objects.
Calling this method turns off the select’s default behavior of “auto-correlation”. Normally, select() auto-correlates all of its FROM clauses to those of an embedded select when compiled.
If the fromclause is None, correlation is disabled for the returned select().
return a ‘grouping’ construct as per the ClauseElement specification.
This produces an element that can be embedded in an expression. Note that this method is called automatically as needed when constructing expressions.
Add an indexing hint for the given selectable to this Select.
The text of the hint is written specific to a specific backend, and typically uses Python string substitution syntax to render the name of the table or alias, such as for Oracle:
select([mytable]).with_hint(mytable, "+ index(%(name)s ix_mytable)")
Would render SQL as:
select /*+ index(mytable ix_mytable) */ ... from mytable
The dialect_name option will limit the rendering of a particular hint to a particular backend. Such as, to add hints for both Oracle and Sybase simultaneously:
select([mytable]). with_hint(mytable, "+ index(%(name)s ix_mytable)", 'oracle'). with_hint(mytable, "WITH INDEX ix_mytable", 'sybase')
Bases: sqlalchemy.sql.expression.ClauseElement
mark a class as being selectable
Bases: sqlalchemy.sql.expression.Executable
Base class for Select and CompoundSelects.
Append the given GROUP BY criterion applied to this selectable.
The criterion will be appended to any pre-existing GROUP BY criterion.
Append the given ORDER BY criterion applied to this selectable.
The criterion will be appended to any pre-existing ORDER BY criterion.
return a new selectable with the ‘use_labels’ flag set to True.
This will result in column expressions being generated using labels against their table name, such as “SELECT somecolumn AS tablename_somecolumn”. This allows selectables which contain multiple FROM clauses to produce a unique set of column names regardless of name conflicts among the individual FROM clauses.
return a ‘scalar’ representation of this selectable, which can be used as a column expression.
Typically, a select statement which has only one column in its columns clause is eligible to be used as a scalar expression.
The returned object is an instance of _ScalarSelect.
return a new selectable with the ‘autocommit’ flag set to True.
autocommit() is deprecated. Use .execution_options(autocommit=True)
return a new selectable with the given list of GROUP BY criterion applied.
The criterion will be appended to any pre-existing GROUP BY criterion.
return a ‘scalar’ representation of this selectable, embedded as a subquery with a label.
See also as_scalar().
return a new selectable with the given list of ORDER BY criterion applied.
The criterion will be appended to any pre-existing ORDER BY criterion.
Bases: sqlalchemy.sql.expression._Immutable, sqlalchemy.sql.expression.FromClause
Represents a “table” construct.
Note that this represents tables only as another syntactical construct within SQL expressions; it does not provide schema-level functionality.
Bases: sqlalchemy.sql.expression._ValuesBase
Represent an Update construct.
The Update object is created using the update() function.
specify the VALUES clause for an INSERT statement, or the SET clause for an UPDATE.
- **kwargs
- key=<somevalue> arguments
- *args
- A single dictionary can be sent as the first positional argument. This allows non-string based keys, such as Column objects, to be used.
SQL functions which are known to SQLAlchemy with regards to database-specific rendering, return types and argument behavior. Generic functions are invoked like all SQL functions, using the func attribute:
select([func.count()]).select_from(sometable)
Bases: sqlalchemy.sql.functions.GenericFunction
Bases: sqlalchemy.sql.expression.Function
Bases: sqlalchemy.sql.functions.GenericFunction
Define a function whose return type is the same as its arguments.
Bases: sqlalchemy.sql.functions.GenericFunction
Bases: sqlalchemy.sql.functions.GenericFunction
Bases: sqlalchemy.sql.functions.GenericFunction
The ANSI COUNT aggregate function. With no arguments, emits COUNT *.
Bases: sqlalchemy.sql.functions.GenericFunction