SQLAlchemy 0.5.5 Documentation

Version: 0.5.5 Last Updated: 07/13/2009 15:02:35
API Reference | Index

Database Schema

SQLAlchemy schema definition language. For more usage examples, see Database Meta Data.

Tables and Columns

class sqlalchemy.schema.Column(*args, **kwargs)

Bases: sqlalchemy.schema.SchemaItem, sqlalchemy.sql.expression.ColumnClause

Represents a column in a database table.

__init__(*args, **kwargs)

Construct a new Column object.

Parameters:
  • name

    The name of this column as represented in the database. This argument may be the first positional argument, or specified via keyword.

    Names which contain no upper case characters will be treated as case insensitive names, and will not be quoted unless they are a reserved word. Names with any number of upper case characters will be quoted and sent exactly. Note that this behavior applies even for databases which standardize upper case names as case insensitive such as Oracle.

    The name field may be omitted at construction time and applied later, at any time before the Column is associated with a Table. This is to support convenient usage within the declarative extension.

  • type_

    The column’s type, indicated using an instance which subclasses AbstractType. If no arguments are required for the type, the class of the type can be sent as well, e.g.:

    # use a type with arguments
    Column('data', String(50))
    
    # use no arguments
    Column('level', Integer)

    The type argument may be the second positional argument or specified by keyword.

    If this column also contains a ForeignKey, the type argument may be left as None in which case the type assigned will be that of the referenced column.

  • *args – Additional positional arguments include various SchemaItem derived constructs which will be applied as options to the column. These include instances of Constraint, ForeignKey, ColumnDefault, and Sequence. In some cases an equivalent keyword argument is available such as server_default, default and unique.
  • autoincrement

    This flag may be set to False to disable SQLAlchemy indicating at the DDL level that an integer primary key column should have autoincrementing behavior. This is an oft misunderstood flag and has no effect whatsoever unless all of the following conditions are met:

    • The column is of the Integer datatype.
    • The column has the primary_key flag set, or is otherwise a member of a PrimaryKeyConstraint on this table.
    • a CREATE TABLE statement is being issued via create() or create_all(). The flag has no relevance at any other time.
    • The database supports autoincrementing behavior, such as PostgreSQL or MySQL, and this behavior can be disabled (which does not include SQLite).
  • default

    A scalar, Python callable, or ClauseElement representing the default value for this column, which will be invoked upon insert if this column is otherwise not specified in the VALUES clause of the insert. This is a shortcut to using ColumnDefault as a positional argument.

    Contrast this argument to server_default which creates a default generator on the database side.

  • key – An optional string identifier which will identify this Column object on the Table. When a key is provided, this is the only identifier referencing the Column within the application, including ORM attribute mapping; the name field is used only when rendering SQL.
  • index – When True, indicates that the column is indexed. This is a shortcut for using a Index construct on the table. To specify indexes with explicit names or indexes that contain multiple columns, use the Index construct instead.
  • info – A dictionary which defaults to {}. A space to store application specific data. This must be a dictionary.
  • nullable – If set to the default of True, indicates the column will be rendered as allowing NULL, else it’s rendered as NOT NULL. This parameter is only used when issuing CREATE TABLE statements.
  • onupdate – A scalar, Python callable, or ClauseElement representing a default value to be applied to the column within UPDATE statements, which wil be invoked upon update if this column is not present in the SET clause of the update. This is a shortcut to using ColumnDefault as a positional argument with for_update=True.
  • primary_key – If True, marks this column as a primary key column. Multiple columns can have this flag set to specify composite primary keys. As an alternative, the primary key of a Table can be specified via an explicit PrimaryKeyConstraint object.
  • server_default

    A FetchedValue instance, str, Unicode or text() construct representing the DDL DEFAULT value for the column.

    String types will be emitted as-is, surrounded by single quotes:

    Column('x', Text, server_default="val")
    
    x TEXT DEFAULT 'val'

    A text() expression will be rendered as-is, without quotes:

    Column('y', DateTime, server_default=text('NOW()'))0
    
    y DATETIME DEFAULT NOW()

    Strings and text() will be converted into a DefaultClause object upon initialization.

    Use FetchedValue to indicate that an already-existing column will generate a default value on the database side which will be available to SQLAlchemy for post-fetch after inserts. This construct does not specify any DDL and the implementation is left to the database, such as via a trigger.

  • server_onupdate – A FetchedValue instance representing a database-side default generation function. This indicates to SQLAlchemy that a newly generated value will be available after updates. This construct does not specify any DDL and the implementation is left to the database, such as via a trigger.
  • quote – Force quoting of this column’s name on or off, corresponding to True or False. When left at its default of None, the column identifier will be quoted according to whether the name is case sensitive (identifiers with at least one upper case character are treated as case sensitive), or if it’s a reserved word. This flag is only needed to force quoting of a reserved word which is not known by the SQLAlchemy dialect.
  • unique – When True, indicates that this column contains a unique constraint, or if index is True as well, indicates that the Index should be created with the unique flag. To specify multiple columns in the constraint/index or to specify an explicit name, use the UniqueConstraint or Index constructs explicitly.
append_foreign_key(fk)
asc()
Produce a ASC clause, i.e. <columnname> ASC
between(cleft, cright)
Produce a BETWEEN clause, i.e. <column> BETWEEN <cleft> AND <cright>
bind
collate(collation)
Produce a COLLATE clause, i.e. <column> COLLATE utf8_bin
compare(other)

Compare this ClauseElement to the given ClauseElement.

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

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

Compile this SQL expression.

The return value is a Compiled object. Calling str() or unicode() on the returned value will yield a string representation of the result. The Compiled object also can return a dictionary of bind parameter names and values using the params accessor.

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • compiler – A Compiled instance which will be used to compile this expression. This argument takes precedence over the bind and dialect arguments as well as this ClauseElement‘s bound engine, if any.
  • dialect – A Dialect instance frmo which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
concat(other)
contains(other, escape=None)
Produce the clause LIKE '%<other>%'
copy(**kw)

Create a copy of this Column, unitialized.

This is used in Table.tometadata.

desc()
Produce a DESC clause, i.e. <columnname> DESC
distinct()
Produce a DISTINCT clause, i.e. DISTINCT <columnname>
endswith(other, escape=None)
Produce the clause LIKE '%<other>'
execute(*multiparams, **params)
Compile and execute this ClauseElement.
get_children(schema_visitor=False, **kwargs)
ilike(other, escape=None)
in_(other)
info
label(name)
like(other, escape=None)
match(other)

Produce a MATCH clause, i.e. MATCH '<other>'

The allowed contents of other are database backend specific.

op(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.
operate(op, *other, **kwargs)
params(*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}
references(column)
Return True if this Column references the given column via foreign key.
reverse_operate(op, other, **kwargs)
scalar(*multiparams, **params)
Compile and execute this ClauseElement, returning the result’s scalar representation.
self_group(against=None)
shares_lineage(othercolumn)
Return True if the given ColumnElement has a common ancestor to this ColumnElement.
startswith(other, escape=None)
Produce the clause LIKE '<other>%'
unique_params(*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.

class sqlalchemy.schema.MetaData(bind=None, reflect=False)

Bases: sqlalchemy.schema.SchemaItem

A collection of Tables and their associated schema constructs.

Holds a collection of Tables and an optional binding to an Engine or Connection. If bound, the Table objects in the collection and their columns may participate in implicit SQL execution.

The Table objects themselves are stored in the metadata.tables dictionary.

The bind property may be assigned to dynamically. A common pattern is to start unbound and then bind later when an engine is available:

metadata = MetaData()
# define tables
Table('mytable', metadata, ...)
# connect to an engine later, perhaps after loading a URL from a
# configuration file
metadata.bind = an_engine

MetaData is a thread-safe object after tables have been explicitly defined or loaded via reflection.

__init__(bind=None, reflect=False)

Create a new MetaData object.

bind
An Engine or Connection to bind to. May also be a string or URL instance, these are passed to create_engine() and this MetaData will be bound to the resulting engine.
reflect
Optional, automatically load all tables from the bound database. Defaults to False. bind is required when this option is set. For finer control over loaded tables, use the reflect method of MetaData.
append_ddl_listener(event, listener)

Append a DDL event listener to this MetaData.

The listener callable will be triggered when this MetaData is involved in DDL creates or drops, and will be invoked either before all Table-related actions or after.

Arguments are:

event
One of MetaData.ddl_events; ‘before-create’, ‘after-create’, ‘before-drop’ or ‘after-drop’.
listener

A callable, invoked with three positional arguments:

event
The event currently being handled
schema_item
The MetaData object being operated upon
bind
The Connection bueing used for DDL execution.

Listeners are added to the MetaData’s ddl_listeners attribute.

Note: MetaData listeners are invoked even when Tables are created in isolation. This may change in a future release. I.e.:

# triggers all MetaData and Table listeners:
metadata.create_all()

# triggers MetaData listeners too:
some.table.create()
bind

An Engine or Connection to which this MetaData is bound.

This property may be assigned an Engine or Connection, or assigned a string or URL to automatically create a basic Engine for this bind with create_engine().

clear()
Clear all Table objects from this MetaData.
connect(bind, **kwargs)

Bind this MetaData to an Engine.

Deprecated. Use metadata.bind = <engine> or metadata.bind = <url>.

bind
A string, URL, Engine or Connection instance. If a string or URL, will be passed to create_engine() along with \**kwargs to produce the engine which to connect to. Otherwise connects directly to the given Engine.
create_all(bind=None, tables=None, checkfirst=True)

Create all tables stored in this metadata.

Conditional by default, will not attempt to recreate tables already present in the target database.

bind
A Connectable used to access the database; if None, uses the existing bind on this MetaData, if any.
tables
Optional list of Table objects, which is a subset of the total tables in the MetaData (others are ignored).
checkfirst
Defaults to True, don’t issue CREATEs for tables already present in the target database.
drop_all(bind=None, tables=None, checkfirst=True)

Drop all tables stored in this metadata.

Conditional by default, will not attempt to drop tables not present in the target database.

bind
A Connectable used to access the database; if None, uses the existing bind on this MetaData, if any.
tables
Optional list of Table objects, which is a subset of the total tables in the MetaData (others are ignored).
checkfirst
Defaults to True, only issue DROPs for tables confirmed to be present in the target database.
is_bound()
True if this MetaData is bound to an Engine or Connection.
reflect(bind=None, schema=None, only=None)

Load all available table definitions from the database.

Automatically creates Table entries in this MetaData for any table available in the database but not yet present in the MetaData. May be called multiple times to pick up tables recently added to the database, however no special action is taken if a table in this MetaData no longer exists in the database.

bind
A Connectable used to access the database; if None, uses the existing bind on this MetaData, if any.
schema
Optional, query and reflect tables from an alterate schema.
only

Optional. Load only a sub-set of available named tables. May be specified as a sequence of names or a callable.

If a sequence of names is provided, only those tables will be reflected. An error is raised if a table is requested but not available. Named tables already present in this MetaData are ignored.

If a callable is provided, it will be used as a boolean predicate to filter the list of potential table names. The callable is called with a table name and this MetaData instance as positional arguments and should return a true value for any table to reflect.

remove(table)
Remove the given Table object from this MetaData.
sorted_tables
Returns a list of Table objects sorted in order of dependency.
table_iterator(reverse=True, tables=None)

Deprecated - use metadata.sorted_tables().

Deprecated. Use metadata.sorted_tables

class sqlalchemy.schema.Table(name, metadata, *args, **kwargs)

Bases: sqlalchemy.schema.SchemaItem, sqlalchemy.sql.expression.TableClause

Represent a table in a database.

__init__(name, metadata, *args, **kwargs)

Construct a Table.

Parameters:
  • name

    The name of this table as represented in the database.

    This property, along with the schema, indicates the singleton identity of this table in relation to its parent MetaData. Additional calls to Table with the same name, metadata, and schema name will return the same Table object.

    Names which contain no upper case characters will be treated as case insensitive names, and will not be quoted unless they are a reserved word. Names with any number of upper case characters will be quoted and sent exactly. Note that this behavior applies even for databases which standardize upper case names as case insensitive such as Oracle.

  • metadata – a MetaData object which will contain this table. The metadata is used as a point of association of this table with other tables which are referenced via foreign key. It also may be used to associate this table with a particular Connectable.
  • *args – Additional positional arguments are used primarily to add the list of Column objects contained within this table. Similar to the style of a CREATE TABLE statement, other SchemaItem constructs may be added here, including PrimaryKeyConstraint, and ForeignKeyConstraint.
  • autoload – Defaults to False: the Columns for this table should be reflected from the database. Usually there will be no Column objects in the constructor if this property is set.
  • autoload_with – If autoload==True, this is an optional Engine or Connection instance to be used for the table reflection. If None, the underlying MetaData’s bound connectable will be used.
  • include_columns – A list of strings indicating a subset of columns to be loaded via the autoload operation; table columns who aren’t present in this list will not be represented on the resulting Table object. Defaults to None which indicates all columns should be reflected.
  • info – A dictionary which defaults to {}. A space to store application specific data. This must be a dictionary.
  • mustexist – When True, indicates that this Table must already be present in the given MetaData` collection.
  • prefixes – A list of strings to insert after CREATE in the CREATE TABLE statement. They will be separated by spaces.
  • quote – Force quoting of this table’s name on or off, corresponding to True or False. When left at its default of None, the column identifier will be quoted according to whether the name is case sensitive (identifiers with at least one upper case character are treated as case sensitive), or if it’s a reserved word. This flag is only needed to force quoting of a reserved word which is not known by the SQLAlchemy dialect.
  • quote_schema – same as ‘quote’ but applies to the schema identifier.
  • schema – The schema name for this table, which is required if the table resides in a schema other than the default selected schema for the engine’s database connection. Defaults to None.
  • useexisting – When True, indicates that if this Table is already present in the given MetaData, apply further arguments within the constructor to the existing Table. If this flag is not set, an error is raised when the parameters of an existing Table are overwritten.
alias(name=None)

return an alias of this FromClause.

For table objects, this has the effect of the table being rendered as tablename AS aliasname in a SELECT statement. For select objects, the effect is that of creating a named subquery, i.e. (select ...) AS aliasname. The alias() method is the general way to create a “subquery” out of an existing SELECT.

The name parameter is optional, and if left blank an “anonymous” name will be generated at compile time, guaranteed to be unique against other anonymous constructs used in the same statement.

append_column(column)
Append a Column to this Table.
append_constraint(constraint)
Append a Constraint to this Table.
append_ddl_listener(event, listener)

Append a DDL event listener to this Table.

The listener callable will be triggered when this Table is created or dropped, either directly before or after the DDL is issued to the database. The listener may modify the Table, but may not abort the event itself.

Arguments are:

event
One of Table.ddl_events; e.g. ‘before-create’, ‘after-create’, ‘before-drop’ or ‘after-drop’.
listener

A callable, invoked with three positional arguments:

event
The event currently being handled
schema_item
The Table object being created or dropped
bind
The Connection bueing used for DDL execution.

Listeners are added to the Table’s ddl_listeners attribute.

bind
Return the connectable associated with this SchemaItem.
c
Return the collection of Column objects contained by this FromClause.
columns
Return the collection of Column objects contained by this FromClause.
compare(other)

Compare this ClauseElement to the given ClauseElement.

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

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

Compile this SQL expression.

The return value is a Compiled object. Calling str() or unicode() on the returned value will yield a string representation of the result. The Compiled object also can return a dictionary of bind parameter names and values using the params accessor.

Parameters:
  • bind – An Engine or Connection from which a Compiled will be acquired. This argument takes precedence over this ClauseElement‘s bound engine, if any.
  • column_keys – Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If None, all columns from the target table object are rendered.
  • compiler – A Compiled instance which will be used to compile this expression. This argument takes precedence over the bind and dialect arguments as well as this ClauseElement‘s bound engine, if any.
  • dialect – A Dialect instance frmo which a Compiled will be acquired. This argument takes precedence over the bind argument as well as this ClauseElement‘s bound engine, if any.
  • inline – Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement’s VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key Column.
correspond_on_equivalents(column, equivalents)
Return corresponding_column for the given column, or if None search for a match in the given dictionary.
corresponding_column(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.

Parameters:
  • 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.
count(whereclause=None, **params)
create(bind=None, checkfirst=False)

Issue a CREATE statement for this table.

See also metadata.create_all().

delete(whereclause=None, **kwargs)
Generate a delete() construct.
drop(bind=None, checkfirst=False)

Issue a DROP statement for this table.

See also metadata.drop_all().

execute(*multiparams, **params)
Compile and execute this ClauseElement.
exists(bind=None)
Return True if this table exists.
foreign_keys
Return the collection of ForeignKey objects which this FromClause references.
get_children(column_collections=True, schema_visitor=False, **kwargs)
info
insert(values=None, inline=False, **kwargs)
Generate an insert() construct.
is_derived_from(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.

join(right, onclause=None, isouter=False)
return a join of this FromClause against another FromClause.
key
outerjoin(right, onclause=None)
return an outer join of this FromClause against another FromClause.
params(*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}
primary_key
replace_selectable(old, alias)
replace all occurences of FromClause ‘old’ with the given Alias object, returning a copy of this FromClause.
scalar(*multiparams, **params)
Compile and execute this ClauseElement, returning the result’s scalar representation.
select(whereclause=None, **params)
return a SELECT of this FromClause.
self_group(against=None)
tometadata(metadata, schema=None)
Return a copy of this Table associated with a different MetaData.
unique_params(*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.

update(whereclause=None, values=None, inline=False, **kwargs)
Generate an update() construct.
class sqlalchemy.schema.ThreadLocalMetaData

Bases: sqlalchemy.schema.MetaData

A MetaData variant that presents a different bind in every thread.

Makes the bind property of the MetaData a thread-local value, allowing this collection of tables to be bound to different Engine implementations or connections in each thread.

The ThreadLocalMetaData starts off bound to None in each thread. Binds must be made explicitly by assigning to the bind property or using connect(). You can also re-bind dynamically multiple times per thread, just like a regular MetaData.

__init__()
Construct a ThreadLocalMetaData.
bind

The bound Engine or Connection for this thread.

This property may be assigned an Engine or Connection, or assigned a string or URL to automatically create a basic Engine for this bind with create_engine().

connect(bind, **kwargs)

Bind to an Engine in the caller’s thread.

Deprecated. Use metadata.bind = <engine> or metadata.bind = <url>.

bind
A string, URL, Engine or Connection instance. If a string or URL, will be passed to create_engine() along with \**kwargs to produce the engine which to connect to. Otherwise connects directly to the given Engine.
dispose()
Dispose all bound engines, in all thread contexts.
is_bound()
True if there is a bind for this thread.

Constraints

class sqlalchemy.schema.CheckConstraint(sqltext, name=None, deferrable=None, initially=None)

Bases: sqlalchemy.schema.Constraint

A table- or column-level CHECK constraint.

Can be included in the definition of a Table or Column.

__init__(sqltext, name=None, deferrable=None, initially=None)

Construct a CHECK constraint.

sqltext
A string containing the constraint definition. Will be used verbatim.
name
Optional, the in-database name of the constraint.
deferrable
Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint.
initially
Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint.
copy(**kw)
class sqlalchemy.schema.Constraint(name=None, deferrable=None, initially=None)

Bases: sqlalchemy.schema.SchemaItem

A table-level SQL constraint, such as a KEY.

Implements a hybrid of dict/setlike behavior with regards to the list of underying columns.

__init__(name=None, deferrable=None, initially=None)

Create a SQL constraint.

name
Optional, the in-database name of this Constraint.
deferrable
Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint.
initially
Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint.
contains_column(col)
copy(**kw)
keys()
class sqlalchemy.schema.ForeignKey(column, constraint=None, use_alter=False, name=None, onupdate=None, ondelete=None, deferrable=None, initially=None, link_to_name=False)

Bases: sqlalchemy.schema.SchemaItem

Defines a column-level FOREIGN KEY constraint between two columns.

ForeignKey is specified as an argument to a Column object, e.g.:

t = Table("remote_table", metadata, 
    Column("remote_id", ForeignKey("main_table.id"))
)

For a composite (multiple column) FOREIGN KEY, use a ForeignKeyConstraint object specified at the level of the Table.

Further examples of foreign key configuration are in Defining Foreign Keys.

__init__(column, constraint=None, use_alter=False, name=None, onupdate=None, ondelete=None, deferrable=None, initially=None, link_to_name=False)

Construct a column-level FOREIGN KEY.

Parameters:
  • column – A single target column for the key relationship. A Column object or a column name as a string: tablename.columnkey or schema.tablename.columnkey. columnkey is the key which has been assigned to the column (defaults to the column name itself), unless link_to_name is True in which case the rendered name of the column is used.
  • constraint – Optional. A parent ForeignKeyConstraint object. If not supplied, a ForeignKeyConstraint will be automatically created and added to the parent table.
  • name – Optional string. An in-database name for the key if constraint is not provided.
  • onupdate – Optional string. If set, emit ON UPDATE <value> when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT.
  • ondelete – Optional string. If set, emit ON DELETE <value> when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT.
  • deferrable – Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint.
  • initially – Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint.
  • link_to_name – if True, the string name given in column is the rendered name of the referenced column, not its locally assigned key.
  • use_alter – If True, do not emit this key as part of the CREATE TABLE definition. Instead, use ALTER TABLE after table creation to add the key. Useful for circular dependencies.
copy(schema=None)
Produce a copy of this ForeignKey object.
get_referent(table)

Return the column in the given table referenced by this ForeignKey.

Returns None if this ForeignKey does not reference the given table.

references(table)
Return True if the given table is referenced by this ForeignKey.
target_fullname
class sqlalchemy.schema.ForeignKeyConstraint(columns, refcolumns, name=None, onupdate=None, ondelete=None, use_alter=False, deferrable=None, initially=None, link_to_name=False)

Bases: sqlalchemy.schema.Constraint

A table-level FOREIGN KEY constraint.

Defines a single column or composite FOREIGN KEY ... REFERENCES constraint. For a no-frills, single column foreign key, adding a ForeignKey to the definition of a Column is a shorthand equivalent for an unnamed, single column ForeignKeyConstraint.

Examples of foreign key configuration are in Defining Foreign Keys.

__init__(columns, refcolumns, name=None, onupdate=None, ondelete=None, use_alter=False, deferrable=None, initially=None, link_to_name=False)

Construct a composite-capable FOREIGN KEY.

Parameters:
  • columns – A sequence of local column names. The named columns must be defined and present in the parent Table. The names should match the key given to each column (defaults to the name) unless link_to_name is True.
  • refcolumns – A sequence of foreign column names or Column objects. The columns must all be located within the same Table.
  • name – Optional, the in-database name of the key.
  • onupdate – Optional string. If set, emit ON UPDATE <value> when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT.
  • ondelete – Optional string. If set, emit ON DELETE <value> when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT.
  • deferrable – Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint.
  • initially – Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint.
  • link_to_name – if True, the string name given in column is the rendered name of the referenced column, not its locally assigned key.
  • use_alter – If True, do not emit this key as part of the CREATE TABLE definition. Instead, use ALTER TABLE after table creation to add the key. Useful for circular dependencies.
append_element(col, refcol)
copy(**kw)
class sqlalchemy.schema.Index(name, *columns, **kwargs)

Bases: sqlalchemy.schema.SchemaItem

A table-level INDEX.

Defines a composite (one or more column) INDEX. For a no-frills, single column index, adding index=True to the Column definition is a shorthand equivalent for an unnamed, single column Index.

__init__(name, *columns, **kwargs)

Construct an index object.

Arguments are:

name
The name of the index
*columns
Columns to include in the index. All columns must belong to the same table, and no column may appear more than once.
**kwargs

Keyword arguments include:

unique
Defaults to False: create a unique index.
postgres_where
Defaults to None: create a partial index when using PostgreSQL
append_column(column)
create(bind=None)
drop(bind=None)
class sqlalchemy.schema.PrimaryKeyConstraint(*columns, **kwargs)

Bases: sqlalchemy.schema.Constraint

A table-level PRIMARY KEY constraint.

Defines a single column or composite PRIMARY KEY constraint. For a no-frills primary key, adding primary_key=True to one or more Column definitions is a shorthand equivalent for an unnamed single- or multiple-column PrimaryKeyConstraint.

__init__(*columns, **kwargs)

Construct a composite-capable PRIMARY KEY.

*columns
A sequence of column names. All columns named must be defined and present within the parent Table.
name
Optional, the in-database name of the key.
deferrable
Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint.
initially
Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint.
add(col)
append_column(col)
copy(**kw)
remove(col)
replace(col)
class sqlalchemy.schema.UniqueConstraint(*columns, **kwargs)

Bases: sqlalchemy.schema.Constraint

A table-level UNIQUE constraint.

Defines a single column or composite UNIQUE constraint. For a no-frills, single column constraint, adding unique=True to the Column definition is a shorthand equivalent for an unnamed, single column UniqueConstraint.

__init__(*columns, **kwargs)

Construct a UNIQUE constraint.

*columns
A sequence of column names. All columns named must be defined and present within the parent Table.
name
Optional, the in-database name of the key.
deferrable
Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint.
initially
Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint.
append_column(col)
copy(**kw)

Default Generators and Markers

class sqlalchemy.schema.ColumnDefault(arg, **kwargs)

Bases: sqlalchemy.schema.DefaultGenerator

A plain default value on a column.

This could correspond to a constant, a callable function, or a SQL clause.

__init__(arg, **kwargs)
class sqlalchemy.schema.DefaultClause(arg, for_update=False)

Bases: sqlalchemy.schema.FetchedValue

A DDL-specified DEFAULT column value.

class sqlalchemy.schema.DefaultGenerator(for_update=False, metadata=None)

Bases: sqlalchemy.schema.SchemaItem

Base class for column default values.

__init__(for_update=False, metadata=None)
execute(bind=None, **kwargs)
class sqlalchemy.schema.FetchedValue(for_update=False)

Bases: object

A default that takes effect on the database side.

__init__(for_update=False)
sqlalchemy.schema.PassiveDefault
alias of DefaultClause
class sqlalchemy.schema.Sequence(name, start=None, increment=None, schema=None, optional=False, quote=None, **kwargs)

Bases: sqlalchemy.schema.DefaultGenerator

Represents a named database sequence.

__init__(name, start=None, increment=None, schema=None, optional=False, quote=None, **kwargs)
create(bind=None, checkfirst=True)
Creates this sequence in the database.
drop(bind=None, checkfirst=True)
Drops this sequence from the database.

DDL

class sqlalchemy.schema.DDL(statement, on=None, context=None, bind=None)

Bases: object

A literal DDL statement.

Specifies literal SQL DDL to be executed by the database. DDL objects can be attached to Tables or MetaData instances, conditionally executing SQL as part of the DDL lifecycle of those schema items. Basic templating support allows a single DDL instance to handle repetitive tasks for multiple tables.

Examples:

tbl = Table('users', metadata, Column('uid', Integer)) # ...
DDL('DROP TRIGGER users_trigger').execute_at('before-create', tbl)

spow = DDL('ALTER TABLE %(table)s SET secretpowers TRUE', on='somedb')
spow.execute_at('after-create', tbl)

drop_spow = DDL('ALTER TABLE users SET secretpowers FALSE')
connection.execute(drop_spow)
__init__(statement, on=None, context=None, bind=None)

Create a DDL statement.

statement

A string or unicode string to be executed. Statements will be processed with Python’s string formatting operator. See the context argument and the execute_at method.

A literal ‘%’ in a statement must be escaped as ‘%%’.

SQL bind parameters are not available in DDL statements.

on

Optional filtering criteria. May be a string or a callable predicate. If a string, it will be compared to the name of the executing database dialect:

DDL('something', on='postgres')

If a callable, it will be invoked with three positional arguments:

event
The name of the event that has triggered this DDL, such as ‘after-create’ Will be None if the DDL is executed explicitly.
schema_item
A SchemaItem instance, such as Table or MetaData. May be None if the DDL is executed explicitly.
connection
The Connection being used for DDL execution

If the callable returns a true value, the DDL statement will be executed.

context
Optional dictionary, defaults to None. These values will be available for use in string substitutions on the DDL statement.
bind
Optional. A Connectable, used by default when execute() is invoked without a bind argument.
bind

An Engine or Connection to which this DDL is bound.

This property may be assigned an Engine or Connection, or assigned a string or URL to automatically create a basic Engine for this bind with create_engine().

execute(bind=None, schema_item=None)

Execute this DDL immediately.

Executes the DDL statement in isolation using the supplied Connectable or Connectable assigned to the .bind property, if not supplied. If the DDL has a conditional on criteria, it will be invoked with None as the event.

bind
Optional, an Engine or Connection. If not supplied, a valid Connectable must be present in the .bind property.
schema_item
Optional, defaults to None. Will be passed to the on callable criteria, if any, and may provide string expansion data for the statement. See execute_at for more information.
execute_at(event, schema_item)

Link execution of this DDL to the DDL lifecycle of a SchemaItem.

Links this DDL to a Table or MetaData instance, executing it when that schema item is created or dropped. The DDL statement will be executed using the same Connection and transactional context as the Table create/drop itself. The .bind property of this statement is ignored.

event
One of the events defined in the schema item’s .ddl_events; e.g. ‘before-create’, ‘after-create’, ‘before-drop’ or ‘after-drop’
schema_item
A Table or MetaData instance

When operating on Table events, the following additional statement string substitions are available:

%(table)s  - the Table name, with any required quoting applied
%(schema)s - the schema name, with any required quoting applied
%(fullname)s - the Table name including schema, quoted if needed

The DDL’s context, if any, will be combined with the standard substutions noted above. Keys present in the context will override the standard substitutions.

A DDL instance can be linked to any number of schema items. The statement subsitution support allows for DDL instances to be used in a template fashion.

execute_at builds on the append_ddl_listener interface of MetaDta and Table objects.

Caveat: Creating or dropping a Table in isolation will also trigger any DDL set to execute_at that Table’s MetaData. This may change in a future release.

Internals

class sqlalchemy.schema.SchemaItem

Bases: sqlalchemy.sql.visitors.Visitable

Base class for items that define a database schema.

bind
Return the connectable associated with this SchemaItem.
get_children(**kwargs)
used to allow SchemaVisitor access
info
class sqlalchemy.schema.SchemaVisitor

Bases: sqlalchemy.sql.visitors.ClauseVisitor

Define the visiting for SchemaItem objects.

Previous: SQL Statements and Expressions Next: Column and Data Types