# SQLAlchemy 0.4 Documentation

Multiple Pages | One Page
Version: 0.4.6 Last Updated: 05/14/08 14:36:43

### module sqlalchemy.sql.expression

Defines the base components of SQL expression trees.

All components are derived from a common base class ClauseElement. Common behaviors are organized based on class hierarchies, in some cases via mixins.

All object construction from this package occurs via functions which in some cases will construct composite `ClauseElement` structures together, and in other cases simply return a single `ClauseElement` constructed directly. The function interface affords a more "DSL-ish" feel to constructing SQL expressions and also allows future class reorganizations.

Even though classes are not constructed directly from the outside, most classes which have additional public methods are considered to be public (i.e. have no leading underscore). Other classes which are "semi-public" are marked with a single leading underscore; these classes usually have few or no public methods and are less guaranteed to stay the same in future releases.

### Module Functions

def alias(selectable, alias=None)

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.

def and_(*clauses)

Join a list of clauses together using the `AND` operator.

The `&` operator is also overloaded on all _CompareMixin subclasses to produce the same result.

def asc(column)

Return an ascending `ORDER BY` clause element.

e.g.:

    order_by = [asc(table1.mycol)]

def between(ctest, cleft, cright)

Return a `BETWEEN` predicate clause.

Equivalent of SQL `clausetest BETWEEN clauseleft AND clauseright`.

The `between()` method on all _CompareMixin subclasses provides similar functionality.

def bindparam(key, value=None, shortname=None, type_=None, unique=False)

Create a bind parameter clause with the given key.

value
  a default value for this bind parameter. a bindparam with a value is called a `value-based bindparam`.
type_
  a sqlalchemy.types.TypeEngine object indicating the type of this bind param, will invoke type-specific bind parameter processing
shortname
  deprecated.
unique
  if True, bind params sharing the same name will have their underlying `key` modified to a uniquely generated name. mostly useful with value-based bind params.

def case(whens, value=None, else_=None)

Produce a `CASE` statement.

whens
  A sequence of pairs, or alternatively a dict, to be translated into "WHEN / THEN" clauses.
value
  Optional for simple case statements, produces a column expression as in "CASE <expr> WHEN ..."
else_
  Optional as well, for case defaults produces the "ELSE" portion of the "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 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,
        })

def cast(clause, totype, **kwargs)

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)

def collate(expression, collation)

Return the clause `expression COLLATE collation`.

def column(text, type_=None)

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.

text
  the name of the column. Quoting rules will be applied to the clause like any other column name. For textual column constructs that are not to be quoted, use the literal_column() function.
type_
  an optional TypeEngine object which will provide result-set translation for this column.

def delete(table, whereclause=None, **kwargs)

Return a Delete clause element.

Similar functionality is available via the `delete()` method on Table.

table
  The table to be updated.
whereclause
  A `ClauseElement` describing the `WHERE` condition of the `UPDATE` statement.

def desc(column)

Return a descending `ORDER BY` clause element.

e.g.:

    order_by = [desc(table1.mycol)]

def distinct(expr)

Return a `DISTINCT` clause.

def except_(*selects, **kwargs)

Return an `EXCEPT` of multiple selectables.

The returned object is an instance of CompoundSelect.

*selects
  a list of Select instances.
**kwargs
  available keyword arguments are the same as those of select().

def except_all(*selects, **kwargs)

Return an `EXCEPT ALL` of multiple selectables.

The returned object is an instance of CompoundSelect.

*selects
  a list of Select instances.
**kwargs
  available keyword arguments are the same as those of select().

def exists(*args, **kwargs)

Return an `EXISTS` clause as applied to a Select object.

The resulting _Exists object can be executed by itself or used as a subquery within an enclosing select.

*args, **kwargs
  all arguments are sent directly to the select() function to produce a `SELECT` statement.

def extract(field, expr)

Return the clause `extract(field FROM expr)`.

def insert(table, values=None, inline=False, **kwargs)

Return an Insert clause element.

Similar functionality is available via the `insert()` method on Table.

table
  The table to be inserted into.
values
  A dictionary which specifies the column specifications of the `INSERT`, and is optional. If left as None, the column specifications are determined from the bind parameters used during the compile phase of the `INSERT` statement. If the bind parameters also are None during the compile phase, then the column specifications will be generated from the full list of table columns.
prefixes
  A list of modifier keywords to be inserted between INSERT and INTO, see `Insert.prefix_with`.
inline
  if True, SQL defaults will be compiled 'inline' into the statement and not pre-executed.

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:

- a literal data value (i.e. string, number, etc.);
- a Column object;
- a SELECT statement.

If a `SELECT` statement is specified which references this `INSERT` statement's table, the statement will be correlated against the `INSERT` statement.

def intersect(*selects, **kwargs)

Return an `INTERSECT` of multiple selectables.

The returned object is an instance of CompoundSelect.

*selects
  a list of Select instances.
**kwargs
  available keyword arguments are the same as those of select().

def intersect_all(*selects, **kwargs)

Return an `INTERSECT ALL` of multiple selectables.

The returned object is an instance of CompoundSelect.

*selects
  a list of Select instances.
**kwargs
  available keyword arguments are the same as those of select().

def is_column(col)

True if `col` is an instance of `ColumnElement`.

def join(left, right, onclause=None, isouter=False)

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.

left
  The left side of the join.
right
  The right side of the join.
onclause
  Optional criterion for the `ON` clause, is derived from foreign key relationships established between left and right otherwise.

To chain joins together, use the `join()` or `outerjoin()` methods on the resulting `Join` object.

def label(name, obj)

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`.

name
  label name
obj
  a `ColumnElement`.

def literal(value, type_=None)

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.

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.

def literal_column(text, type_=None)

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).

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.

def not_(clause)

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.

def null()

Return a `_Null` object, which compiles to `NULL` in a sql statement.

def or_(*clauses)

Join a list of clauses together using the `OR` operator.

The `|` operator is also overloaded on all _CompareMixin subclasses to produce the same result.

def outerjoin(left, right, onclause=None)

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.

left
  The left side of the join.
right
  The right side of the join.
onclause
  Optional criterion for the `ON` clause, is derived from foreign key relationships established between left and right otherwise.

To chain joins together, use the `join()` or `outerjoin()` methods on the resulting `Join` object.

def outparam(key, type_=None)

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.

def select(columns=None, whereclause=None, from_obj=[], **kwargs)

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.

columns

  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`.

whereclause
  A `ClauseElement` expression which will be used to form the `WHERE` clause.
from_obj
  A list of `ClauseElement` objects which will be added to the `FROM` clause of the resulting statement. Note that "from" objects are automatically located within the columns and whereclause ClauseElements. Use this parameter to explicitly specify "from" objects which are not automatically locatable. This could include `Table` objects that aren't otherwise present, or `Join` objects whose presence will supercede that of the `Table` objects already located in the other clauses.
**kwargs

  Additional parameters include:

  autocommit
    indicates this SELECT statement modifies the database, and should be subject to autocommit behavior if no transaction has been started.
  prefixes
    a list of strings or `ClauseElement` objects to include directly after the SELECT keyword in the generated statement, for dialect-specific query features.
  distinct=False
    when `True`, applies a `DISTINCT` qualifier to the columns clause of the resulting statement.
  use_labels=False
    when `True`, the statement will be generated using labels for each column in the columns clause, which qualify each column with its parent table's (or aliases) name so that name conflicts between columns in different tables don't occur. The format of the label is <tablename>_<column>. The "c" collection of the resulting `Select` object will use these names as well for targeting column members.
  for_update=False
    when `True`, applies `FOR UPDATE` to the end of the resulting statement. Certain database dialects also support alternate values for this parameter, for example mysql supports "read" which translates to `LOCK IN SHARE MODE`, and oracle supports "nowait" which translates to `FOR UPDATE NOWAIT`.
  correlate=True
    indicates that this `Select` object should have its contained `FromClause` elements "correlated" to an enclosing `Select` object. This means that any `ClauseElement` instance within the "froms" collection of this `Select` which is also present in the "froms" collection of an enclosing select will not be rendered in the `FROM` clause of this select statement.
  group_by
    a list of `ClauseElement` objects which will comprise the `GROUP BY` clause of the resulting select.
  having
    a `ClauseElement` that will comprise the `HAVING` clause of the resulting select when `GROUP BY` is used.
  order_by
    a scalar or list of `ClauseElement` objects which will comprise the `ORDER BY` clause of the resulting select.
  limit=None
    a numerical value which usually compiles to a `LIMIT` expression in the resulting select. Databases that don't support `LIMIT` will attempt to provide similar functionality.
  offset=None
    a numeric value which usually compiles to an `OFFSET` expression in the resulting select. Databases that don't support `OFFSET` will attempt to provide similar functionality.
  bind=None
    an `Engine` or `Connection` instance to which the resulting `Select ` object will be bound. The ``Select` object will otherwise automatically bind to whatever `Connectable` instances can be located within its contained `ClauseElement` members.
  scalar=False
    deprecated. Use select(...).as_scalar() to create a "scalar column" proxy for an existing Select object.

def subquery(alias, *args, **kwargs)

Return an Alias object derived from a Select.

name
  alias name

*args, **kwargs

> all other arguments are delivered to the select() function.

def table(name, *columns)

Return a Table object.

This is a primitive version of the Table object, which is a subclass of this object.

def text(text, bind=None, *args, **kwargs)

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.

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.
autocommit=True
  indicates this SELECT statement modifies the database, and should be subject to autocommit behavior if no transaction has been started.
bindparams
  a list of `bindparam()` instances which can be used to define the types and/or initial values for the bind parameters within the textual statement; the keynames of the bindparams must match those within the text of the statement. The types will be used for pre-processing on bind values.
typemap
  a dictionary mapping the names of columns represented in the `SELECT` clause of the textual statement to type objects, which will be used to perform post-processing on columns within the result set (for textual statements that produce result sets).

def union(*selects, **kwargs)

Return a `UNION` of multiple selectables.

The returned object is an instance of CompoundSelect.

A similar `union()` method is available on all FromClause subclasses.

*selects
  a list of Select instances.
**kwargs
  available keyword arguments are the same as those of select().

def union_all(*selects, **kwargs)

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.

*selects
  a list of Select instances.
**kwargs
  available keyword arguments are the same as those of select().

def update(table, whereclause=None, values=None, inline=False, **kwargs)

Return an Update clause element.

Similar functionality is available via the `update()` method on Table.

table
  The table to be updated.
whereclause
  A `ClauseElement` describing the `WHERE` condition of the `UPDATE` statement.
values
  A dictionary which specifies the `SET` conditions of the `UPDATE`, and is optional. If left as None, the `SET` conditions are determined from the bind parameters used during the compile phase of the `UPDATE` statement. If the bind parameters also are None during the compile phase, then the `SET` conditions will be generated from the full list of table columns.
inline
  if True, SQL defaults will be compiled 'inline' into the statement and not pre-executed.

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:

- a literal data value (i.e. string, number, etc.);
- a Column object;
- a SELECT statement.

If a `SELECT` statement is specified which references this `UPDATE` statement's table, the statement will be correlated against the `UPDATE` statement.

### class Alias(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.

def __init__(self, selectable, alias=None)

Construct a new `Alias`.

bind = property()
description = property()
def get_children(self, column_collections=True, aliased_selectables=True, **kwargs)
def is_derived_from(self, fromclause)
def supports_execution(self)
back to section top

### class _BinaryExpression(ColumnElement)

Represent an expression that is `LEFT <operator> RIGHT`.

def __init__(self, left, right, operator, type_=None, negate=None, modifiers=None)

Construct a new `_BinaryExpression`.

def compare(self, other)

Compare this `_BinaryExpression` against the given `_BinaryExpression`.

def get_children(self, **kwargs)
def self_group(self, against=None)
back to section top

### class _BindParamClause(ClauseElement,_CompareMixin)

Represent a bind parameter.

Public constructor is the `bindparam()` function.

def __init__(self, key, value, type_=None, unique=False, isoutparam=False, shortname=None)

Construct a _BindParamClause.

key
  the key 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 `_BindParamClause` objects exist with the same key, or if its length is too long and truncation is required.
value
  Initial value for this bind param. This value may be overridden by the dictionary of parameters sent to statement compilation/execution.
shortname
  deprecated.
type_
  A `TypeEngine` object that will be used to pre-process the value corresponding to this `_BindParamClause` at execution time.
unique
  if True, the key name of this BindParamClause will be modified if another `_BindParamClause` of the same name already has been located within the containing `ClauseElement`.
isoutparam
  if True, the parameter should be treated like a stored procedure "OUT" parameter.

def bind_processor(self, dialect)
def compare(self, other)

Compare this `_BindParamClause` to the given clause.

Since `compare()` is meant to compare statement syntax, this method returns True if the two `_BindParamClauses` have just the same type.

back to section top

### class _CalculatedClause(ColumnElement)

Describe a calculated SQL expression that has a type, like `CASE`.

Extends `ColumnElement` to provide column-level comparison operators.

def __init__(self, name, *clauses, **kwargs)

Construct a new `_CalculatedClause`.

clauses = property()
def execute(self)
def get_children(self, **kwargs)
key = property()
def scalar(self)
def select(self)
back to section top

### class _Cast(ColumnElement)

def __init__(self, clause, totype, **kwargs)

Construct a new `_Cast`.

def get_children(self, **kwargs)
back to section top

### class ClauseElement(object)

Base class for elements of a programmatically constructed SQL expression.

bind = property()

Returns the Engine or Connection to which this ClauseElement is bound, or None if none found.

def compare(self, other)

Compare this ClauseElement to the given ClauseElement.

Subclasses should override the default behavior, which is a straight identity comparison.

def compile(self, bind=None, column_keys=None, compiler=None, dialect=None, inline=False)

Compile this SQL expression.

Uses the given `Compiler`, or the given `AbstractDialect` or `Engine` to create a `Compiler`. If no compiler arguments are given, tries to use the underlying `Engine` this `ClauseElement` is bound to to create a `Compiler`, if any.

Finally, if there is no bound `Engine`, uses an `DefaultDialect` to create a default `Compiler`.

parameters is a dictionary representing the default bind parameters to be used with the statement. If parameters is a list, it is assumed to be a list of dictionaries and the first dictionary in the list is used with which to compile against.

The bind parameters can in some cases determine the output of the compilation, such as for `UPDATE` and `INSERT` statements the bind parameters that are present determine the `SET` and `VALUES` clause of those statements.

def execute(self, *multiparams, **params)

Compile and execute this `ClauseElement`.

def get_children(self, **kwargs)

Return immediate child elements of this `ClauseElement`.

This is used for visit traversal.

**kwargs may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level).

def params(self, *optionaldict, **kwargs)

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}

def scalar(self, *multiparams, **params)

Compile and execute this `ClauseElement`, returning the result's scalar representation.

def self_group(self, against=None)
def supports_execution(self)

Return True if this clause element represents a complete executable statement.

def unique_params(self, *optionaldict, **kwargs)

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.

def __and__(self, other)
def __invert__(self)
def __or__(self, other)
back to section top

### class ClauseList(ClauseElement)

Describe a list of clauses, separated by an operator.

By default, is comma-separated, such as a column listing.

def __init__(self, *clauses, **kwargs)

Construct a new `ClauseList`.

def append(self, clause)
def compare(self, other)

Compare this `ClauseList` to the given `ClauseList`, including a comparison of all the clause items.

def get_children(self, **kwargs)
def self_group(self, against=None)
def __iter__(self)
def __len__(self)
back to section top

### class _ColumnClause(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.

text
  the text of the element.
selectable
  parent selectable.
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 is usually used to create such a `_ColumnClause`.

def __init__(self, text, selectable=None, type_=None, _is_oid=False, is_literal=False)

Construct a new `_ColumnClause`.

description = property()
def label(self, name)
back to section top

### class ColumnCollection(OrderedProperties)

An ordered dictionary that stores a list of ColumnElement instances.

Overrides the `__eq__()` method to produce SQL clauses between sets of correlated columns.

def __init__(self, *cols)

Construct a new `ColumnCollection`.

def add(self, column)

Add a column to this collection.

The key attribute of the column will be used as the hash key for this dictionary.

def contains_column(self, col)
def extend(self, iter)
def remove(self, column)
def replace(self, column)

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', Column('col1', Integer))
>     t.replace_unalised(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.

def __contains__(self, other)
def __eq__(self, other)
def __setitem__(self, key, value)
back to section top

### class ColumnElement(ClauseElement,_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.

anon_label = property()

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.

base_columns = property()
proxy_set = property()
def shares_lineage(self, othercolumn)

Return True if the given `ColumnElement` has a common ancestor to this `ColumnElement`.

back to section top

### class _ColumnElementAdapter(ColumnElement)

Adapts a ClauseElement which may or may not be a ColumnElement subclass itself into an object which acts like a ColumnElement.

def __init__(self, elem)

Construct a new `_ColumnElementAdapter`.

def get_children(self, **kwargs)
key = property()
def __getattr__(self, attr)
back to section top

### class ColumnOperators(Operators)

Defines comparison and math operations.

def asc(self)
def between(self, cleft, cright)
def collate(self, collation)
def concat(self, other)
def contains(self, other, **kwargs)
def desc(self)
def distinct(self)
def endswith(self, other, **kwargs)
def ilike(self, other, escape=None)
def in_(self, *other)
def like(self, other, escape=None)
def startswith(self, other, **kwargs)
def __add__(self, other)
def __div__(self, other)
def __eq__(self, other)
def __ge__(self, other)
def __gt__(self, other)
def __le__(self, other)
def __lt__(self, other)
def __mod__(self, other)
def __mul__(self, other)
def __ne__(self, other)
def __radd__(self, other)
def __rdiv__(self, other)
def __rmul__(self, other)
def __rsub__(self, other)
def __sub__(self, other)
def __truediv__(self, other)
back to section top

### class ColumnSet(OrderedSet)

def contains_column(self, col)
def extend(self, cols)
def __add__(self, other)
def __eq__(self, other)
back to section top

### class _CompareMixin(ColumnOperators)

Defines comparison and math operations for `ClauseElement` instances.

def asc(self)

Produce a ASC clause, i.e. `<columnname> ASC`

def between(self, cleft, cright)

Produce a BETWEEN clause, i.e. `<column> BETWEEN <cleft> AND <cright>`

def clause_element(self)

Allow `_CompareMixins` to return the underlying `ClauseElement`, for non-`ClauseElement` `_CompareMixins`.

def collate(self, collation)

Produce a COLLATE clause, i.e. `<column> COLLATE utf8_bin`

def contains(self, other, escape=None)

Produce the clause `LIKE '%<other>%'`

def desc(self)

Produce a DESC clause, i.e. `<columnname> DESC`

def distinct(self)

Produce a DISTINCT clause, i.e. `DISTINCT <columnname>`

def endswith(self, other, escape=None)

Produce the clause `LIKE '%<other>'`

def expression_element(self)

Allow `_CompareMixins` to return the appropriate object to be used in expressions.

def in_(self, *other)
def label(self, name)

Produce a column label, i.e. `<columnname> AS <name>`.

if 'name' is None, an anonymous label name will be generated.

def op(self, operator)

produce a generic operator function.

e.g.:

    somecolumn.op("*")(5)

produces:

    somecolumn * 5

operator
  a string which will be output as the infix operator between this `ClauseElement` and the expression passed to the generated function.

def operate(self, op, *other, **kwargs)
def reverse_operate(self, op, other, **kwargs)
def startswith(self, other, escape=None)

Produce the clause `LIKE '<other>%'`

back to section top

### class CompoundSelect(_SelectBaseMixin,FromClause)

def __init__(self, keyword, *selects, **kwargs)

Construct a new `CompoundSelect`.

bind = property()
def get_children(self, column_collections=True, **kwargs)
def self_group(self, against=None)
back to section top

### class Delete(_UpdateBase)

def __init__(self, table, whereclause, bind=None)

Construct a new `Delete`.

def get_children(self, **kwargs)
def where(self, whereclause)

return a new delete() construct with the given expression added to its WHERE clause, joined to the existing clause via AND, if any.

back to section top

### class _Exists(_UnaryExpression)

def __init__(self, *args, **kwargs)

Construct a new `_Exists`.

def correlate(self, fromclause)
def select(self, whereclause=None, **params)
def where(self, clause)

return a new exists() construct with the given expression added to its WHERE clause, joined to the existing clause via AND, if any.

back to section top

### class _FigureVisitName(type)

def __init__(cls, clsname, bases, dict)

Construct a new `_FigureVisitName`.

back to section top

### class FromClause(Selectable)

Represent an element that can be used within the `FROM` clause of a `SELECT` statement.

def alias(self, name=None)

return an alias of this `FromClause` against another `FromClause`.

c = property()
columns = property()
def correspond_on_equivalents(self, column, equivalents)
def corresponding_column(self, column, require_embedded=False)

Given a `ColumnElement`, return the exported `ColumnElement` object from this `Selectable` which corresponds to that original `Column` via a common anscestor column.

column
  the target `ColumnElement` to be matched
require_embedded
  only return corresponding columns for the given `ColumnElement`, if the given `ColumnElement` is actually present within a sub-element of this `FromClause`. Normally the column will match if it merely shares a common anscestor with one of the exported columns of this `FromClause`.

def count(self, whereclause=None, **params)

return a SELECT COUNT generated against this `FromClause`.

def default_order_by(self)
description = property()

a brief description of this FromClause.

Used primarily for error message formatting.

foreign_keys = property()
def is_derived_from(self, fromclause)

Return True if this FromClause is 'derived' from the given FromClause.

An example would be an Alias of a Table is derived from that Table.

def join(self, right, onclause=None, isouter=False)

return a join of this `FromClause` against another `FromClause`.

oid_column = property()
def outerjoin(self, right, onclause=None)

return an outer join of this `FromClause` against another `FromClause`.

primary_key = property()
def replace_selectable(self, old, alias)

replace all occurences of FromClause 'old' with the given Alias object, returning a copy of this `FromClause`.

def select(self, whereclause=None, **params)

return a SELECT of this `FromClause`.

back to section top

### class _FromGrouping(FromClause)

Represent a grouping of a FROM clause

def __init__(self, elem)

Construct a new `_FromGrouping`.

c = property()
columns = property()
def get_children(self, **kwargs)
def __getattr__(self, attr)
back to section top

### class _Function(_CalculatedClause,FromClause)

Describe a SQL function.

Extends `_CalculatedClause`, turn the clauselist into function arguments, also adds a packagenames argument.

def __init__(self, name, *clauses, **kwargs)

Construct a new `_Function`.

columns = property()
def get_children(self, **kwargs)
key = property()
back to section top

### class _FunctionGenerator(object)

Generate `_Function` objects based on getattr calls.

def __init__(self, **opts)

Construct a new `_FunctionGenerator`.

def __call__(self, *c, **kwargs)
def __getattr__(self, name)
back to section top

### class _Grouping(_ColumnElementAdapter)

Represent a grouping within a column expression

back to section top

### class _IdentifiedClause(ClauseElement)

def __init__(self, ident)

Construct a new `_IdentifiedClause`.

def supports_execution(self)
back to section top

### class Insert(_ValuesBase)

def __init__(self, table, values=None, inline=False, bind=None, prefixes=None, **kwargs)

Construct a new `Insert`.

def get_children(self, **kwargs)
def prefix_with(self, clause)

Add a word or expression between INSERT and INTO. Generative.

If multiple prefixes are supplied, they will be separated with spaces.

back to section top

### class Join(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.

def __init__(self, left, right, onclause=None, isouter=False)

Construct a new `Join`.

def alias(self, name=None)

Create a `Select` out of this `Join` clause and return an `Alias` of it.

The `Select` is not correlating.

bind = property()
description = property()
def get_children(self, **kwargs)
def is_derived_from(self, fromclause)
def select(self, whereclause=None, fold_equivalents=False, **kwargs)

Create a `Select` from this `Join`.

whereclause
  the WHERE criterion that will be sent to the `select()` function
fold_equivalents
  based on the join criterion of this `Join`, do not include repeat column names in the column list of the resulting select, for columns that are calculated to be "equivalent" based on the join criterion of this `Join`. This will recursively apply to any joins directly nested by this one as well.
**kwargs
  all other kwargs are sent to the underlying `select()` function. See the `select()` module level function for details.

def self_group(self, against=None)
back to section top

### class _Label(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.

def __init__(self, name, obj, type_=None)

Construct a new `_Label`.

base_columns = property()
def expression_element(self)
foreign_keys = property()
def get_children(self, **kwargs)
key = property()
primary_key = property()
proxies = property()
proxy_set = property()
back to section top

### class _Null(ColumnElement)

Represent the NULL keyword in a SQL statement.

Public constructor is the `null()` function.

def __init__(self)

Construct a new `_Null`.

back to section top

### class Operators(object)

def clause_element(self)
def op(self, opstring)
def operate(self, op, *other, **kwargs)
def reverse_operate(self, op, other, **kwargs)
def __and__(self, other)
def __invert__(self)
def __or__(self, other)
back to section top

### class ReleaseSavepointClause(_IdentifiedClause)

back to section top

### class RollbackToSavepointClause(_IdentifiedClause)

back to section top

### class SavepointClause(_IdentifiedClause)

back to section top

### class _ScalarSelect(_Grouping)

def __init__(self, elem)

Construct a new `_ScalarSelect`.

c = property()
columns = property()
def self_group(self, **kwargs)
back to section top

### class Select(_SelectBaseMixin,FromClause)

Represents a `SELECT` statement.

Select statements support appendable clauses, as well as the ability to execute themselves and return a result set.

def __init__(self, columns, whereclause=None, from_obj=None, distinct=False, having=None, correlate=True, prefixes=None, **kwargs)

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.

def append_column(self, column)

append the given column expression to the columns clause of this select() construct.

def append_correlation(self, fromclause)

append the given correlation expression to this select() construct.

def append_from(self, fromclause)

append the given FromClause expression to this select() construct's FROM clause.

def append_having(self, having)

append the given expression to this select() construct's HAVING criterion.

The expression will be joined to existing HAVING criterion via AND.

def append_prefix(self, clause)

append the given columns clause prefix expression to this select() construct.

def append_whereclause(self, whereclause)

append the given expression to this select() construct's WHERE criterion.

The expression will be joined to existing WHERE criterion via AND.

bind = property()
def column(self, column)

return a new select() construct with the given column expression added to its columns clause.

def correlate(self, *fromclauses)

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().

def distinct(self)

return a new select() construct which will apply DISTINCT to its columns clause.

def except_(self, other, **kwargs)

return a SQL EXCEPT of this select() construct against the given selectable.

def except_all(self, other, **kwargs)

return a SQL EXCEPT ALL of this select() construct against the given selectable.

froms = property()

Return a list of all FromClause elements which will be applied to the FROM clause of the resulting statement.

def get_children(self, column_collections=True, **kwargs)

return child elements as per the ClauseElement specification.

def having(self, having)

return a new select() construct with the given expression added to its HAVING clause, joined to the existing clause via AND, if any.

inner_columns = property()

an iteratorof all ColumnElement expressions which would be rendered into the columns clause of the resulting SELECT statement.

def intersect(self, other, **kwargs)

return a SQL INTERSECT of this select() construct against the given selectable.

def intersect_all(self, other, **kwargs)

return a SQL INTERSECT ALL of this select() construct against the given selectable.

def is_derived_from(self, fromclause)
def locate_all_froms(self)

return a Set of all FromClause elements referenced by this Select.

This set is a superset of that returned by the `froms` property, which is specifically for those FromClause elements that would actually be rendered.

def prefix_with(self, clause)

return a new select() construct which will apply the given expression to the start of its columns clause, not using any commas.

def select_from(self, fromclause)

return a new select() construct with the given FROM expression applied to its list of FROM objects.

def self_group(self, against=None)

return a 'grouping' construct as per the ClauseElement specification.

This produces an element that can be embedded in an expression. Note that this method is called automatically as needed when constructing expressions.

type = property()
def union(self, other, **kwargs)

return a SQL UNION of this select() construct against the given selectable.

def union_all(self, other, **kwargs)

return a SQL UNION ALL of this select() construct against the given selectable.

def where(self, whereclause)

return a new select() construct with the given expression added to its WHERE clause, joined to the existing clause via AND, if any.

back to section top

### class _SelectBaseMixin(object)

Base class for `Select` and `CompoundSelects`.

def __init__(self, use_labels=False, for_update=False, limit=None, offset=None, order_by=None, group_by=None, bind=None, autocommit=False)

Construct a new `_SelectBaseMixin`.

def append_group_by(self, *clauses)

Append the given GROUP BY criterion applied to this selectable.

The criterion will be appended to any pre-existing GROUP BY criterion.

def append_order_by(self, *clauses)

Append the given ORDER BY criterion applied to this selectable.

The criterion will be appended to any pre-existing ORDER BY criterion.

def apply_labels(self)

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.

def as_scalar(self)

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.

def autocommit(self)

return a new selectable with the 'autocommit' flag set to True.

def group_by(self, *clauses)

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.

def label(self, name)

return a 'scalar' representation of this selectable, embedded as a subquery with a label.

See also `as_scalar()`.

def limit(self, limit)

return a new selectable with the given LIMIT criterion applied.

def offset(self, offset)

return a new selectable with the given OFFSET criterion applied.

def order_by(self, *clauses)

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.

def supports_execution(self)

part of the ClauseElement contract; returns `True` in all cases for this class.

back to section top

### class Selectable(ClauseElement)

mark a class as being selectable

back to section top

### class TableClause(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.

def __init__(self, name, *columns)

Construct a new `TableClause`.

def append_column(self, c)
def count(self, whereclause=None, **params)
def delete(self, whereclause=None)
description = property()
def get_children(self, column_collections=True, **kwargs)
def insert(self, values=None, inline=False, **kwargs)
def update(self, whereclause=None, values=None, inline=False, **kwargs)
back to section top

### class _TextClause(ClauseElement)

Represent a literal SQL text fragment.

Public constructor is the `text()` function.

def __init__(self, text='', bind=None, bindparams=None, typemap=None, autocommit=False)

Construct a new `_TextClause`.

def get_children(self, **kwargs)
def supports_execution(self)
type = property()
back to section top

### class _TypeClause(ClauseElement)

Handle a type keyword in a SQL statement.

Used by the `Case` statement.

def __init__(self, type)

Construct a new `_TypeClause`.

back to section top

### class _UnaryExpression(ColumnElement)

def __init__(self, element, operator=None, modifier=None, type_=None, negate=None)

Construct a new `_UnaryExpression`.

def compare(self, other)

Compare this `_UnaryExpression` against the given `ClauseElement`.

def get_children(self, **kwargs)
def self_group(self, against)
back to section top

### class Update(_ValuesBase)

def __init__(self, table, whereclause, values=None, inline=False, bind=None, **kwargs)

Construct a new `Update`.

def get_children(self, **kwargs)
def where(self, whereclause)

return a new update() construct with the given expression added to its WHERE clause, joined to the existing clause via AND, if any.

back to section top

### class _UpdateBase(ClauseElement)

Form the base for `INSERT`, `UPDATE`, and `DELETE` statements.

bind = property()
def supports_execution(self)
back to section top

### class _ValuesBase(_UpdateBase)

def values(self, *args, **kwargs)

specify the VALUES clause for an INSERT statement, or the SET clause for an UPDATE.

**kwargs
  key=<somevalue> arguments
*args
  deprecated. A single dictionary can be sent as the first positional argument.

back to section top