SQLAlchemy 0.3 Documentation - module sqlalchemy.sql

# SQLAlchemy 0.3 Documentation

Multiple Pages | One Page
Version: 0.3.7 Last Updated: 04/30/07 00:08:52

### module sqlalchemy.sql

Define 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 between_(*args, **kwargs)

synonym for between() (deprecated).

def bindparam(key, value=None, type=None, shortname=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`.
shortname
  an `alias` for this bind parameter. usually used to alias the `key` and `label` of a column, i.e. `somecolname` and `sometable_somecolname`
type
  a sqlalchemy.types.TypeEngine object indicating the type of this bind param, will invoke type-specific bind parameter processing
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 to be translated into "when / then" clauses.
value
  Optional for simple case statements.
else_
  Optional as well, for case defaults.

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 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 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, **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.

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)
def join(left, right, onclause=None, **kwargs)

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 DBAPI, 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 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 not be applied to the column. For textual column constructs that should be quoted like any other column construct, use the column() function.
> type
>   an optional TypeEngine object which will provide result-set translation for this column.

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, **kwargs)

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 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:

>   order_by
>     a scalar or list of `ClauseElement` objects which will comprise the `ORDER BY` clause of the resulting select.
>   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.
>   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.
>   distinct=False
>     when `True`, applies a `DISTINCT` qualifier to the columns clause of the resulting statement.
>   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`.
>   engine=None
>     an `Engine` instance to which the resulting `Select` object will be bound. The `Select` object will otherwise automatically bind to whatever `Engine` instances can be located within its contained `ClauseElement` members.
>   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 numerical value which usually compiles to an `OFFSET` expression in the resulting select. Databases that don't support `OFFSET` will attempt to provide similar functionality.
>   scalar=False
>     when `True`, indicates that the resulting `Select` object is to be used in the "columns" clause of another select statement, where the evaluated value of the column is the scalar result of this statement. Normally, placing any `Selectable` within the columns clause of a `select()` call will expand the member columns of the `Selectable` individually.
>   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.

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, engine=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.
> engine
>   An optional engine to be used for this text query.
> 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, **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.

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 AbstractDialect(object)

Represent the behavior of a particular database.

Used by `Compiled` objects.

back to section top

### class Alias(FromClause)

represent 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)
def accept_visitor(self, visitor)
engine = property()
def get_children(self, **kwargs)
def named_with_column(self)
def supports_execution(self)
back to section top

### class _BinaryClause(ClauseElement)

Represent two clauses with an operator in between.

This class serves as the base class for `_BinaryExpression` and `_BooleanExpression`, both of which add additional semantics to the base `_BinaryClause` construct.

def __init__(self, left, right, operator, type=None)
def accept_visitor(self, visitor)
def compare(self, other)

Compare this `_BinaryClause` against the given `_BinaryClause`.

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

### class _BinaryExpression(_BinaryClause,ColumnElement)

Represent a binary expression, which can be in a `WHERE` criterion or in the column list of a `SELECT`.

This class differs from `_BinaryClause` in that it mixes in `ColumnElement`. The effect is that elements of this type become `Selectable` units which can be placed in the column list of a `select()` construct.

back to section top

### class _BindParamClause(ClauseElement,_CompareMixin)

Represent a bind parameter.

Public constructor is the `bindparam()` function.

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

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
  Defaults to the key, a short name that will also identify this bind parameter, similar to an alias. the bind parameter keys sent to a statement compilation or compiled execution may match either the key or the shortname of the corresponding `_BindParamClause` objects.
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`.

def accept_visitor(self, visitor)
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.

def copy_container(self)
def typeprocess(self, value, dialect)
back to section top

### class _BooleanExpression(_BinaryExpression)

Represent a boolean expression.

`_BooleanExpression` is constructed as the result of compare operations involving `CompareMixin` subclasses, such as when comparing a `ColumnElement` to a scalar value via the `==` operator, `CompareMixin`'s `__eq__()` method produces a `_BooleanExpression` consisting of the `ColumnElement` and a `_BindParamClause`.

def __init__(self, *args, **kwargs)
back to section top

### class _CalculatedClause(ClauseList,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)
def accept_visitor(self, visitor)
def copy_container(self)
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)
def accept_visitor(self, visitor)
def get_children(self, **kwargs)
back to section top

### class ClauseElement(object)

Base class for elements of a programmatically constructed SQL expression.

def accept_visitor(self, visitor)

Accept a `ClauseVisitor` and call the appropriate `visit_xxx` method.

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, engine=None, parameters=None, compiler=None, dialect=None)

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 `ANSIDialect` 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 copy_container(self)

Return a copy of this `ClauseElement`, if this `ClauseElement` contains other `ClauseElements`.

If this `ClauseElement` is not a container, it should return self. This is used to create copies of expression trees that still reference the same leaf nodes. The new structure can then be restructured without affecting the original.

engine = property()

Attempts to locate a Engine within this ClauseElement structure, or returns None if none found.

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 scalar(self, *multiparams, **params)

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

def supports_execution(self)

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

back to section top

### class ClauseList(ClauseElement)

Describe a list of clauses.

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

def __init__(self, *clauses, **kwargs)
def accept_visitor(self, visitor)
def append(self, clause)
def compare(self, other)

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

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

### class ClauseParameters(object)

Represent a dictionary/iterator of bind parameter key names/values.

Tracks the original `BindParam` objects as well as the keys/position of each parameter, and can return parameters as a dictionary or a list. Will process parameter values according to the `TypeEngine` objects present in the `BindParams`.

def __init__(self, dialect, positional=None)
def get_original(self, key)

Return the given parameter as it was originally placed in this `ClauseParameters` object, without any `Type` conversion.

def get_original_dict(self)
def get_processed(self, key)
def get_raw_dict(self)
def get_raw_list(self)
def keys(self)
def set_parameter(self, bindparam, value, name)
def set_value(self, key, value)
back to section top

### class ClauseVisitor(object)

A class that knows how to traverse and visit `ClauseElements`.

Each `ClauseElement`'s accept_visitor() method will call a corresponding visit_XXXX() method here. Traversal of a hierarchy of `ClauseElements` is achieved via the `traverse()` method, which is passed the lead `ClauseElement`.

By default, `ClauseVisitor` traverses all elements fully. Options can be specified at the class level via the `__traverse_options__` dictionary which will be passed to the `get_children()` method of each `ClauseElement`; these options can indicate modifications to the set of elements returned, such as to not return column collections (column_collections=False) or to return Schema-level items (schema_visitor=True).

def traverse(self, obj)
def visit_alias(self, alias)
def visit_binary(self, binary)
def visit_bindparam(self, bindparam)
def visit_calculatedclause(self, calcclause)
def visit_cast(self, cast)
def visit_clauselist(self, list)
def visit_column(self, column)
def visit_compound(self, compound)
def visit_compound_select(self, compound)
def visit_fromclause(self, fromclause)
def visit_function(self, func)
def visit_join(self, join)
def visit_label(self, label)
def visit_null(self, null)
def visit_select(self, select)
def visit_table(self, table)
def visit_textclause(self, textclause)
def visit_typeclause(self, typeclause)
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 `column_literal()` function.

> text
>   the text of the element.
> selectable
>   parent selectable.
> type
>   `TypeEngine` object which can associate this `_ColumnClause` with a type.
> case_sensitive
>   defines whether identifier quoting rules will be applied to the generated text of this `_ColumnClause` so that it is identified in a case-sensitive manner.
> 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 `column_literal()` function is usually used to create such a `_ColumnClause`.

def __init__(self, text, selectable=None, type=None, _is_oid=False, case_sensitive=True, is_literal=False)
def accept_visitor(self, visitor)
is_labeled = 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)
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)
back to section top

### class ColumnElement(Selectable,_CompareMixin)

Represent an element that is useable 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.

columns = property()

Columns accessor which returns `self`, to provide compatibility with `Selectable` objects.

foreign_key = property()
foreign_keys = property()

Foreign key accessor. References a list of `ForeignKey` objects which each represent a foreign key placed on this column's ultimate ancestor.

orig_set = property()

A Set containing TableClause-bound, non-proxied ColumnElements for which this ColumnElement is a proxy. In all cases except for a column proxied from a Union (i.e. CompoundSelect), this set will be just one element.

primary_key = property()

Primary key flag. Indicates if this `Column` represents part or whole of a primary key for its parent table.

def shares_lineage(self, othercolumn)

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

back to section top

### class _CompareMixin(object)

Defines comparison operations for `ClauseElement` instances.

This is a mixin class that adds the capability to produce `ClauseElement` instances based on regular Python operators. These operations are achieved using Python's operator overload methods (i.e. `__eq__()`, `__ne__()`, etc.

Overridden operators include all comparison operators (i.e. '==', '!=', '<'), math operators ('+', '-', '*', etc), the '&' and '|' operators which evaluate to `AND` and `OR` respectively.

Other methods exist to create additional SQL clauses such as `IN`, `LIKE`, `DISTINCT`, etc.

def between(self, cleft, cright)

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

def distinct(self)

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

def endswith(self, other)

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

def in_(self, *other)

produce an `IN` clause.

def label(self, name)

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

def like(self, other)

produce a `LIKE` clause.

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 startswith(self, other)

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

back to section top

### class Compiled(ClauseVisitor)

Represent a compiled SQL expression.

The `__str__` method of the `Compiled` object should produce the actual text of the statement. `Compiled` objects are specific to their underlying database dialect, and also may or may not be specific to the columns referenced within a particular set of bind parameters. In no case should the `Compiled` object be dependent on the actual values of those bind parameters, even though it may reference those values as defaults.

def __init__(self, dialect, statement, parameters, engine=None, traversal=None)

Construct a new Compiled object.

statement
  `ClauseElement` to be compiled.
parameters
  Optional dictionary indicating a set of bind parameters specified with this `Compiled` object. These parameters are the default values corresponding to the `ClauseElement`'s `_BindParamClauses` when the `Compiled` is executed. In the case of an `INSERT` or `UPDATE` statement, these parameters will also result in the creation of new `_BindParamClause` objects for each key and will also affect the generated column list in an `INSERT` statement and the `SET` clauses of an `UPDATE` statement. The keys of the parameter dictionary can either be the string names of columns or `_ColumnClause` objects.
engine
  Optional Engine to compile this statement against.

def compile(self)
def construct_params(self, params)

Return the bind params for this compiled object.

Will start with the default parameters specified when this `Compiled` object was first constructed, and will override those values with those sent via **params, which are key/value pairs. Each key should match one of the `_BindParamClause` objects compiled into this object; either the key or shortname property of the `_BindParamClause`.

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

Execute this compiled object.

def get_params(self, **params)

Deprecated. use construct_params(). (supports unicode names)

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

Execute this compiled object and return the result's scalar value.

back to section top

### class _CompoundClause(ClauseList)

Represent a list of clauses joined by an operator, such as `AND` or `OR`.

Extends `ClauseList` to add the operator as well as a from_objects accessor to help determine `FROM` objects in a `SELECT` statement.

def __init__(self, operator, *clauses, **kwargs)
def accept_visitor(self, visitor)
def append(self, clause)
def compare(self, other)

Compare this `_CompoundClause` to the given item.

In addition to the regular comparison, has the special case that it returns True if this `_CompoundClause` has only one item, and that item matches the given item.

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

### class CompoundSelect(_SelectBaseMixin,FromClause)

def __init__(self, keyword, *selects, **kwargs)
def accept_visitor(self, visitor)
def get_children(self, column_collections=True, **kwargs)
name = property()
back to section top

### class _Delete(_UpdateBase)

def __init__(self, table, whereclause)
def accept_visitor(self, visitor)
def get_children(self, **kwargs)
back to section top

### class Executor(object)

Interface representing a "thing that can produce Compiled objects and execute them".

def compiler(self, statement, parameters, **kwargs)

Return a Compiled object for the given statement and parameters.

def execute_compiled(self, compiled, parameters, echo=None, **kwargs)

Execute a Compiled object.

back to section top

### class _Exists(_BooleanExpression)

def __init__(self, *args, **kwargs)
back to section top

### class FromClause(Selectable)

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

def __init__(self, name=None)
def accept_visitor(self, visitor)
def alias(self, name=None)
c = property()
columns = property()
def corresponding_column(self, column, raiseerr=True, keys_ok=False, 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
raiseerr
  if True, raise an error if the given `ColumnElement` could not be matched. if False, non-matches will return None.
keys_ok
  if the `ColumnElement` cannot be matched, attempt to match based on the string "key" property of the column alone. This makes the search much more liberal.
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)
def default_order_by(self)
foreign_keys = property()
def join(self, right, *args, **kwargs)
def named_with_column(self)

True if the name of this FromClause may be prepended to a column in a generated SQL statement.

oid_column = property()
original_columns = property()

A dictionary mapping an original Table-bound column to a proxied column in this FromClause.

def outerjoin(self, right, *args, **kwargs)
primary_key = property()
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)
def accept_visitor(self, visitor)
def append(self, clause)
def copy_container(self)
def get_children(self, **kwargs)
key = property()
back to section top

### class _FunctionGateway(object)

Return a callable based on an attribute name, which then returns a `_Function` object with that name.

back to section top

### class _FunctionGenerator(object)

Generate `_Function` objects based on getattr calls.

def __init__(self, engine=None)
back to section top

### class _Insert(_UpdateBase)

def __init__(self, table, values=None)
def accept_visitor(self, visitor)
def get_children(self, **kwargs)
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)
def accept_visitor(self, visitor)
def alias(self, name=None)

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

The `Select` is not correlating.

encodedname = property()
engine = property()
def get_children(self, **kwargs)
name = property()
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.

back to section top

### class _Label(ColumnElement)

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)
def accept_visitor(self, visitor)
def get_children(self, **kwargs)
key = property()
orig_set = property()
back to section top

### class LoggingClauseVisitor(ClauseVisitor)

extends ClauseVisitor to include debug logging of all traversal.

To install this visitor, set logging.DEBUG for 'sqlalchemy.sql.ClauseVisitor' before you import the sqlalchemy.sql module.

def traverse(self, obj)
back to section top

### class NoColumnVisitor(ClauseVisitor)

a ClauseVisitor that will not traverse the exported Column collections on Table, Alias, Select, and CompoundSelect objects (i.e. their 'columns' or 'c' attribute).

this is useful because most traversals don't need those columns, or in the case of ANSICompiler it traverses them explicitly; so skipping their traversal here greatly cuts down on method call overhead.

back to section top

### class _Null(ColumnElement)

Represent the NULL keyword in a SQL statement.

Public constructor is the `null()` function.

def __init__(self)
def accept_visitor(self, visitor)
back to section top

### class Select(_SelectBaseMixin,FromClause)

Represent a `SELECT` statement, with appendable clauses, as well as the ability to execute itself and return a result set.

def __init__(self, columns=None, whereclause=None, from_obj=[], order_by=None, group_by=None, having=None, use_labels=False, distinct=False, for_update=False, engine=None, limit=None, offset=None, scalar=False, correlate=True)

construct a Select object.

The public constructor for Select is the select() function; see that function for argument descriptions.

def accept_visitor(self, visitor)
def append_column(self, column)
def append_from(self, fromclause)
def append_having(self, having)
def append_whereclause(self, whereclause)
def correlate(self, from_obj)

Given a `FROM` object, correlate this `SELECT` statement to it.

This basically means the given from object will not come out in this select statement's `FROM` clause when printed.

froms = property()

A collection containing all elements of the `FROM` clause.

def get_children(self, column_collections=True, **kwargs)
def label(self, name)
def union(self, other, **kwargs)
def union_all(self, other, **kwargs)
back to section top

### class _SelectBaseMixin(object)

Base class for `Select` and `CompoundSelects`.

def group_by(self, *clauses)
def order_by(self, *clauses)
def select(self, whereclauses=None, **params)
def supports_execution(self)
back to section top

### class Selectable(ClauseElement)

Represent a column list-holding object.

this is the common base class of ColumnElement and FromClause. The reason `ColumnElement` is marked as a "list-holding" object is so that it can be treated similarly to `FromClause` in column-selection scenarios; it contains a list of columns consisting of itself.

def accept_visitor(self, visitor)
columns = property()

a ColumnCollection containing `ColumnElement` instances.

def select(self, whereclauses=None, **params)
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)
def accept_visitor(self, visitor)
def alias(self, name=None)
def append_column(self, c)
def count(self, whereclause=None, **params)
def delete(self, whereclause=None)
def get_children(self, column_collections=True, **kwargs)
def insert(self, values=None)
def join(self, right, *args, **kwargs)
def named_with_column(self)
original_columns = property()
def outerjoin(self, right, *args, **kwargs)
def select(self, whereclause=None, **params)
def update(self, whereclause=None, values=None)
back to section top

### class _TextClause(ClauseElement)

Represent a literal SQL text fragment.

Public constructor is the `text()` function.

def __init__(self, text='', engine=None, bindparams=None, typemap=None)
def accept_visitor(self, visitor)
columns = property()
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)
def accept_visitor(self, visitor)
back to section top

### class _Update(_UpdateBase)

def __init__(self, table, whereclause, values=None)
def accept_visitor(self, visitor)
def get_children(self, **kwargs)
back to section top

### class _UpdateBase(ClauseElement)

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

def supports_execution(self)
back to section top