SQLAlchemy 0.6.1 Documentation

Version: 0.6.1 Last Updated: 07/25/2016 21:14:41
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.

    There is partial support for automatic detection of the type based on that of a ForeignKey associated with this column, if the type is specified as None. However, this feature is not fully implemented and may not function in all cases.

  • *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 indicate an integer primary key column that should not be considered to be the “autoincrement” column, that is the integer primary key column which generates values implicitly upon INSERT and whose value is usually returned via the DBAPI cursor.lastrowid attribute. It defaults to True to satisfy the common use case of a table with a single integer primary key column. If the table has a composite primary key consisting of more than one integer column, set this flag to True only on the column that should be considered “autoincrement”.

    The setting only has an effect for columns which are:

    • Integer derived (i.e. INT, SMALLINT, BIGINT)
    • Part of the primary key
    • Are not referenced by any foreign keys
    • have no server side or client side defaults (with the exception of Postgresql SERIAL).

    The setting has these two effects on columns that meet the above criteria:

    • DDL issued for the column will include database-specific keywords intended to signify this column as an “autoincrement” column, such as AUTO INCREMENT on MySQL, SERIAL on Postgresql, and IDENTITY on MS-SQL. It does not issue AUTOINCREMENT for SQLite since this is a special SQLite flag that is not required for autoincrementing behavior. See the SQLite dialect documentation for information on SQLite’s AUTOINCREMENT.
    • The column will be considered to be available as cursor.lastrowid or equivalent, for those dialects which “post fetch” newly inserted identifiers after a row has been inserted (SQLite, MySQL, MS-SQL). It does not have any effect in this regard for databases that use sequences to generate primary key identifiers (i.e. Firebird, Postgresql, Oracle).
  • 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.

  • doc – optional String that can be used by the ORM or similar to document attributes. This attribute does not render SQL comments (a future attribute ‘comment’ will achieve that).
  • 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)
copy(**kw)

Create a copy of this Column, unitialized.

This is used in Table.tometadata.

get_children(schema_visitor=False, **kwargs)
references(column)
Return True if this Column references the given column via foreign key.
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
target
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.
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.
class sqlalchemy.schema.Table(*args, **kw)

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

Represent a table in a database.

e.g.:

mytable = Table("mytable", metadata, 
                Column('mytable_id', Integer, primary_key=True),
                Column('value', String(50))
           )

The Table object constructs a unique instance of itself based on its name within the given MetaData object. Constructor arguments are as follows:

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.
  • implicit_returning – True by default - indicates that RETURNING can be used by default to fetch newly inserted primary key values, for backends which support this. Note that create_engine() also provides an implicit_returning flag.
  • 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.
__init__(*args, **kw)
add_is_dependent_on(table)

Add a ‘dependency’ for this Table.

This is another Table object which must be created first before this one can, or dropped after this one.

Usually, dependencies between tables are determined via ForeignKey objects. However, for other situations that create dependencies outside of foreign keys (rules, inheriting), this method can manually establish such a link.

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
target
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 Table.
create(bind=None, checkfirst=False)

Issue a CREATE statement for this table.

See also metadata.create_all().

drop(bind=None, checkfirst=False)

Issue a DROP statement for this table.

See also metadata.drop_all().

exists(bind=None)
Return True if this table exists.
get_children(column_collections=True, schema_visitor=False, **kwargs)
key
primary_key
tometadata(metadata, schema=<symbol 'retain_schema>)
Return a copy of this Table associated with a different MetaData.
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().

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, table=None, _create_rule=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, table=None, _create_rule=None)

Construct a CHECK constraint.

sqltext
A string containing the constraint definition, which will be used verbatim, or a SQL expression construct.
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, _create_rule=None)

Bases: sqlalchemy.schema.SchemaItem

A table-level SQL constraint.

__init__(name=None, deferrable=None, initially=None, _create_rule=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.
_create_rule

a callable which is passed the DDLCompiler object during compilation. Returns True or False to signal inline generation of this Constraint.

The AddConstraint and DropConstraint DDL constructs provide DDLElement’s more comprehensive “conditional DDL” approach that is passed a database connection when DDL is being issued. _create_rule is instead called during any CREATE TABLE compilation, where there may not be any transaction/connection in progress. However, it allows conditional compilation of the constraint even for backends which do not support addition of constraints through ALTER TABLE, which currently includes SQLite.

_create_rule is used by some types to create constraints. Currently, its call signature is subject to change at any time.

copy(**kw)
table
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 dependency 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"))
)

Note that ForeignKey is only a marker object that defines a dependency between two columns. The actual constraint is in all cases represented by the ForeignKeyConstraint object. This object will be generated automatically when a ForeignKey is associated with a Column which in turn is associated with a Table. Conversely, when ForeignKeyConstraint is applied to a Table, ForeignKey markers are automatically generated to be present on each associated Column, which are also associated with the constraint object.

Note that you cannot define a “composite” foreign key constraint, that is a constraint between a grouping of multiple parent/child columns, using ForeignKey objects. To define this grouping, the ForeignKeyConstraint object must be used, and applied to the Table. The associated ForeignKey objects are created automatically.

The ForeignKey objects associated with an individual Column object are available in the foreign_keys collection of that column.

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.

The ForeignKey object when constructed generates a ForeignKeyConstraint which is associated with the parent Table object’s collection of constraints.

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.
  • 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 – passed to the underlying ForeignKeyConstraint to indicate the constraint should be generated/dropped externally from the CREATE TABLE/ DROP TABLE statement. See that classes’ constructor for details.
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, deferrable=None, initially=None, use_alter=False, link_to_name=False, table=None)

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, deferrable=None, initially=None, use_alter=False, link_to_name=False, table=None)

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 the DDL for this constraint as part of the CREATE TABLE definition. Instead, generate it via an ALTER TABLE statement issued after the full collection of tables have been created, and drop it via an ALTER TABLE statement before the full collection of tables are dropped. This is shorthand for the usage of AddConstraint and DropConstraint applied as “after-create” and “before-drop” events on the MetaData object. This is normally used to generate/drop constraints on objects that are mutually dependent on each other.
columns
copy(**kw)
elements
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.
**kwargs

Keyword arguments include:

unique
Defaults to False: create a unique index.
postgresql_where
Defaults to None: create a partial index when using PostgreSQL
bind
Return the connectable associated with this Index.
create(bind=None)
drop(bind=None)
class sqlalchemy.schema.PrimaryKeyConstraint(*columns, **kw)

Bases: sqlalchemy.schema.ColumnCollectionConstraint

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.

class sqlalchemy.schema.UniqueConstraint(*columns, **kw)

Bases: sqlalchemy.schema.ColumnCollectionConstraint

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.

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)

Bases: sqlalchemy.schema.SchemaItem

Base class for column default values.

__init__(for_update=False)
bind
Return the connectable associated with this default.
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)
class sqlalchemy.schema.PassiveDefault(*arg, **kw)

Bases: sqlalchemy.schema.DefaultClause

__init__(*arg, **kw)
class sqlalchemy.schema.Sequence(name, start=None, increment=None, schema=None, optional=False, quote=None, metadata=None, for_update=False)

Bases: sqlalchemy.schema.DefaultGenerator

Represents a named database sequence.

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

DDL Generation

class sqlalchemy.schema.DDLElement

Bases: sqlalchemy.sql.expression.Executable, sqlalchemy.sql.expression.ClauseElement

Base class for DDL expression constructs.

against(target)
Return a copy of this DDL against a specific schema item.
bind
execute(bind=None, target=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.
target
Optional, defaults to None. The target SchemaItem for the execute call. Will be passed to the on callable if any, and may also provide string expansion data for the statement. See execute_at for more information.
execute_at(event, target)

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

Links this DDLElement 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’
target
The Table or MetaData instance for which this DDLElement will be associated with.

A DDLElement instance can be linked to any number of schema items.

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.

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

Bases: sqlalchemy.schema.DDLElement

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)

When operating on Table events, the following 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.

__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, tuple or a callable predicate. If a string, it will be compared to the name of the executing database dialect:

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

If a tuple, specifies multiple dialect names:

DDL('something', on=('postgresql', 'mysql'))

If a callable, it will be invoked with four positional arguments as well as optional keyword arguments:

ddl
This DDL element.
event
The name of the event that has triggered this DDL, such as ‘after-create’ Will be None if the DDL is executed explicitly.
target
The Table or MetaData object which is the target of this event. May be None if the DDL is executed explicitly.
connection
The Connection being used for DDL execution
**kw
Keyword arguments which may be sent include:
tables - a list of Table objects which are to be created/ dropped within a MetaData.create_all() or drop_all() method call.

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.
class sqlalchemy.schema.CreateTable(element, on=None, bind=None)

Bases: sqlalchemy.schema._CreateDropBase

Represent a CREATE TABLE statement.

class sqlalchemy.schema.DropTable(element, on=None, bind=None)

Bases: sqlalchemy.schema._CreateDropBase

Represent a DROP TABLE statement.

class sqlalchemy.schema.CreateSequence(element, on=None, bind=None)

Bases: sqlalchemy.schema._CreateDropBase

Represent a CREATE SEQUENCE statement.

class sqlalchemy.schema.DropSequence(element, on=None, bind=None)

Bases: sqlalchemy.schema._CreateDropBase

Represent a DROP SEQUENCE statement.

class sqlalchemy.schema.CreateIndex(element, on=None, bind=None)

Bases: sqlalchemy.schema._CreateDropBase

Represent a CREATE INDEX statement.

class sqlalchemy.schema.DropIndex(element, on=None, bind=None)

Bases: sqlalchemy.schema._CreateDropBase

Represent a DROP INDEX statement.

class sqlalchemy.schema.AddConstraint(element, *args, **kw)

Bases: sqlalchemy.schema._CreateDropBase

Represent an ALTER TABLE ADD CONSTRAINT statement.

__init__(element, *args, **kw)
class sqlalchemy.schema.DropConstraint(element, cascade=False, **kw)

Bases: sqlalchemy.schema._CreateDropBase

Represent an ALTER TABLE DROP CONSTRAINT statement.

__init__(element, cascade=False, **kw)

Internals

class sqlalchemy.schema.SchemaItem

Bases: sqlalchemy.sql.visitors.Visitable

Base class for items that define a database schema.

get_children(**kwargs)
used to allow SchemaVisitor access
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