Release: 0.8.7 | Release Date: July 22, 2014

SQLAlchemy 0.8 Documentation

Defining Constraints and Indexes

This section will discuss SQL constraints and indexes. In SQLAlchemy the key classes include ForeignKeyConstraint and Index.

Defining Foreign Keys

A foreign key in SQL is a table-level construct that constrains one or more columns in that table to only allow values that are present in a different set of columns, typically but not always located on a different table. We call the columns which are constrained the foreign key columns and the columns which they are constrained towards the referenced columns. The referenced columns almost always define the primary key for their owning table, though there are exceptions to this. The foreign key is the “joint” that connects together pairs of rows which have a relationship with each other, and SQLAlchemy assigns very deep importance to this concept in virtually every area of its operation.

In SQLAlchemy as well as in DDL, foreign key constraints can be defined as additional attributes within the table clause, or for single-column foreign keys they may optionally be specified within the definition of a single column. The single column foreign key is more common, and at the column level is specified by constructing a ForeignKey object as an argument to a Column object:

user_preference = Table('user_preference', metadata,
    Column('pref_id', Integer, primary_key=True),
    Column('user_id', Integer, ForeignKey("user.user_id"), nullable=False),
    Column('pref_name', String(40), nullable=False),
    Column('pref_value', String(100))
)

Above, we define a new table user_preference for which each row must contain a value in the user_id column that also exists in the user table’s user_id column.

The argument to ForeignKey is most commonly a string of the form <tablename>.<columnname>, or for a table in a remote schema or “owner” of the form <schemaname>.<tablename>.<columnname>. It may also be an actual Column object, which as we’ll see later is accessed from an existing Table object via its c collection:

ForeignKey(user.c.user_id)

The advantage to using a string is that the in-python linkage between user and user_preference is resolved only when first needed, so that table objects can be easily spread across multiple modules and defined in any order.

Foreign keys may also be defined at the table level, using the ForeignKeyConstraint object. This object can describe a single- or multi-column foreign key. A multi-column foreign key is known as a composite foreign key, and almost always references a table that has a composite primary key. Below we define a table invoice which has a composite primary key:

invoice = Table('invoice', metadata,
    Column('invoice_id', Integer, primary_key=True),
    Column('ref_num', Integer, primary_key=True),
    Column('description', String(60), nullable=False)
)

And then a table invoice_item with a composite foreign key referencing invoice:

invoice_item = Table('invoice_item', metadata,
    Column('item_id', Integer, primary_key=True),
    Column('item_name', String(60), nullable=False),
    Column('invoice_id', Integer, nullable=False),
    Column('ref_num', Integer, nullable=False),
    ForeignKeyConstraint(['invoice_id', 'ref_num'], ['invoice.invoice_id', 'invoice.ref_num'])
)

It’s important to note that the ForeignKeyConstraint is the only way to define a composite foreign key. While we could also have placed individual ForeignKey objects on both the invoice_item.invoice_id and invoice_item.ref_num columns, SQLAlchemy would not be aware that these two values should be paired together - it would be two individual foreign key constraints instead of a single composite foreign key referencing two columns.

Creating/Dropping Foreign Key Constraints via ALTER

In all the above examples, the ForeignKey object causes the “REFERENCES” keyword to be added inline to a column definition within a “CREATE TABLE” statement when create_all() is issued, and ForeignKeyConstraint invokes the “CONSTRAINT” keyword inline with “CREATE TABLE”. There are some cases where this is undesireable, particularly when two tables reference each other mutually, each with a foreign key referencing the other. In such a situation at least one of the foreign key constraints must be generated after both tables have been built. To support such a scheme, ForeignKey and ForeignKeyConstraint offer the flag use_alter=True. When using this flag, the constraint will be generated using a definition similar to “ALTER TABLE <tablename> ADD CONSTRAINT <name> ...”. Since a name is required, the name attribute must also be specified. For example:

node = Table('node', meta,
    Column('node_id', Integer, primary_key=True),
    Column('primary_element', Integer,
        ForeignKey('element.element_id', use_alter=True, name='fk_node_element_id')
    )
)

element = Table('element', meta,
    Column('element_id', Integer, primary_key=True),
    Column('parent_node_id', Integer),
    ForeignKeyConstraint(
        ['parent_node_id'],
        ['node.node_id'],
        use_alter=True,
        name='fk_element_parent_node_id'
    )
)

ON UPDATE and ON DELETE

Most databases support cascading of foreign key values, that is the when a parent row is updated the new value is placed in child rows, or when the parent row is deleted all corresponding child rows are set to null or deleted. In data definition language these are specified using phrases like “ON UPDATE CASCADE”, “ON DELETE CASCADE”, and “ON DELETE SET NULL”, corresponding to foreign key constraints. The phrase after “ON UPDATE” or “ON DELETE” may also other allow other phrases that are specific to the database in use. The ForeignKey and ForeignKeyConstraint objects support the generation of this clause via the onupdate and ondelete keyword arguments. The value is any string which will be output after the appropriate “ON UPDATE” or “ON DELETE” phrase:

child = Table('child', meta,
    Column('id', Integer,
            ForeignKey('parent.id', onupdate="CASCADE", ondelete="CASCADE"),
            primary_key=True
    )
)

composite = Table('composite', meta,
    Column('id', Integer, primary_key=True),
    Column('rev_id', Integer),
    Column('note_id', Integer),
    ForeignKeyConstraint(
                ['rev_id', 'note_id'],
                ['revisions.id', 'revisions.note_id'],
                onupdate="CASCADE", ondelete="SET NULL"
    )
)

Note that these clauses are not supported on SQLite, and require InnoDB tables when used with MySQL. They may also not be supported on other databases.

UNIQUE Constraint

Unique constraints can be created anonymously on a single column using the unique keyword on Column. Explicitly named unique constraints and/or those with multiple columns are created via the UniqueConstraint table-level construct.

meta = MetaData()
mytable = Table('mytable', meta,

    # per-column anonymous unique constraint
    Column('col1', Integer, unique=True),

    Column('col2', Integer),
    Column('col3', Integer),

    # explicit/composite unique constraint.  'name' is optional.
    UniqueConstraint('col2', 'col3', name='uix_1')
    )

CHECK Constraint

Check constraints can be named or unnamed and can be created at the Column or Table level, using the CheckConstraint construct. The text of the check constraint is passed directly through to the database, so there is limited “database independent” behavior. Column level check constraints generally should only refer to the column to which they are placed, while table level constraints can refer to any columns in the table.

Note that some databases do not actively support check constraints such as MySQL.

meta = MetaData()
mytable = Table('mytable', meta,

    # per-column CHECK constraint
    Column('col1', Integer, CheckConstraint('col1>5')),

    Column('col2', Integer),
    Column('col3', Integer),

    # table level CHECK constraint.  'name' is optional.
    CheckConstraint('col2 > col3 + 5', name='check1')
    )

sqlmytable.create(engine)

Setting up Constraints when using the Declarative ORM Extension

The Table is the SQLAlchemy Core construct that allows one to define table metadata, which among other things can be used by the SQLAlchemy ORM as a target to map a class. The Declarative extension allows the Table object to be created automatically, given the contents of the table primarily as a mapping of Column objects.

To apply table-level constraint objects such as ForeignKeyConstraint to a table defined using Declarative, use the __table_args__ attribute, described at Table Configuration.

Constraints API

class sqlalchemy.schema.Constraint(name=None, deferrable=None, initially=None, _create_rule=None, **kw)

Bases: sqlalchemy.schema.SchemaItem

A table-level SQL constraint.

class sqlalchemy.schema.CheckConstraint(sqltext, name=None, deferrable=None, initially=None, table=None, _create_rule=None, _autoattach=True)

Bases: sqlalchemy.schema.Constraint

A table- or column-level CHECK constraint.

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

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

Bases: sqlalchemy.schema.ColumnCollectionMixin, sqlalchemy.schema.Constraint

A constraint that proxies a ColumnCollection.

class sqlalchemy.schema.ForeignKey(column, _constraint=None, use_alter=False, name=None, onupdate=None, ondelete=None, deferrable=None, schema=None, initially=None, link_to_name=False, match=None)

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

__init__(column, _constraint=None, use_alter=False, name=None, onupdate=None, ondelete=None, deferrable=None, schema=None, initially=None, link_to_name=False, match=None)

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.

    New in version 0.7.4: Note that if the schema name is not included, and the underlying MetaData has a “schema”, that value will be 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.
  • match – Optional string. If set, emit MATCH <value> when issuing DDL for this constraint. Typical values include SIMPLE, PARTIAL and FULL.
  • schema – Deprecated; this flag does nothing and will be removed in 0.9.
column

Return the target Column referenced by this ForeignKey.

If this ForeignKey was created using a string-based target column specification, this attribute will on first access initiate a resolution process to locate the referenced remote Column. The resolution process traverses to the parent Column, Table, and MetaData to proceed - if any of these aren’t yet present, an error is raised.

copy(schema=None)

Produce a copy of this ForeignKey object.

The new ForeignKey will not be bound to any Column.

This method is usually used by the internal copy procedures of Column, Table, and MetaData.

Parameters:schema – The returned ForeignKey will reference the original table and column name, qualified by the given string schema name.
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

Return a string based ‘column specification’ for this ForeignKey.

This is usually the equivalent of the string-based “tablename.colname” argument first passed to the object’s constructor.

class sqlalchemy.schema.ForeignKeyConstraint(columns, refcolumns, name=None, onupdate=None, ondelete=None, deferrable=None, initially=None, use_alter=False, link_to_name=False, match=None, 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 metadata_foreignkeys.

__init__(columns, refcolumns, name=None, onupdate=None, ondelete=None, deferrable=None, initially=None, use_alter=False, link_to_name=False, match=None, 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.
  • match – Optional string. If set, emit MATCH <value> when issuing DDL for this constraint. Typical values include SIMPLE, PARTIAL and FULL.
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.

Indexes

Indexes can be created anonymously (using an auto-generated name ix_<column label>) for a single column using the inline index keyword on Column, which also modifies the usage of unique to apply the uniqueness to the index itself, instead of adding a separate UNIQUE constraint. For indexes with specific names or which encompass more than one column, use the Index construct, which requires a name.

Below we illustrate a Table with several Index objects associated. The DDL for “CREATE INDEX” is issued right after the create statements for the table:

meta = MetaData()
mytable = Table('mytable', meta,
    # an indexed column, with index "ix_mytable_col1"
    Column('col1', Integer, index=True),

    # a uniquely indexed column with index "ix_mytable_col2"
    Column('col2', Integer, index=True, unique=True),

    Column('col3', Integer),
    Column('col4', Integer),

    Column('col5', Integer),
    Column('col6', Integer),
    )

# place an index on col3, col4
Index('idx_col34', mytable.c.col3, mytable.c.col4)

# place a unique index on col5, col6
Index('myindex', mytable.c.col5, mytable.c.col6, unique=True)

sqlmytable.create(engine)

Note in the example above, the Index construct is created externally to the table which it corresponds, using Column objects directly. Index also supports “inline” definition inside the Table, using string names to identify columns:

meta = MetaData()
mytable = Table('mytable', meta,
    Column('col1', Integer),

    Column('col2', Integer),

    Column('col3', Integer),
    Column('col4', Integer),

    # place an index on col1, col2
    Index('idx_col12', 'col1', 'col2'),

    # place a unique index on col3, col4
    Index('idx_col34', 'col3', 'col4', unique=True)
)

New in version 0.7: Support of “inline” definition inside the Table for Index.

The Index object also supports its own create() method:

i = Index('someindex', mytable.c.col5)
sqli.create(engine)

Functional Indexes

Index supports SQL and function expressions, as supported by the target backend. To create an index against a column using a descending value, the ColumnElement.desc() modifier may be used:

from sqlalchemy import Index

Index('someindex', mytable.c.somecol.desc())

Or with a backend that supports functional indexes such as Postgresql, a “case insensitive” index can be created using the lower() function:

from sqlalchemy import func, Index

Index('someindex', func.lower(mytable.c.somecol))

New in version 0.8: Index supports SQL expressions and functions as well as plain columns.

Index API

class sqlalchemy.schema.Index(name, *expressions, **kw)

Bases: sqlalchemy.schema.ColumnCollectionMixin, sqlalchemy.schema.SchemaItem

A table-level INDEX.

Defines a composite (one or more column) INDEX.

E.g.:

sometable = Table("sometable", metadata,
                Column("name", String(50)),
                Column("address", String(100))
            )

Index("some_index", sometable.c.name)

For a no-frills, single column index, adding Column also supports index=True:

sometable = Table("sometable", metadata,
                Column("name", String(50), index=True)
            )

For a composite index, multiple columns can be specified:

Index("some_index", sometable.c.name, sometable.c.address)

Functional indexes are supported as well, keeping in mind that at least one Column must be present:

Index("some_index", func.lower(sometable.c.name))

New in version 0.8: support for functional and expression-based indexes.

See also

Indexes - General information on Index.

Postgresql-Specific Index Options - PostgreSQL-specific options available for the Index construct.

MySQL Specific Index Options - MySQL-specific options available for the Index construct.

MSSQL-Specific Index Options - MSSQL-specific options available for the Index construct.

__init__(name, *expressions, **kw)

Construct an index object.

Parameters:
  • name – The name of the index
  • *expressions – Column or SQL expressions.
  • unique – Defaults to False: create a unique index.
  • **kw – Other keyword arguments may be interpreted by specific dialects.
bind

Return the connectable associated with this Index.

create(bind=None)

Issue a CREATE statement for this Index, using the given Connectable for connectivity.

drop(bind=None)

Issue a DROP statement for this Index, using the given Connectable for connectivity.