Customizing DDL

    Custom DDL phrases are most easily achieved using the DDL construct. This construct works like all the other DDL elements except it accepts a string which is the text to be emitted:

    A more comprehensive method of creating libraries of DDL constructs is to use custom compilation - see for details.

    The DDL construct introduced previously also has the ability to be invoked conditionally based on inspection of the database. This feature is available using the method. For example, if we wanted to create a trigger but only on the PostgreSQL backend, we could invoke this as:

    1. mytable = Table(
    2. 'mytable', metadata,
    3. Column('id', Integer, primary_key=True),
    4. Column('data', String(50))
    5. )
    6. func = DDL(
    7. "CREATE FUNCTION my_func() "
    8. "RETURNS TRIGGER AS $$ "
    9. "BEGIN "
    10. "NEW.data := 'ins'; "
    11. "RETURN NEW; "
    12. "END; $$ LANGUAGE PLPGSQL"
    13. )
    14. trigger = DDL(
    15. "CREATE TRIGGER dt_ins BEFORE INSERT ON mytable "
    16. "FOR EACH ROW EXECUTE PROCEDURE my_func();"
    17. )
    18. event.listen(
    19. mytable,
    20. 'after_create',
    21. func.execute_if(dialect='postgresql')
    22. )
    23. event.listen(
    24. mytable,
    25. 'after_create',
    26. trigger.execute_if(dialect='postgresql')
    27. )

    The DDLElement.execute_if.dialect keyword also accepts a tuple of string dialect names:

    1. event.listen(
    2. mytable,
    3. "after_create",
    4. trigger.execute_if(dialect=('postgresql', 'mysql'))
    5. )
    6. event.listen(
    7. mytable,
    8. "before_drop",
    9. trigger.execute_if(dialect=('postgresql', 'mysql'))
    10. )

    The method can also work against a callable function that will receive the database connection in use. In the example below, we use this to conditionally create a CHECK constraint, first looking within the PostgreSQL catalogs to see if it exists:

    1. def should_create(ddl, target, connection, **kw):
    2. row = connection.execute(
    3. "select conname from pg_constraint where conname='%s'" %
    4. ddl.element.name).scalar()
    5. return not bool(row)
    6. def should_drop(ddl, target, connection, **kw):
    7. return not should_create(ddl, target, connection, **kw)
    8. event.listen(
    9. users,
    10. "after_create",
    11. DDL(
    12. "ALTER TABLE users ADD CONSTRAINT "
    13. "cst_user_name_length CHECK (length(user_name) >= 8)"
    14. ).execute_if(callable_=should_create)
    15. )
    16. event.listen(
    17. users,
    18. "before_drop",
    19. DDL(
    20. "ALTER TABLE users DROP CONSTRAINT cst_user_name_length"
    21. ).execute_if(callable_=should_drop)
    22. )
    23. sqlusers.create(engine)
    24. CREATE TABLE users (
    25. user_id SERIAL NOT NULL,
    26. user_name VARCHAR(40) NOT NULL,
    27. PRIMARY KEY (user_id)
    28. )
    29. select conname from pg_constraint where conname='cst_user_name_length'
    30. ALTER TABLE users ADD CONSTRAINT cst_user_name_length CHECK (length(user_name) >= 8)
    31. sqlusers.drop(engine)
    32. select conname from pg_constraint where conname='cst_user_name_length'
    33. ALTER TABLE users DROP CONSTRAINT cst_user_name_length
    34. DROP TABLE users

    The sqlalchemy.schema package contains SQL expression constructs that provide DDL expressions. For example, to produce a CREATE TABLE statement:

    1. from sqlalchemy.schema import CreateTable
    2. with engine.connect() as conn:
    3. sql conn.execute(CreateTable(mytable))
    4. CREATE TABLE mytable (
    5. col1 INTEGER,
    6. col2 INTEGER,
    7. col3 INTEGER,
    8. col4 INTEGER,
    9. col5 INTEGER,
    10. col6 INTEGER
    11. )

    Above, the CreateTable construct works like any other expression construct (such as select(), table.insert(), etc.). All of SQLAlchemy’s DDL oriented constructs are subclasses of the base class; this is the base of all the objects corresponding to CREATE and DROP as well as ALTER, not only in SQLAlchemy but in Alembic Migrations as well. A full reference of available constructs is in DDL Expression Constructs API.

    User-defined DDL constructs may also be created as subclasses of itself. The documentation in Custom SQL Constructs and Compilation Extension has several examples of this.

    The event-driven DDL system described in the previous section is available with other DDLElement objects as well. However, when dealing with the built-in constructs such as , CreateSequence, etc, the event system is of limited use, as methods like and MetaData.create_all() will invoke these constructs unconditionally. In a future SQLAlchemy release, the DDL event system including conditional execution will taken into account for built-in constructs that currently invoke in all cases.

    We can illustrate an event-driven example with the and DropConstraint constructs, as the event-driven system will work for CHECK and UNIQUE constraints, using these as we did in our previous example of :

    1. row = connection.execute(
    2. "select conname from pg_constraint where conname='%s'" %
    3. ddl.element.name).scalar()
    4. return not bool(row)
    5. def should_drop(ddl, target, connection, **kw):
    6. return not should_create(ddl, target, connection, **kw)
    7. event.listen(
    8. users,
    9. "after_create",
    10. AddConstraint(constraint).execute_if(callable_=should_create)
    11. )
    12. event.listen(
    13. users,
    14. "before_drop",
    15. DropConstraint(constraint).execute_if(callable_=should_drop)
    16. )
    17. sqlusers.create(engine)
    18. CREATE TABLE users (
    19. user_id SERIAL NOT NULL,
    20. user_name VARCHAR(40) NOT NULL,
    21. PRIMARY KEY (user_id)
    22. )
    23. select conname from pg_constraint where conname='cst_user_name_length'
    24. ALTER TABLE users ADD CONSTRAINT cst_user_name_length CHECK (length(user_name) >= 8)
    25. sqlusers.drop(engine)
    26. select conname from pg_constraint where conname='cst_user_name_length'
    27. ALTER TABLE users DROP CONSTRAINT cst_user_name_length
    28. DROP TABLE users

    While the above example is against the built-in AddConstraint and objects, the main usefulness of DDL events for now remains focused on the use of the DDL construct itself, as well as with user-defined subclasses of that aren’t already part of the MetaData.create_all(), , and corresponding “drop” processes.

    function sqlalchemy.schema.``sort_tables(tables, skip_fn=None, extra_dependencies=None)

    Sort a collection of Table objects based on dependency.

    This is a dependency-ordered sort which will emit objects such that they will follow their dependent Table objects. Tables are dependent on another based on the presence of objects as well as explicit dependencies added by Table.add_is_dependent_on().

    Warning

    The function cannot by itself accommodate automatic resolution of dependency cycles between tables, which are usually caused by mutually dependent foreign key constraints. When these cycles are detected, the foreign keys of these tables are omitted from consideration in the sort. A warning is emitted when this condition occurs, which will be an exception raise in a future release. Tables which are not part of the cycle will still be returned in dependency order.

    To resolve these cycles, the ForeignKeyConstraint.use_alter parameter may be applied to those constraints which create a cycle. Alternatively, the function will automatically return foreign key constraints in a separate collection when cycles are detected so that they may be applied to a schema separately.

    Changed in version 1.3.17: - a warning is emitted when sort_tables() cannot perform a proper sort due to cyclical dependencies. This will be an exception in a future release. Additionally, the sort will continue to return other tables not involved in the cycle in dependency order which was not the case previously.

    • Parameters

      • tables – a sequence of objects.

      • skip_fn – optional callable which will be passed a ForeignKey object; if it returns True, this constraint will not be considered as a dependency. Note this is different from the same parameter in , which is instead passed the owning ForeignKeyConstraint object.

      • extra_dependencies – a sequence of 2-tuples of tables which will also be considered as dependent on each other.

    See also

    MetaData.sorted_tables - uses this function to sort

    function sqlalchemy.schema.``sort_tables_and_constraints(tables, filter_fn=None, extra_dependencies=None, _warn_for_cycles=False)

    Sort a collection of / ForeignKeyConstraint objects.

    This is a dependency-ordered sort which will emit tuples of (Table, [ForeignKeyConstraint, ...]) such that each follows its dependent Table objects. Remaining objects that are separate due to dependency rules not satisfied by the sort are emitted afterwards as (None, [ForeignKeyConstraint ...]).

    Tables are dependent on another based on the presence of ForeignKeyConstraint objects, explicit dependencies added by , as well as dependencies stated here using the sort_tables_and_constraints.skip_fn and/or parameters.

    • Parameters

      • tables – a sequence of Table objects.

      • filter_fn – optional callable which will be passed a object, and returns a value based on whether this constraint should definitely be included or excluded as an inline constraint, or neither. If it returns False, the constraint will definitely be included as a dependency that cannot be subject to ALTER; if True, it will only be included as an ALTER result at the end. Returning None means the constraint is included in the table-based result unless it is detected as part of a dependency cycle.

      • extra_dependencies – a sequence of 2-tuples of tables which will also be considered as dependent on each other.

    New in version 1.0.0.

    See also

    sort_tables()

    class sqlalchemy.schema.``DDLElement

    Base class for DDL expression constructs.

    This class is the base for the general purpose class, as well as the various create/drop clause constructs such as CreateTable, , AddConstraint, etc.

    integrates closely with SQLAlchemy events, introduced in Events. An instance of one is itself an event receiving callable:

    1. event.listen(
    2. users,
    3. 'after_create',
    4. AddConstraint(constraint).execute_if(dialect='postgresql')
    5. )

    See also

    DDLEvents

    Class signature

    class sqlalchemy.schema.DDLElement (sqlalchemy.sql.roles.DDLRole, , sqlalchemy.schema._DDLCompiles)

    • method sqlalchemy.schema.DDLElement.__call__(target, bind, \*kw*)

      Execute the DDL as a ddl_listener.

    • method against(target)

      Return a copy of this DDLElement which will include the given target.

      This essentially applies the given item to the .target attribute of the returned object. This target is then usable by event handlers and compilation routines in order to provide services such as tokenization of a DDL string in terms of a particular Table.

      When a object is established as an event handler for the DDLEvents.before_create() or events, and the event then occurs for a given target such as a Constraint or , that target is established with a copy of the DDLElement object using this method, which then proceeds to the method in order to invoke the actual DDL instruction.

      • Parameters

        target – a SchemaItem that will be the subject of a DDL operation.

        Returns

        a copy of this with the .target attribute assigned to the given SchemaItem.

      See also

      - uses tokenization against the “target” when processing the DDL string.

    • attribute sqlalchemy.schema.DDLElement.bind

    • attribute callable_ = None

    • attribute sqlalchemy.schema.DDLElement.dialect = None

    • method execute(bind=None, target=None)

      Execute this DDL immediately.

      Deprecated since version 1.4: The DDLElement.execute() method is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. All statement execution in SQLAlchemy 2.0 is performed by the method of Connection, or in the ORM by the method of Session. (Background on SQLAlchemy 2.0 at: )

      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.

      • Parameters

        • 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. This is equivalent to passing the to the DDLElement.against() method and then invoking upon the resulting DDLElement object. See for further detail.

    • method sqlalchemy.schema.DDLElement.execute_if(dialect=None, callable_=None, state=None)

      Return a callable that will execute this conditionally within an event handler.

      Used to provide a wrapper for event listening:

      • Parameters

        • dialect

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

          1. DDL('something').execute_if(dialect='postgresql')

          If a tuple, specifies multiple dialect names:

          1. DDL('something').execute_if(dialect=('postgresql', 'mysql'))
        • callable_

          A callable, which will be invoked with four positional arguments as well as optional keyword arguments:

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

        • state – any value which will be passed to the callable_ as the state keyword argument.

    1. See also
    2. [`DDLEvents`]($db915629bc58de5f.md#sqlalchemy.events.DDLEvents "sqlalchemy.events.DDLEvents")
    3. [Events]($c14d75f7aa5f8339.md)

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

    A literal DDL statement.

    Specifies literal SQL DDL to be executed by the database. DDL objects function as DDL event listeners, and can be subscribed to those events listed in DDLEvents, using either or MetaData objects as targets. Basic templating support allows a single DDL instance to handle repetitive tasks for multiple tables.

    Examples:

    1. from sqlalchemy import event, DDL
    2. tbl = Table('users', metadata, Column('uid', Integer))
    3. event.listen(tbl, 'before_create', DDL('DROP TRIGGER users_trigger'))
    4. spow = DDL('ALTER TABLE %(table)s SET secretpowers TRUE')
    5. event.listen(tbl, 'after_create', spow.execute_if(dialect='somedb'))
    6. drop_spow = DDL('ALTER TABLE users SET secretpowers FALSE')
    7. connection.execute(drop_spow)

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

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

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

    Class signature

    class (sqlalchemy.schema.DDLElement)

    • method __init__(statement, context=None, bind=None)

      Create a DDL statement.

      • Parameters

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

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

          Deprecated since version 1.4: The DDL.bind argument is deprecated and will be removed in SQLAlchemy 2.0.

    1. See also
    2. [`DDLEvents`]($db915629bc58de5f.md#sqlalchemy.events.DDLEvents "sqlalchemy.events.DDLEvents")
    3. [Events]($c14d75f7aa5f8339.md)

    class sqlalchemy.schema.``_CreateDropBase(element, bind=None, if_exists=False, if_not_exists=False, _legacy_bind=None)

    Base class for DDL constructs that represent CREATE and DROP or equivalents.

    The common theme of _CreateDropBase is a single element attribute which refers to the element to be created or dropped.

    Class signature

    class sqlalchemy.schema._CreateDropBase ()

    class sqlalchemy.schema.``CreateTable(element, bind=None, include_foreign_key_constraints=None, if_not_exists=False)

    Represent a CREATE TABLE statement.

    Class signature

    • method sqlalchemy.schema.CreateTable.__init__(element, bind=None, include_foreign_key_constraints=None, if_not_exists=False)

      Create a construct.

      • Parameters

        • on – See the description for ‘on’ in DDL.

        • bind – See the description for ‘bind’ in .

    class sqlalchemy.schema.``DropTable(element, bind=None, if_exists=False)

    Represent a DROP TABLE statement.

    Class signature

    class sqlalchemy.schema.DropTable (sqlalchemy.schema._CreateDropBase)

    • method __init__(element, bind=None, if_exists=False)

      Create a DropTable construct.

      • Parameters

        • element – a that’s the subject of the DROP.

        • on – See the description for ‘on’ in DDL.

        • bind – See the description for ‘bind’ in .

    1. Deprecated since version 1.4: The [`DropTable.bind`](#sqlalchemy.schema.DropTable.params.bind "sqlalchemy.schema.DropTable") argument is deprecated and will be removed in SQLAlchemy 2.0.
    2. - Parameters
    3. **if\_exists**
    4. if True, an IF EXISTS operator will be applied to the construct.
    5. New in version 1.4.0b2.

    class sqlalchemy.schema.``CreateColumn(element)

    Represent a Column as rendered in a CREATE TABLE statement, via the construct.

    This is provided to support custom column DDL within the generation of CREATE TABLE statements, by using the compiler extension documented in Custom SQL Constructs and Compilation Extension to extend .

    Typical integration is to examine the incoming Column object, and to redirect compilation if a particular flag or condition is found:

    1. from sqlalchemy import schema
    2. from sqlalchemy.ext.compiler import compiles
    3. @compiles(schema.CreateColumn)
    4. def compile(element, compiler, **kw):
    5. column = element.element
    6. if "special" not in column.info:
    7. return compiler.visit_create_column(element, **kw)
    8. text = "%s SPECIAL DIRECTIVE %s" % (
    9. column.name,
    10. compiler.type_compiler.process(column.type)
    11. )
    12. default = compiler.get_column_default_string(column)
    13. if default is not None:
    14. text += " DEFAULT " + default
    15. if not column.nullable:
    16. text += " NOT NULL"
    17. if column.constraints:
    18. text += " ".join(
    19. compiler.process(const)
    20. for const in column.constraints)
    21. return text

    The above construct can be applied to a as follows:

    1. from sqlalchemy import Table, Metadata, Column, Integer, String
    2. from sqlalchemy import schema
    3. metadata = MetaData()
    4. table = Table('mytable', MetaData(),
    5. Column('x', Integer, info={"special":True}, primary_key=True),
    6. Column('y', String(50)),
    7. Column('z', String(20), info={"special":True})
    8. )
    9. metadata.create_all(conn)

    Above, the directives we’ve added to the Column.info collection will be detected by our custom compilation scheme:

    1. CREATE TABLE mytable (
    2. x SPECIAL DIRECTIVE INTEGER NOT NULL,
    3. y VARCHAR(50),
    4. z SPECIAL DIRECTIVE VARCHAR(20),
    5. PRIMARY KEY (x)
    6. )

    The construct can also be used to skip certain columns when producing a CREATE TABLE. This is accomplished by creating a compilation rule that conditionally returns None. This is essentially how to produce the same effect as using the system=True argument on Column, which marks a column as an implicitly-present “system” column.

    For example, suppose we wish to produce a which skips rendering of the PostgreSQL xmin column against the PostgreSQL backend, but on other backends does render it, in anticipation of a triggered rule. A conditional compilation rule could skip this name only on PostgreSQL:

    1. from sqlalchemy.schema import CreateColumn
    2. @compiles(CreateColumn, "postgresql")
    3. def skip_xmin(element, compiler, **kw):
    4. if element.element.name == 'xmin':
    5. return None
    6. else:
    7. return compiler.visit_create_column(element, **kw)
    8. my_table = Table('mytable', metadata,
    9. Column('id', Integer, primary_key=True),
    10. Column('xmin', Integer)
    11. )

    Above, a CreateTable construct will generate a CREATE TABLE which only includes the id column in the string; the xmin column will be omitted, but only against the PostgreSQL backend.

    Class signature

    class (sqlalchemy.schema._DDLCompiles)

    class sqlalchemy.schema.``CreateSequence(element, bind=None, if_exists=False, if_not_exists=False, _legacy_bind=None)

    Represent a CREATE SEQUENCE statement.

    Class signature

    class sqlalchemy.schema.CreateSequence (sqlalchemy.schema._CreateDropBase)

    class sqlalchemy.schema.``DropSequence(element, bind=None, if_exists=False, if_not_exists=False, _legacy_bind=None)

    Represent a DROP SEQUENCE statement.

    Class signature

    class (sqlalchemy.schema._CreateDropBase)

    class sqlalchemy.schema.``CreateIndex(element, bind=None, if_not_exists=False)

    Represent a CREATE INDEX statement.

    Class signature

    class sqlalchemy.schema.CreateIndex (sqlalchemy.schema._CreateDropBase)

    • method __init__(element, bind=None, if_not_exists=False)

      Create a Createindex construct.

      • Parameters

        • element – a Index that’s the subject of the CREATE.

        • on – See the description for ‘on’ in .

        • bind – See the description for ‘bind’ in DDL.

    1. Deprecated since version 1.4: The [`CreateIndex.bind`](#sqlalchemy.schema.CreateIndex.params.bind "sqlalchemy.schema.CreateIndex") argument is deprecated and will be removed in SQLAlchemy 2.0.
    2. - Parameters
    3. **if\_not\_exists**
    4. if True, an IF NOT EXISTS operator will be applied to the construct.
    5. New in version 1.4.0b2.

    class sqlalchemy.schema.``DropIndex(element, bind=None, if_exists=False)

    Represent a DROP INDEX statement.

    Class signature

    class (sqlalchemy.schema._CreateDropBase)

    • method sqlalchemy.schema.DropIndex.__init__(element, bind=None, if_exists=False)

      Create a construct.

      • Parameters

        • element – a Index that’s the subject of the DROP.

        • on – See the description for ‘on’ in .

        • bind – See the description for ‘bind’ in DDL.

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

    Represent an ALTER TABLE ADD CONSTRAINT statement.

    Class signature

    class (sqlalchemy.schema._CreateDropBase)

    class sqlalchemy.schema.``DropConstraint(element, cascade=False, \*kw*)

    Represent an ALTER TABLE DROP CONSTRAINT statement.

    Class signature

    class sqlalchemy.schema.DropConstraint (sqlalchemy.schema._CreateDropBase)

    class sqlalchemy.schema.``CreateSchema(name, quote=None, \*kw*)

    Represent a CREATE SCHEMA statement.

    The argument here is the string name of the schema.

    Class signature

    class (sqlalchemy.schema._CreateDropBase)

    class sqlalchemy.schema.``DropSchema(name, quote=None, cascade=False, \*kw*)

    Represent a DROP SCHEMA statement.

    The argument here is the string name of the schema.

    Class signature

    class sqlalchemy.schema.DropSchema (sqlalchemy.schema._CreateDropBase)

    • method __init__(name, quote=None, cascade=False, \*kw*)