Customizing DDL

これまでのセクションでは、 TableForeignKeyConstraintCheckConstraint 、および Sequence など、さまざまなスキーマ構成体について説明してきました。これまでずっと、 Table および MetaDatacreate() および create_all() メソッドを利用して、すべての構成体に対してデータ定義言語(DDL)を発行してきました。発行されると、事前に決定された操作の順序が呼び出され、各テーブルを作成するためのDDLが、すべての制約とそれに関連付けられた他のオブジェクトを含めて無条件に作成されます。データベース固有のDDLが必要とされるより複雑なシナリオでは、SQLAlchemyは、テーブルの標準生成に付随して、またはそれ自体で、任意の条件に基づいて任意のDDLを追加するために使用できる2つの手法を提供します。

Custom DDL

カスタムDDLフレーズは、 DDL 構文を使うと簡単に実現できます。この構文は他のDDL要素と同じように動作しますが、出力されるテキストである文字列を受け付ける点が異なります:

event.listen(
    metadata,
    "after_create",
    DDL(
        "ALTER TABLE users ADD CONSTRAINT "
        "cst_user_name_length "
        " CHECK (length(user_name) >= 8)"
    ),
)

DDL構文のライブラリを作成するより包括的な方法は、カスタムコンパイルを使用することです。詳細は Custom SQL Constructs and Compilation Extension を参照してください:

Controlling DDL Sequences

前に紹介した DDL 構文にも、データベースの検査に基づいて条件付きで呼び出す機能があります。この機能は ExecutableDDLElement.execute_if() メソッドを使用して利用できます。例えば、PostgreSQLバックエンド上でのみトリガを作成したい場合、次のように呼び出すことができます:

mytable = Table(
    "mytable",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("data", String(50)),
)

func = DDL(
    "CREATE FUNCTION my_func() "
    "RETURNS TRIGGER AS $$ "
    "BEGIN "
    "NEW.data := 'ins'; "
    "RETURN NEW; "
    "END; $$ LANGUAGE PLPGSQL"
)

trigger = DDL(
    "CREATE TRIGGER dt_ins BEFORE INSERT ON mytable "
    "FOR EACH ROW EXECUTE PROCEDURE my_func();"
)

event.listen(mytable, "after_create", func.execute_if(dialect="postgresql"))

event.listen(mytable, "after_create", trigger.execute_if(dialect="postgresql"))

ExecutableDDLElement.execute_if.dialect キーワードは、タプルの文字列のダイアレクト名も受け付けます:

event.listen(
    mytable, "after_create", trigger.execute_if(dialect=("postgresql", "mysql"))
)
event.listen(
    mytable, "before_drop", trigger.execute_if(dialect=("postgresql", "mysql"))
)

ExecutableDDLElement.execute_if() メソッドは、使用中のデータベース接続を受け取る呼び出し可能な関数に対しても動作します。以下の例では、これを使用して条件付きでCHECK制約を作成し、まずPostgreSQLカタログ内を調べて存在するかどうかを確認します:

def should_create(ddl, target, connection, **kw):
    row = connection.execute(
        "select conname from pg_constraint where conname='%s'" % ddl.element.name
    ).scalar()
    return not bool(row)

def should_drop(ddl, target, connection, **kw):
    return not should_create(ddl, target, connection, **kw)

event.listen(
    users,
    "after_create",
    DDL(
        "ALTER TABLE users ADD CONSTRAINT "
        "cst_user_name_length CHECK (length(user_name) >= 8)"
    ).execute_if(callable_=should_create),
)
event.listen(
    users,
    "before_drop",
    DDL("ALTER TABLE users DROP CONSTRAINT cst_user_name_length").execute_if(
        callable_=should_drop
    ),
)

users.create(engine)
CREATE TABLE users ( user_id SERIAL NOT NULL, user_name VARCHAR(40) NOT NULL, PRIMARY KEY (user_id) ) SELECT conname FROM pg_constraint WHERE conname='cst_user_name_length' ALTER TABLE users ADD CONSTRAINT cst_user_name_length CHECK (length(user_name) >= 8)
users.drop(engine)
SELECT conname FROM pg_constraint WHERE conname='cst_user_name_length' ALTER TABLE users DROP CONSTRAINT cst_user_name_length DROP TABLE users

Using the built-in DDLElement Classes

sqlalchemy.schema パッケージには、DDL式を提供するSQL式の構成体が含まれています。これらはすべて、共通のベース ExecutableDDLElement から拡張されています。例えば、 CreateTable 文を生成するには、 CreateTable 構成体を使用できます。

from sqlalchemy.schema import CreateTable

with engine.connect() as conn:
    conn.execute(CreateTable(mytable))
CREATE TABLE mytable ( col1 INTEGER, col2 INTEGER, col3 INTEGER, col4 INTEGER, col5 INTEGER, col6 INTEGER )

上記の CreateTable 構文は、他の式構文(例えば select()table.insert() など)と同じように動作します。SQLAlchemyのDDL指向の構文はすべて、 ExecutableDDLElement 基底クラスのサブクラスです。これは、CREATEやDROP、ALTERに対応するすべてのオブジェクトの基底であり、SQLAlchemyだけでなくAlembic Migrationsでも同様です。利用可能な構文の完全なリファレンスは DDL Expression Constructs API にあります。

ユーザ定義のDDL構文は、 ExecutableDDLElement 自身のサブクラスとして作成することもできます。 Custom SQL Constructs and Compilation Extension のドキュメントにいくつか例があります。

Controlling DDL Generation of Constraints and Indexes

New in version 2.0.

前述の ExecutableDDLElement.execute_if() メソッドは、条件付きで呼び出す必要があるカスタムの DDL クラスには便利ですが、特定の Table に通常関連する要素、つまり制約とインデックスも、PostgreSQLやSQL Serverなどの特定のバックエンドに固有の機能を含むインデックスなどの”条件付き”ルールの対象にする必要があります。このユースケースでは、 Constraint.ddl_if() メソッドと Index.ddl_if() メソッドを CheckConstraintUniqueConstraintIndex などの構文に対して使用できます。 ExecutableDDLElement.execute_if() メソッドと同じ引数を受け入れて、親の Table オブジェクトに関してDDLが生成されるかどうかを制御します。これらのメソッドは、 Table の定義を作成するときにインラインで使用できます。(または、ORM宣言型マッピングで __table_args__ コレクションを使用する場合も同様です)

たとえば:

from sqlalchemy import CheckConstraint, Index
from sqlalchemy import MetaData, Table, Column
from sqlalchemy import Integer, String

meta = MetaData()

my_table = Table(
    "my_table",
    meta,
    Column("id", Integer, primary_key=True),
    Column("num", Integer),
    Column("data", String),
    Index("my_pg_index", "data").ddl_if(dialect="postgresql"),
    CheckConstraint("num > 5").ddl_if(dialect="postgresql"),
)

上の例では、 Table 構文は IndexCheckConstraint の両方を参照します。どちらも .ddl_if(dialect="postgresql") を示します。これは、これらの要素がPostgreSQLダイアレクトに対してのみCREATE TABLEシーケンスに含まれることを示します。例えば、SQLiteダイアレクトに対して meta.create_all() を実行しても、どちらの構文も含まれません。

>>> from sqlalchemy import create_engine
>>> sqlite_engine = create_engine("sqlite+pysqlite://", echo=True)
>>> meta.create_all(sqlite_engine)
BEGIN (implicit) PRAGMA main.table_info("my_table") [raw sql] () PRAGMA temp.table_info("my_table") [raw sql] () CREATE TABLE my_table ( id INTEGER NOT NULL, num INTEGER, data VARCHAR, PRIMARY KEY (id) )

しかし、同じコマンドをPostgreSQLデータベースに対して実行すると、CHECK制約用のインラインDDLと、インデックス用に生成された別のCREATE文が表示されます。

>>> from sqlalchemy import create_engine
>>> postgresql_engine = create_engine(
...     "postgresql+psycopg2://scott:tiger@localhost/test", echo=True
... )
>>> meta.create_all(postgresql_engine)
BEGIN (implicit) select relname from pg_class c join pg_namespace n on n.oid=c.relnamespace where pg_catalog.pg_table_is_visible(c.oid) and relname=%(name)s [generated in 0.00009s] {'name': 'my_table'} CREATE TABLE my_table ( id SERIAL NOT NULL, num INTEGER, data VARCHAR, PRIMARY KEY (id), CHECK (num > 5) ) [no key 0.00007s] {} CREATE INDEX my_pg_index ON my_table (data) [no key 0.00013s] {} COMMIT

Constraint.ddl_if() および Index.ddl_if() メソッドは、 ExecutableDDLElement.execute_if() の動作のようにDDLの実行時だけでなく、 CreateTable オブジェクトのSQLコンパイル時にも参照されるイベントフックを作成します。このオブジェクトは、CreateTableステートメント内のインラインで CHECK (num > 5) DDLをレンダリングします。そのため、 ddl_if.callable_() パラメータが受け取るイベントフックには、より豊富な引数セットが存在します。これには、 dialect キーワード引数が渡されることや、シーケンスの”インラインレンダリング”部分の compiler キーワード引数を介して DDLCompiler のインスタンスが渡されることなどが含まれます。 bind 引数は、イベントが DDLCompiler シーケンス内でトリガされるときには 存在しない ので、データベースのバージョン情報を検査しようとする最新のイベントフックは、PostgreSQLのバージョン情報をテストするなど、与えられた Dialect オブジェクトを使用するのが最適です。

def only_pg_14(ddl_element, target, bind, dialect, **kw):
    return dialect.name == "postgresql" and dialect.server_version_info >= (14,)

my_table = Table(
    "my_table",
    meta,
    Column("id", Integer, primary_key=True),
    Column("num", Integer),
    Column("data", String),
    Index("my_pg_index", "data").ddl_if(callable_=only_pg_14),
)

DDL Expression Constructs API

Object Name Description

_CreateDropBase

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

AddConstraint

Represent an ALTER TABLE ADD CONSTRAINT statement.

BaseDDLElement

The root of DDL constructs, including those that are sub-elements within the “create table” and other processes.

CreateColumn

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

CreateIndex

Represent a CREATE INDEX statement.

CreateSchema

Represent a CREATE SCHEMA statement.

CreateSequence

Represent a CREATE SEQUENCE statement.

CreateTable

Represent a CREATE TABLE statement.

DDL

A literal DDL statement.

DropConstraint

Represent an ALTER TABLE DROP CONSTRAINT statement.

DropIndex

Represent a DROP INDEX statement.

DropSchema

Represent a DROP SCHEMA statement.

DropSequence

Represent a DROP SEQUENCE statement.

DropTable

Represent a DROP TABLE statement.

ExecutableDDLElement

Base class for standalone executable DDL expression constructs.

sort_tables(tables[, skip_fn, extra_dependencies])

Sort a collection of Table objects based on dependency.

sort_tables_and_constraints(tables[, filter_fn, extra_dependencies, _warn_for_cycles])

Sort a collection of Table / ForeignKeyConstraint objects.

function sqlalchemy.schema.sort_tables(tables: Iterable[TableClause], skip_fn: Callable[[ForeignKeyConstraint], bool] | None = None, extra_dependencies: typing_Sequence[Tuple[TableClause, TableClause]] | None = None) List[Table]

Sort a collection of Table objects based on dependency.

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

Warning

The sort_tables() 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 sort_tables_and_constraints() 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 Table objects.

  • skip_fn – optional callable which will be passed a ForeignKeyConstraint object; if it returns True, this constraint will not be considered as a dependency. Note this is different from the same parameter in sort_tables_and_constraints(), 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

sort_tables_and_constraints()

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 Table / ForeignKeyConstraint objects.

This is a dependency-ordered sort which will emit tuples of (Table, [ForeignKeyConstraint, ...]) such that each Table follows its dependent Table objects. Remaining ForeignKeyConstraint 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 Table.add_is_dependent_on(), as well as dependencies stated here using the sort_tables_and_constraints.skip_fn and/or sort_tables_and_constraints.extra_dependencies parameters.

Parameters:
  • tables – a sequence of Table objects.

  • filter_fn – optional callable which will be passed a ForeignKeyConstraint 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.

See also

sort_tables()

class sqlalchemy.schema.BaseDDLElement

The root of DDL constructs, including those that are sub-elements within the “create table” and other processes.

New in version 2.0.

class sqlalchemy.schema.ExecutableDDLElement

Base class for standalone executable DDL expression constructs.

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

Changed in version 2.0: ExecutableDDLElement is renamed from DDLElement, which still exists for backwards compatibility.

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

event.listen(
    users,
    'after_create',
    AddConstraint(constraint).execute_if(dialect='postgresql')
)
method sqlalchemy.schema.ExecutableDDLElement.__call__(target, bind, **kw)

Execute the DDL as a ddl_listener.

method sqlalchemy.schema.ExecutableDDLElement.against(target: SchemaItem) Self

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

This essentially applies the given item to the .target attribute of the returned ExecutableDDLElement 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 ExecutableDDLElement object is established as an event handler for the DDLEvents.before_create() or DDLEvents.after_create() events, and the event then occurs for a given target such as a Constraint or Table, that target is established with a copy of the ExecutableDDLElement object using this method, which then proceeds to the ExecutableDDLElement.execute() 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 ExecutableDDLElement with the .target attribute assigned to the given SchemaItem.

See also

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

method sqlalchemy.schema.ExecutableDDLElement.execute_if(dialect: str | None = None, callable_: DDLIfCallable | None = None, state: Any | None = None) Self

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

Used to provide a wrapper for event listening:

event.listen(
            metadata,
            'before_create',
            DDL("my_ddl").execute_if(dialect='postgresql')
        )
Parameters:
  • dialect

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

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

    If a tuple, specifies multiple dialect names:

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

  • callable_

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

    ddl:

    This DDL element.

    target:

    The Table or MetaData object which is the target of this event. May be None if the DDL is executed explicitly.

    bind:

    The Connection being used for DDL execution. May be None if this construct is being created inline within a table, in which case compiler will be present.

    tables:

    Optional keyword argument - a list of Table objects which are to be created/ dropped within a MetaData.create_all() or drop_all() method call.

    dialect:

    keyword argument, but always present - the Dialect involved in the operation.

    compiler:

    keyword argument. Will be None for an engine level DDL invocation, but will refer to a DDLCompiler if this DDL element is being created inline within a table.

    state:

    Optional keyword argument - will be the state argument passed to this function.

    checkfirst:

    Keyword argument, will be True if the ‘checkfirst’ flag was set during the call to create(), create_all(), drop(), drop_all().

    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.

See also

SchemaItem.ddl_if()

DDLEvents

Events

class sqlalchemy.schema.DDL

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 Table or MetaData objects as targets. Basic templating support allows a single DDL instance to handle repetitive tasks for multiple tables.

Examples:

from sqlalchemy import event, DDL

tbl = Table('users', metadata, Column('uid', Integer))
event.listen(tbl, 'before_create', DDL('DROP TRIGGER users_trigger'))

spow = DDL('ALTER TABLE %(table)s SET secretpowers TRUE')
event.listen(tbl, 'after_create', spow.execute_if(dialect='somedb'))

drop_spow = DDL('ALTER TABLE users SET secretpowers FALSE')
connection.execute(drop_spow)

When operating on Table events, the following statement string substitutions 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 substitutions noted above. Keys present in the context will override the standard substitutions.

Members

__init__()

method sqlalchemy.schema.DDL.__init__(statement, context=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 using a fixed set of string substitutions, as well as additional substitutions provided by the optional DDL.context parameter.

    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.

See also

DDLEvents

Events

class sqlalchemy.schema._CreateDropBase

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 (sqlalchemy.schema.ExecutableDDLElement)

class sqlalchemy.schema.CreateTable

Represent a CREATE TABLE statement.

Members

__init__()

Class signature

class sqlalchemy.schema.CreateTable (sqlalchemy.schema._CreateBase)

method sqlalchemy.schema.CreateTable.__init__(element: Table, include_foreign_key_constraints: typing_Sequence[ForeignKeyConstraint] | None = None, if_not_exists: bool = False)

Create a CreateTable construct.

Parameters:
  • element – a Table that’s the subject of the CREATE

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

  • include_foreign_key_constraints – optional sequence of ForeignKeyConstraint objects that will be included inline within the CREATE construct; if omitted, all foreign key constraints that do not specify use_alter=True are included.

  • if_not_exists

    if True, an IF NOT EXISTS operator will be applied to the construct.

    New in version 1.4.0b2.

class sqlalchemy.schema.DropTable

Represent a DROP TABLE statement.

Members

__init__()

Class signature

class sqlalchemy.schema.DropTable (sqlalchemy.schema._DropBase)

method sqlalchemy.schema.DropTable.__init__(element: Table, if_exists: bool = False)

Create a DropTable construct.

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

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

  • if_exists

    if True, an IF EXISTS operator will be applied to the construct.

    New in version 1.4.0b2.

class sqlalchemy.schema.CreateColumn

Represent a Column as rendered in a CREATE TABLE statement, via the CreateTable 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 CreateColumn.

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

from sqlalchemy import schema
from sqlalchemy.ext.compiler import compiles

@compiles(schema.CreateColumn)
def compile(element, compiler, **kw):
    column = element.element

    if "special" not in column.info:
        return compiler.visit_create_column(element, **kw)

    text = "%s SPECIAL DIRECTIVE %s" % (
            column.name,
            compiler.type_compiler.process(column.type)
        )
    default = compiler.get_column_default_string(column)
    if default is not None:
        text += " DEFAULT " + default

    if not column.nullable:
        text += " NOT NULL"

    if column.constraints:
        text += " ".join(
                    compiler.process(const)
                    for const in column.constraints)
    return text

The above construct can be applied to a Table as follows:

from sqlalchemy import Table, Metadata, Column, Integer, String
from sqlalchemy import schema

metadata = MetaData()

table = Table('mytable', MetaData(),
        Column('x', Integer, info={"special":True}, primary_key=True),
        Column('y', String(50)),
        Column('z', String(20), info={"special":True})
    )

metadata.create_all(conn)

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

CREATE TABLE mytable (
        x SPECIAL DIRECTIVE INTEGER NOT NULL,
        y VARCHAR(50),
        z SPECIAL DIRECTIVE VARCHAR(20),
    PRIMARY KEY (x)
)

The CreateColumn 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 Table 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:

from sqlalchemy.schema import CreateColumn

@compiles(CreateColumn, "postgresql")
def skip_xmin(element, compiler, **kw):
    if element.element.name == 'xmin':
        return None
    else:
        return compiler.visit_create_column(element, **kw)


my_table = Table('mytable', metadata,
            Column('id', Integer, primary_key=True),
            Column('xmin', Integer)
        )

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 sqlalchemy.schema.CreateSequence

Represent a CREATE SEQUENCE statement.

Class signature

class sqlalchemy.schema.CreateSequence (sqlalchemy.schema._CreateBase)

class sqlalchemy.schema.DropSequence

Represent a DROP SEQUENCE statement.

Class signature

class sqlalchemy.schema.DropSequence (sqlalchemy.schema._DropBase)

class sqlalchemy.schema.CreateIndex

Represent a CREATE INDEX statement.

Members

__init__()

Class signature

class sqlalchemy.schema.CreateIndex (sqlalchemy.schema._CreateBase)

method sqlalchemy.schema.CreateIndex.__init__(element, if_not_exists=False)

Create a Createindex construct.

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

  • if_not_exists

    if True, an IF NOT EXISTS operator will be applied to the construct.

    New in version 1.4.0b2.

class sqlalchemy.schema.DropIndex

Represent a DROP INDEX statement.

Members

__init__()

Class signature

class sqlalchemy.schema.DropIndex (sqlalchemy.schema._DropBase)

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

Create a DropIndex construct.

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

  • if_exists

    if True, an IF EXISTS operator will be applied to the construct.

    New in version 1.4.0b2.

class sqlalchemy.schema.AddConstraint

Represent an ALTER TABLE ADD CONSTRAINT statement.

Class signature

class sqlalchemy.schema.AddConstraint (sqlalchemy.schema._CreateBase)

class sqlalchemy.schema.DropConstraint

Represent an ALTER TABLE DROP CONSTRAINT statement.

Class signature

class sqlalchemy.schema.DropConstraint (sqlalchemy.schema._DropBase)

class sqlalchemy.schema.CreateSchema

Represent a CREATE SCHEMA statement.

The argument here is the string name of the schema.

Members

__init__()

Class signature

class sqlalchemy.schema.CreateSchema (sqlalchemy.schema._CreateBase)

method sqlalchemy.schema.CreateSchema.__init__(name, if_not_exists=False)

Create a new CreateSchema construct.

class sqlalchemy.schema.DropSchema

Represent a DROP SCHEMA statement.

The argument here is the string name of the schema.

Members

__init__()

Class signature

class sqlalchemy.schema.DropSchema (sqlalchemy.schema._DropBase)

method sqlalchemy.schema.DropSchema.__init__(name, cascade=False, if_exists=False)

Create a new DropSchema construct.