Defining Constraints and Indexes

この節では、SQLの constraints とインデックスについて説明します。SQLAlchemyのキークラスには ForeignKeyConstraintIndex があります。

Defining Foreign Keys

SQLの 外部キー はテーブル・レベルの構成体であり、そのテーブルの1つ以上の列を制約して、別の列セットに存在する値のみを許可します。通常は別のテーブルにあるとは限りません。制約される列を 外部キー 列と呼び、制約される列を 参照される 列と呼びます。参照される列は、ほとんどの場合、所有するテーブルの主キーを定義しますが、これには例外があります。外部キーは、互いに関係を持つ行のペアを接続する”ジョイント”であり、SQLAlchemyは、その操作の事実上すべての領域において、この概念を非常に重視しています。

SQLAlchemyでもDDLでも、外部キー制約はテーブル句の中で追加の属性として定義することができます。また、単一列の外部キーの場合は、単一列の定義の中でオプションで指定することもできます。単一列の外部キーの方が一般的で、列レベルでは ForeignKey オブジェクトを Column オブジェクトへの引数として構築することで指定されます:

user_preference = Table(
    "user_preference",
    metadata_obj,
    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)),
)

上記では、新しいテーブル user_preference を定義しています。このテーブルの各行には、 user テーブルの user_id 列にも存在する値が含まれている必要があります。

ForeignKey への引数は、最も一般的には <tablename>.<columnname> という形式の文字列か、リモートスキーマ内のテーブルか <schemaname>.<tablename>.<columnname> という形式の”owner”に対するものです。実際の Column オブジェクトでもかまいません。これは、後で説明するように、既存の Table オブジェクトの c コレクションからアクセスされます:

ForeignKey(user.c.user_id)

文字列を使用する利点は、Python内での useruser_preference の間のリンクが最初に必要になったときにのみ解決されることです。これにより、テーブルオブジェクトを複数のモジュールに簡単に展開し、任意の順序で定義することができます。

外部キーは、 ForeignKeyConstraint オブジェクトを使って、テーブルレベルで定義することもできます。このオブジェクトは、単一カラムまたは複数カラムの外部キーを記述することができます。複数カラムの外部キーは composite 外部キーと呼ばれ、ほとんどの場合、複合主キーを持つテーブルを参照します。以下では、複合主キーを持つテーブル invoice を定義します:

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

次に、 invoice を参照する複合外部キーを持つテーブル invoice_item があります:

invoice_item = Table(
    "invoice_item",
    metadata_obj,
    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"]
    ),
)

Creating/Dropping Foreign Key Constraints via ALTER

DDLで外部キーを使用したチュートリアルや他の場所で見られた動作は、制約が通常、次のようにCREATE TABLE文内で”インライン”でレンダリングされることを示しています。

CREATE TABLE addresses (
    id INTEGER NOT NULL,
    user_id INTEGER,
    email_address VARCHAR NOT NULL,
    PRIMARY KEY (id),
    CONSTRAINT user_id_fk FOREIGN KEY(user_id) REFERENCES users (id)
)

CONSTRAINT .. FOREIGN KEY ディレクティブは、CREATE TABLE定義内で”インライン”方式で制約を作成するために使用されます。 MetaData.create_all() メソッドと MetaData.drop_all() メソッドはデフォルトでこれを行い、関係するすべての Table オブジェクトのトポロジソートを使用して、外部キーの依存関係の順にテーブルが作成されてドロップされます(このソートは MetaData.sorted_tables アクセッサからも利用できます)。

この方法は、バックエンドが外部キーを強制すると仮定して(SQLite、MySQL/MyISAMを除くすべての場合)、テーブルのセットが相互に依存する”依存サイクル”に2つ以上の外部キー制約が含まれている場合には機能しません。したがって、これらのメソッドは、ほとんどの形式のALTERをサポートしていないSQLite以外のすべてのバックエンドで、このようなサイクル内の制約を個別のALTER文に分割します。次のようなスキーマがあるとします:

node = Table(
    "node",
    metadata_obj,
    Column("node_id", Integer, primary_key=True),
    Column("primary_element", Integer, ForeignKey("element.element_id")),
)

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

PostgreSQLバックエンドなどのバックエンドで MetaData.create_all() を呼び出すと、これら2つのテーブル間のサイクルが解決され、制約が別々に作成されます。

>>> with engine.connect() as conn:
...     metadata_obj.create_all(conn, checkfirst=False)
CREATE TABLE element ( element_id SERIAL NOT NULL, parent_node_id INTEGER, PRIMARY KEY (element_id) ) CREATE TABLE node ( node_id SERIAL NOT NULL, primary_element INTEGER, PRIMARY KEY (node_id) ) ALTER TABLE element ADD CONSTRAINT fk_element_parent_node_id FOREIGN KEY(parent_node_id) REFERENCES node (node_id) ALTER TABLE node ADD FOREIGN KEY(primary_element) REFERENCES element (element_id)

これらのテーブルに対してDROPを発行するには、同じロジックが適用されます。ただし、SQLでは、DROP CONSTRAINTを発行するには、制約に名前が必要であることに注意してください。上記の node テーブルの場合、この制約には名前が付けられていません。したがって、システムは名前が付けられた制約に対してのみDROPを発行しようとします。

>>> with engine.connect() as conn:
...     metadata_obj.drop_all(conn, checkfirst=False)
ALTER TABLE element DROP CONSTRAINT fk_element_parent_node_id DROP TABLE node DROP TABLE element

ここでどちらの制約にも名前を適用しなかった場合など、サイクルを解決できない場合は、次のエラーが発生します。

sqlalchemy.exc.CircularDependencyError: Can't sort tables for DROP; an unresolvable foreign key dependency exists between tables: element, node.  Please ensure that the ForeignKey and ForeignKeyConstraint objects involved in the cycle have names so that they can be dropped using DROP CONSTRAINT.

このエラーはDROPの場合にのみ適用されます。なぜなら、CREATEの場合は名前なしで”ADD CONSTRAINT”を発行できるからです。通常、データベースは自動的に名前を割り当てます。

ForeignKeyConstraint.use_alter および ForeignKey.use_alter キーワード引数を使用して、依存関係の循環を手動で解決することができます。このフラグは、次のようにして 'element' テーブルにのみ追加できます:

element = Table(
    "element",
    metadata_obj,
    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",
    ),
)

CREATE DDLでは、この制約に対してのみALTER文が表示され、他の制約に対しては表示されません。

>>> with engine.connect() as conn:
...     metadata_obj.create_all(conn, checkfirst=False)
CREATE TABLE element ( element_id SERIAL NOT NULL, parent_node_id INTEGER, PRIMARY KEY (element_id) ) CREATE TABLE node ( node_id SERIAL NOT NULL, primary_element INTEGER, PRIMARY KEY (node_id), FOREIGN KEY(primary_element) REFERENCES element (element_id) ) ALTER TABLE element ADD CONSTRAINT fk_element_parent_node_id FOREIGN KEY(parent_node_id) REFERENCES node (node_id)

ForeignKeyConstraint.use_alter および ForeignKey.use_alter をドロップ操作と組み合わせて使用する場合、制約に名前を付ける必要があります。そうしないと、次のようなエラーが生成されます。

sqlalchemy.exc.CompileError: Can't emit DROP CONSTRAINT for constraint
ForeignKeyConstraint(...); it has no name

ON UPDATE and ON DELETE

ほとんどのデータベースは外部キー値の*カスケード*をサポートしています。つまり、親の行が更新されると新しい値が子の行に置かれ、親の行が削除されると、対応するすべての子の行がnullに設定されるか削除されます。データ定義言語では、これらは外部キー制約に対応する”ON UPDATECASCADE”、”ON DELETE CASCADE”、”ON DELETE SET NULL”のような句を使用して指定されます。”ON UPDATE”または”ON DELETE”の後の句は、使用中のデータベースに固有の他の句を許可することもできます。 ForeignKey および ForeignKeyConstraint オブジェクトは、この句の生成を onupdate および ondelete キーワード引数を介してサポートします。値は、適切な”ON UPDATE”または”ON DELETE”句の後に出力される任意の文字列です:

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

composite = Table(
    "composite",
    metadata_obj,
    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",
    ),
)

これらの句をMySQLで使用する場合は、 InnoDB テーブルが必要であることに注意してください。また、他のデータベースでもサポートされていない可能性があります。

UNIQUE Constraint

一意制約は、 Columnunique キーワードを使って、1つの列に匿名で作成することができます。明示的に名前が付けられた一意制約や、複数の列を持つものは、 UniqueConstraint のテーブルレベルの構文を使って作成されます。

from sqlalchemy import UniqueConstraint

metadata_obj = MetaData()
mytable = Table(
    "mytable",
    metadata_obj,
    # 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

検査制約は名前付きでも名前なしでもよく、 CheckConstraint 構文を使って、列またはテーブルレベルで作成することができます。検査制約のテキストはデータベースに直接渡されるので、”データベースに依存しない”動作には制限があります。列レベルの検査制約は一般的に、置き換え先の列のみを参照すべきですが、テーブルレベルの制約はテーブル内の任意の列を参照できます。

(8.0.16より前の)MySQLのように、チェック制約を積極的にサポートしていないデータベースもあることに注意してください。

from sqlalchemy import CheckConstraint

metadata_obj = MetaData()
mytable = Table(
    "mytable",
    metadata_obj,
    # 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"),
)

mytable.create(engine)
CREATE TABLE mytable ( col1 INTEGER CHECK (col1>5), col2 INTEGER, col3 INTEGER, CONSTRAINT check1 CHECK (col2 > col3 + 5) )

PRIMARY KEY Constraint

Table オブジェクトの主キー制約は、 Column.primary_key フラグでマークされた Column オブジェクトに基づいて、暗黙的に存在します。 PrimaryKeyConstraint オブジェクトは、この制約への明示的なアクセスを提供します。これには、直接設定されるオプションが含まれます:

from sqlalchemy import PrimaryKeyConstraint

my_table = Table(
    "mytable",
    metadata_obj,
    Column("id", Integer),
    Column("version_id", Integer),
    Column("data", String(50)),
    PrimaryKeyConstraint("id", "version_id", name="mytable_pk"),
)

See also

PrimaryKeyConstraint - detailed API documentation.

Setting up Constraints when using the Declarative ORM Extension

Table はSQLAlchemy Coreの構成体で、テーブルのメタデータを定義することができます。これはSQLAlchemy ORMasがクラスをマップするために使用することができます。 Declarative 拡張を使用すると、テーブルの内容を主に Column オブジェクトのマッピングとして指定して、 Table オブジェクトを自動的に作成できます。

Declarativeを使って定義されたテーブルに ForeignKeyConstraint のようなテーブルレベルの制約オブジェクトを適用するには、 Table Configuration で説明されているように、 __table_args__ 属性を使用してください。

Configuring Constraint Naming Conventions

リレーショナル・データベースは通常、すべての制約とインデックスに明示的な名前を割り当てます。CHECK、UNIQUE、PRIMARY KEY制約などの制約がテーブル定義とインラインで生成される CREATE TABLE を使用してテーブルが作成される一般的なケースでは、データベースは通常、名前が他に指定されていない場合に、これらの制約に自動的に名前が割り当てられるシステムを備えています。既存のデータベース・テーブルが ALTER TABLE などのコマンドを使用してデータベース内で変更される場合、このコマンドは通常、新しい制約に明示的な名前を指定するとともに、削除または変更される既存の制約の名前を指定できる必要があります。

制約には Constraint.name パラメータを使って明示的に名前を付けることができ、インデックスには Index.name パラメータを使うことができます。ただし、制約の場合、このパラメータはオプションです。また、 Column.unique および Column.index パラメータを使って、明示的な名前を指定せずに UniqueConstraint および Index オブジェクトを作成するユースケースもあります。

既存のテーブルや制約を変更するユースケースは、 Alembic などのスキーマ移行ツールで処理できます。しかし、AlembicもSQLAlchemyも、名前が指定されていない制約オブジェクトに対して名前を作成することはできません。そのため、既存の制約を変更できるということは、名前を自動的に割り当てるためにリレーショナルデータベースで使用される命名システムをリバースエンジニアリングする必要があることや、すべての制約に名前が付けられるように注意する必要があることを意味します。

すべての Constraint および Index オブジェクトに明示的な名前を割り当てる必要があるのとは対照的に、自動化された命名スキームはイベントを使用して構築することができます。このアプローチには、コード全体で明示的な名前パラメータを必要とせずに、制約が一貫した命名スキームを取得するという利点があります。また、 Column.index パラメータによって生成された制約とインデックスに対しても同様に規則が行われるという利点もあります。SQLAlchemy 0.9.2では、このイベントベースのアプローチが含まれており、引数 MetaData.naming_convention を使用して設定できます。

Configuring a Naming Convention for a MetaData Collection

MetaData.naming_convention は、キーとして Index クラスまたは個々の Constraint クラスを受け入れ、値としてPython文字列テンプレートを受け入れる辞書を参照します。また、代替キーとして一連の文字列コードを受け入れます。それぞれ、外部キー、主キー、インデックス、チェック、一意性制約に対して、それぞれ "fk""pk""ix""ck""uq" を受け入れます。この辞書の文字列テンプレートは、既存の名前が与えられていない(既存の名前をさらに修飾できる1つの例外を含む) MetaData オブジェクトに制約またはインデックスが関連付けられている場合に使用されます。

基本的なケースに適した命名規則の例を次に示します:

convention = {
    "ix": "ix_%(column_0_label)s",
    "uq": "uq_%(table_name)s_%(column_0_name)s",
    "ck": "ck_%(table_name)s_%(constraint_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s",
}

metadata_obj = MetaData(naming_convention=convention)

上記の規則は、対象の MetaData コレクション内のすべての制約に対して名前を確立します。例えば、名前のない UniqueConstraint を作成したときに生成される名前を確認できます。

>>> user_table = Table(
...     "user",
...     metadata_obj,
...     Column("id", Integer, primary_key=True),
...     Column("name", String(30), nullable=False),
...     UniqueConstraint("name"),
... )
>>> list(user_table.constraints)[1].name
'uq_user_name'

これと同じ機能は、単に Column.unique フラグを使用しても有効です:

>>> user_table = Table(
...     "user",
...     metadata_obj,
...     Column("id", Integer, primary_key=True),
...     Column("name", String(30), nullable=False, unique=True),
... )
>>> list(user_table.constraints)[1].name
'uq_user_name'

命名規則アプローチの主な利点は、DDLの出力時ではなく、Pythonの構築時に名前が確立されることです。Alembicの --autogenerate 機能を使用した場合の効果は、新しい移行スクリプトが生成されたときに命名規則が明示的になることです:

def upgrade():
    op.create_unique_constraint("uq_user_name", "user", ["name"])

上記の "uq_user_name" という文字列は、メタデータにある --autogenerate という UniqueConstraint オブジェクトからコピーされたものです。

使用可能なトークンには、 %(table_name)s%(referred_table_name)s%(column_0_name)s%(column_0_label)s%(column_0_key)s%(referred_column_0_name)s%(constraint_name)s などがありま す。また、それぞれの複数列バージョンには、 %(column_0N_name)s%(column_0_N_name)s%(referred_column_0_N_name)s などがあり、これらはすべての列名をアンダースコアで区切って表示したり、アンダースコアなしで表示したりします。 MetaData.naming_convention のドキュメントには、これらの表記法の詳細が記載されています。

The Default Naming Convention

MetaData.naming_convention のデフォルト値は、 Column.index パラメータを使用して作成された Index オブジェクトに名前を割り当てるという長年のSQLAlchemyの動作を処理します:

>>> from sqlalchemy.sql.schema import DEFAULT_NAMING_CONVENTION
>>> DEFAULT_NAMING_CONVENTION
immutabledict({'ix': 'ix_%(column_0_label)s'})

Truncation of Long Names

生成された名前、特に複数列トークンを使用する名前が、対象データベースの識別子の長さ制限に対して長すぎる場合(例えば、PostgreSQLでは63文字に制限されています)、名前は次のようになります。 長い名前のmd 5ハッシュに基づく4文字の接尾辞を使用して、確定的に切り捨てられます。たとえば、次の命名規則では、使用されているカラム名を指定すると、非常に長い名前が生成されます:

metadata_obj = MetaData(
    naming_convention={"uq": "uq_%(table_name)s_%(column_0_N_name)s"}
)

long_names = Table(
    "long_names",
    metadata_obj,
    Column("information_channel_code", Integer, key="a"),
    Column("billing_convention_name", Integer, key="b"),
    Column("product_identifier", Integer, key="c"),
    UniqueConstraint("a", "b", "c"),
)

PostgreSQLダイアレクトでは、63文字を超える名前は次の例のように切り詰められます。

CREATE TABLE long_names (
    information_channel_code INTEGER,
    billing_convention_name INTEGER,
    product_identifier INTEGER,
    CONSTRAINT uq_long_names_information_channel_code_billing_conventi_a79e
    UNIQUE (information_channel_code, billing_convention_name, product_identifier)
)

上記のサフィックス a79e は、長い名前のmd5ハッシュに基づいており、与えられたスキーマに対して一貫した名前を生成するために毎回同じ値を生成します。

Creating Custom Tokens for Naming Conventions

naming_conventionディクショナリ内で追加のトークンと呼び出し可能なを指定することで、新しいトークンを追加することもできます。たとえば、GUIDスキームを使用して外部キー制約に名前を付けたい場合は、次のようにします:

import uuid

def fk_guid(constraint, table):
    str_tokens = (
        [
            table.name,
        ]
        + [element.parent.name for element in constraint.elements]
        + [element.target_fullname for element in constraint.elements]
    )
    guid = uuid.uuid5(uuid.NAMESPACE_OID, "_".join(str_tokens).encode("ascii"))
    return str(guid)

convention = {
    "fk_guid": fk_guid,
    "ix": "ix_%(column_0_label)s",
    "fk": "fk_%(fk_guid)s",
}

上記では、新しい ForeignKeyConstraint を作成すると、次のような名前が得られます:

>>> metadata_obj = MetaData(naming_convention=convention)

>>> user_table = Table(
...     "user",
...     metadata_obj,
...     Column("id", Integer, primary_key=True),
...     Column("version", Integer, primary_key=True),
...     Column("data", String(30)),
... )
>>> address_table = Table(
...     "address",
...     metadata_obj,
...     Column("id", Integer, primary_key=True),
...     Column("user_id", Integer),
...     Column("user_version_id", Integer),
... )
>>> fk = ForeignKeyConstraint(["user_id", "user_version_id"], ["user.id", "user.version"])
>>> address_table.append_constraint(fk)
>>> fk.name
fk_0cd51ab5-8d70-56e8-a83c-86661737766d

See also

MetaData.naming_convention - 使用方法の詳細と、使用可能なすべての命名コンポーネントのリストです。

The Importance of Naming Constraints - Alembicドキュメントにて。

New in version 1.3.0では、: %(column_0_N_name)s のような複数列の名前付けトークンが追加されました。ターゲットデータベースの文字数制限を超えて生成された名前は、確定的に切り捨てられます。

Naming CHECK Constraints

CheckConstraint オブジェクトは、任意のSQL式に対して設定されます。任意のSQL式には任意の数の列を含めることができます。さらに、多くの場合、生のSQL文字列を使用して設定されます。したがって、 CheckConstraint で使用する一般的な規約は、オブジェクトがすでに名前を持っていることを想定し、他の規約要素でそれを拡張するものです。典型的な規約は "ck_%(table_name)s_%(constraint_name)s" です:

metadata_obj = MetaData(
    naming_convention={"ck": "ck_%(table_name)s_%(constraint_name)s"}
)

Table(
    "foo",
    metadata_obj,
    Column("value", Integer),
    CheckConstraint("value > 5", name="value_gt_5"),
)

上の表は ck_foo_value_gt_5 という名前になります。

CREATE TABLE foo (
    value INTEGER,
    CONSTRAINT ck_foo_value_gt_5 CHECK (value > 5)
)

CheckConstraint はまた、 %(columns_0_name)s トークンもサポートしています。 Column または column() 要素を制約式の中で確実に使用することで、これを利用することができます。テーブルとは別に制約を宣言してください:

metadata_obj = MetaData(naming_convention={"ck": "ck_%(table_name)s_%(column_0_name)s"})

foo = Table("foo", metadata_obj, Column("value", Integer))

CheckConstraint(foo.c.value > 5)

または column() のインライン方式:

from sqlalchemy import column

metadata_obj = MetaData(naming_convention={"ck": "ck_%(table_name)s_%(column_0_name)s"})

foo = Table(
    "foo", metadata_obj, Column("value", Integer), CheckConstraint(column("value") > 5)
)

どちらも ck_foo_value という名前を生成します。

CREATE TABLE foo (
    value INTEGER,
    CONSTRAINT ck_foo_value CHECK (value > 5)
)

“column zero”の名前の決定は、列オブジェクトに対して指定された式をスキャンすることによって実行されます。式に複数の列が存在する場合、スキャンでは決定論的検索が使用されますが、式の構造によってどの列が”column zero”として示されるかが決定されます。

Configuring Naming for Boolean, Enum, and other schema types

SchemaType クラスは、型に付随するCHECK制約を生成する BooleanEnum などの型オブジェクトを参照します。ここでの制約の名前は、”name”パラメータを送ることで直接設定されます。例えば Boolean.name

Table("foo", metadata_obj, Column("flag", Boolean(name="ck_foo_flag")))

命名規則の機能は、これらの型と組み合わせることもできます。通常は、 %(constraint_name)s を含む命名規則を使用し、型に名前を適用します:

metadata_obj = MetaData(
    naming_convention={"ck": "ck_%(table_name)s_%(constraint_name)s"}
)

Table("foo", metadata_obj, Column("flag", Boolean(name="flag_bool")))

上の表は制約名 ck_foo_flag_bool を生成します。

CREATE TABLE foo (
    flag BOOL,
    CONSTRAINT ck_foo_flag_bool CHECK (flag IN (0, 1))
)

SchemaType クラスは特別な内部シンボルを使用するので、DDLのコンパイル時にのみ名前付け規則が決定されます。PostgreSQLにはネイティブブーリアン型がありますので、 Boolean のCHECK制約は必要ありません。名前なしで Boolean 型を設定しても安全です。たとえ名前付け規則がCHECK制約用に用意されていたとしてもです。この規則は、SQLiteやMySQLのようなネイティブブーリアン型を持たないデータベースに対して実行した場合にのみ、CHECK制約に対して参照されます。

CHECK制約はまた、 column_0_name トークンを利用することもできます。これは SchemaType とうまく動作します。なぜなら、これらの制約は1つの列しか持たないからです:

metadata_obj = MetaData(naming_convention={"ck": "ck_%(table_name)s_%(column_0_name)s"})

Table("foo", metadata_obj, Column("flag", Boolean()))

上記のスキーマは以下を生成します。

CREATE TABLE foo (
    flag BOOL,
    CONSTRAINT ck_foo_flag CHECK (flag IN (0, 1))
)

ORM宣言型ミックスインでの命名規則の使用


ORM Declarative Mixins で命名規則機能を使用する場合、個々の制約オブジェクトはテーブルにマップされた実際のサブクラスごとに存在しなければなりません。背景と例については Creating Indexes and Constraints with Naming Conventions on Mixins を参照してください。

Constraints API

Object Name Description

CheckConstraint

A table- or column-level CHECK constraint.

ColumnCollectionConstraint

A constraint that proxies a ColumnCollection.

ColumnCollectionMixin

A ColumnCollection of Column objects.

Constraint

A table-level SQL constraint.

conv

Mark a string indicating that a name has already been converted by a naming convention.

ForeignKey

Defines a dependency between two columns.

ForeignKeyConstraint

A table-level FOREIGN KEY constraint.

HasConditionalDDL

define a class that includes the HasConditionalDDL.ddl_if() method, allowing for conditional rendering of DDL.

PrimaryKeyConstraint

A table-level PRIMARY KEY constraint.

UniqueConstraint

A table-level UNIQUE constraint.

class sqlalchemy.schema.Constraint

A table-level SQL constraint.

Constraint serves as the base class for the series of constraint objects that can be associated with Table objects, including PrimaryKeyConstraint, ForeignKeyConstraint UniqueConstraint, and CheckConstraint.

method sqlalchemy.schema.Constraint.__init__(name: _ConstraintNameArgument = None, deferrable: bool | None = None, initially: str | None = None, info: _InfoType | None = None, comment: str | None = None, _create_rule: Any | None = None, _type_bound: bool = False, **dialect_kw: Any) None

Create a SQL constraint.

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

  • info – Optional data dictionary which will be populated into the SchemaItem.info attribute of this object.

  • comment

    Optional string that will render an SQL comment on foreign key constraint creation.

    New in version 2.0.

  • **dialect_kw – Additional keyword arguments are dialect specific, and passed in the form <dialectname>_<argname>. See the documentation regarding an individual dialect at Dialects for detail on documented arguments.

  • _create_rule – used internally by some datatypes that also create constraints.

  • _type_bound – used internally to indicate that this constraint is associated with a specific datatype.

classmethod sqlalchemy.schema.Constraint.argument_for(dialect_name, argument_name, default)

inherited from the DialectKWArgs.argument_for() method of DialectKWArgs

Add a new kind of dialect-specific keyword argument for this class.

E.g.:

Index.argument_for("mydialect", "length", None)

some_index = Index('a', 'b', mydialect_length=5)

The DialectKWArgs.argument_for() method is a per-argument way adding extra arguments to the DefaultDialect.construct_arguments dictionary. This dictionary provides a list of argument names accepted by various schema-level constructs on behalf of a dialect.

New dialects should typically specify this dictionary all at once as a data member of the dialect class. The use case for ad-hoc addition of argument names is typically for end-user code that is also using a custom compilation scheme which consumes the additional arguments.

Parameters:
  • dialect_name – name of a dialect. The dialect must be locatable, else a NoSuchModuleError is raised. The dialect must also include an existing DefaultDialect.construct_arguments collection, indicating that it participates in the keyword-argument validation and default system, else ArgumentError is raised. If the dialect does not include this collection, then any keyword argument can be specified on behalf of this dialect already. All dialects packaged within SQLAlchemy include this collection, however for third party dialects, support may vary.

  • argument_name – name of the parameter.

  • default – default value of the parameter.

method sqlalchemy.schema.Constraint.copy(**kw: Any) Self

Deprecated since version 1.4: The Constraint.copy() method is deprecated and will be removed in a future release.

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

inherited from the HasConditionalDDL.ddl_if() method of HasConditionalDDL

apply a conditional DDL rule to this schema item.

These rules work in a similar manner to the ExecutableDDLElement.execute_if() callable, with the added feature that the criteria may be checked within the DDL compilation phase for a construct such as CreateTable. HasConditionalDDL.ddl_if() currently applies towards the Index construct as well as all Constraint constructs.

Parameters:
  • dialect – string name of a dialect, or a tuple of string names to indicate multiple dialect types.

  • callable_ – a callable that is constructed using the same form as that described in ExecutableDDLElement.execute_if.callable_.

  • state – any arbitrary object that will be passed to the callable, if present.

New in version 2.0.

See also

Controlling DDL Generation of Constraints and Indexes - background and usage examples

attribute sqlalchemy.schema.Constraint.dialect_kwargs

inherited from the DialectKWArgs.dialect_kwargs attribute of DialectKWArgs

A collection of keyword arguments specified as dialect-specific options to this construct.

The arguments are present here in their original <dialect>_<kwarg> format. Only arguments that were actually passed are included; unlike the DialectKWArgs.dialect_options collection, which contains all options known by this dialect including defaults.

The collection is also writable; keys are accepted of the form <dialect>_<kwarg> where the value will be assembled into the list of options.

See also

DialectKWArgs.dialect_options - nested dictionary form

attribute sqlalchemy.schema.Constraint.dialect_options

inherited from the DialectKWArgs.dialect_options attribute of DialectKWArgs

A collection of keyword arguments specified as dialect-specific options to this construct.

This is a two-level nested registry, keyed to <dialect_name> and <argument_name>. For example, the postgresql_where argument would be locatable as:

arg = my_object.dialect_options['postgresql']['where']

New in version 0.9.2.

See also

DialectKWArgs.dialect_kwargs - flat dictionary form

attribute sqlalchemy.schema.Constraint.info

inherited from the SchemaItem.info attribute of SchemaItem

Info dictionary associated with the object, allowing user-defined data to be associated with this SchemaItem.

The dictionary is automatically generated when first accessed. It can also be specified in the constructor of some objects, such as Table and Column.

attribute sqlalchemy.schema.Constraint.kwargs

inherited from the DialectKWArgs.kwargs attribute of DialectKWArgs

A synonym for DialectKWArgs.dialect_kwargs.

class sqlalchemy.schema.ColumnCollectionMixin

A ColumnCollection of Column objects.

This collection represents the columns which are referred to by this object.

class sqlalchemy.schema.ColumnCollectionConstraint

A constraint that proxies a ColumnCollection.

method sqlalchemy.schema.ColumnCollectionConstraint.__init__(*columns: _DDLColumnArgument, name: _ConstraintNameArgument = None, deferrable: bool | None = None, initially: str | None = None, info: _InfoType | None = None, _autoattach: bool = True, _column_flag: bool = False, _gather_expressions: List[_DDLColumnArgument] | None = None, **dialect_kw: Any) None
Parameters:
  • *columns – A sequence of column names or Column objects.

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

  • **dialect_kw – other keyword arguments including dialect-specific arguments are propagated to the Constraint superclass.

classmethod sqlalchemy.schema.ColumnCollectionConstraint.argument_for(dialect_name, argument_name, default)

inherited from the DialectKWArgs.argument_for() method of DialectKWArgs

Add a new kind of dialect-specific keyword argument for this class.

E.g.:

Index.argument_for("mydialect", "length", None)

some_index = Index('a', 'b', mydialect_length=5)

The DialectKWArgs.argument_for() method is a per-argument way adding extra arguments to the DefaultDialect.construct_arguments dictionary. This dictionary provides a list of argument names accepted by various schema-level constructs on behalf of a dialect.

New dialects should typically specify this dictionary all at once as a data member of the dialect class. The use case for ad-hoc addition of argument names is typically for end-user code that is also using a custom compilation scheme which consumes the additional arguments.

Parameters:
  • dialect_name – name of a dialect. The dialect must be locatable, else a NoSuchModuleError is raised. The dialect must also include an existing DefaultDialect.construct_arguments collection, indicating that it participates in the keyword-argument validation and default system, else ArgumentError is raised. If the dialect does not include this collection, then any keyword argument can be specified on behalf of this dialect already. All dialects packaged within SQLAlchemy include this collection, however for third party dialects, support may vary.

  • argument_name – name of the parameter.

  • default – default value of the parameter.

attribute sqlalchemy.schema.ColumnCollectionConstraint.columns: ReadOnlyColumnCollection[str, Column[Any]]

inherited from the ColumnCollectionMixin.columns attribute of ColumnCollectionMixin

A ColumnCollection representing the set of columns for this constraint.

method sqlalchemy.schema.ColumnCollectionConstraint.contains_column(col: Column[Any]) bool

Return True if this constraint contains the given column.

Note that this object also contains an attribute .columns which is a ColumnCollection of Column objects.

method sqlalchemy.schema.ColumnCollectionConstraint.copy(*, target_table: Table | None = None, **kw: Any) ColumnCollectionConstraint

Deprecated since version 1.4: The ColumnCollectionConstraint.copy() method is deprecated and will be removed in a future release.

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

inherited from the HasConditionalDDL.ddl_if() method of HasConditionalDDL

apply a conditional DDL rule to this schema item.

These rules work in a similar manner to the ExecutableDDLElement.execute_if() callable, with the added feature that the criteria may be checked within the DDL compilation phase for a construct such as CreateTable. HasConditionalDDL.ddl_if() currently applies towards the Index construct as well as all Constraint constructs.

Parameters:
  • dialect – string name of a dialect, or a tuple of string names to indicate multiple dialect types.

  • callable_ – a callable that is constructed using the same form as that described in ExecutableDDLElement.execute_if.callable_.

  • state – any arbitrary object that will be passed to the callable, if present.

New in version 2.0.

See also

Controlling DDL Generation of Constraints and Indexes - background and usage examples

attribute sqlalchemy.schema.ColumnCollectionConstraint.dialect_kwargs

inherited from the DialectKWArgs.dialect_kwargs attribute of DialectKWArgs

A collection of keyword arguments specified as dialect-specific options to this construct.

The arguments are present here in their original <dialect>_<kwarg> format. Only arguments that were actually passed are included; unlike the DialectKWArgs.dialect_options collection, which contains all options known by this dialect including defaults.

The collection is also writable; keys are accepted of the form <dialect>_<kwarg> where the value will be assembled into the list of options.

See also

DialectKWArgs.dialect_options - nested dictionary form

attribute sqlalchemy.schema.ColumnCollectionConstraint.dialect_options

inherited from the DialectKWArgs.dialect_options attribute of DialectKWArgs

A collection of keyword arguments specified as dialect-specific options to this construct.

This is a two-level nested registry, keyed to <dialect_name> and <argument_name>. For example, the postgresql_where argument would be locatable as:

arg = my_object.dialect_options['postgresql']['where']

New in version 0.9.2.

See also

DialectKWArgs.dialect_kwargs - flat dictionary form

attribute sqlalchemy.schema.ColumnCollectionConstraint.info

inherited from the SchemaItem.info attribute of SchemaItem

Info dictionary associated with the object, allowing user-defined data to be associated with this SchemaItem.

The dictionary is automatically generated when first accessed. It can also be specified in the constructor of some objects, such as Table and Column.

attribute sqlalchemy.schema.ColumnCollectionConstraint.kwargs

inherited from the DialectKWArgs.kwargs attribute of DialectKWArgs

A synonym for DialectKWArgs.dialect_kwargs.

class sqlalchemy.schema.CheckConstraint

A table- or column-level CHECK constraint.

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

method sqlalchemy.schema.CheckConstraint.__init__(sqltext: _TextCoercedExpressionArgument[Any], name: _ConstraintNameArgument = None, deferrable: bool | None = None, initially: str | None = None, table: Table | None = None, info: _InfoType | None = None, _create_rule: Any | None = None, _autoattach: bool = True, _type_bound: bool = False, **dialect_kw: Any) None

Construct a CHECK constraint.

Parameters:
  • sqltext

    A string containing the constraint definition, which will be used verbatim, or a SQL expression construct. If given as a string, the object is converted to a text() object. If the textual string includes a colon character, escape this using a backslash:

    CheckConstraint(r"foo ~ E'a(?\:b|c)d")

    Warning

    The CheckConstraint.sqltext argument to CheckConstraint can be passed as a Python string argument, which will be treated as trusted SQL text and rendered as given. DO NOT PASS UNTRUSTED INPUT TO THIS PARAMETER.

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

  • info – Optional data dictionary which will be populated into the SchemaItem.info attribute of this object.

classmethod sqlalchemy.schema.CheckConstraint.argument_for(dialect_name, argument_name, default)

inherited from the DialectKWArgs.argument_for() method of DialectKWArgs

Add a new kind of dialect-specific keyword argument for this class.

E.g.:

Index.argument_for("mydialect", "length", None)

some_index = Index('a', 'b', mydialect_length=5)

The DialectKWArgs.argument_for() method is a per-argument way adding extra arguments to the DefaultDialect.construct_arguments dictionary. This dictionary provides a list of argument names accepted by various schema-level constructs on behalf of a dialect.

New dialects should typically specify this dictionary all at once as a data member of the dialect class. The use case for ad-hoc addition of argument names is typically for end-user code that is also using a custom compilation scheme which consumes the additional arguments.

Parameters:
  • dialect_name – name of a dialect. The dialect must be locatable, else a NoSuchModuleError is raised. The dialect must also include an existing DefaultDialect.construct_arguments collection, indicating that it participates in the keyword-argument validation and default system, else ArgumentError is raised. If the dialect does not include this collection, then any keyword argument can be specified on behalf of this dialect already. All dialects packaged within SQLAlchemy include this collection, however for third party dialects, support may vary.

  • argument_name – name of the parameter.

  • default – default value of the parameter.

attribute sqlalchemy.schema.CheckConstraint.columns: ReadOnlyColumnCollection[str, Column[Any]]

inherited from the ColumnCollectionMixin.columns attribute of ColumnCollectionMixin

A ColumnCollection representing the set of columns for this constraint.

method sqlalchemy.schema.CheckConstraint.contains_column(col: Column[Any]) bool

Return True if this constraint contains the given column.

Note that this object also contains an attribute .columns which is a ColumnCollection of Column objects.

method sqlalchemy.schema.CheckConstraint.copy(*, target_table: Table | None = None, **kw: Any) CheckConstraint

Deprecated since version 1.4: The CheckConstraint.copy() method is deprecated and will be removed in a future release.

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

inherited from the HasConditionalDDL.ddl_if() method of HasConditionalDDL

apply a conditional DDL rule to this schema item.

These rules work in a similar manner to the ExecutableDDLElement.execute_if() callable, with the added feature that the criteria may be checked within the DDL compilation phase for a construct such as CreateTable. HasConditionalDDL.ddl_if() currently applies towards the Index construct as well as all Constraint constructs.

Parameters:
  • dialect – string name of a dialect, or a tuple of string names to indicate multiple dialect types.

  • callable_ – a callable that is constructed using the same form as that described in ExecutableDDLElement.execute_if.callable_.

  • state – any arbitrary object that will be passed to the callable, if present.

New in version 2.0.

See also

Controlling DDL Generation of Constraints and Indexes - background and usage examples

attribute sqlalchemy.schema.CheckConstraint.dialect_kwargs

inherited from the DialectKWArgs.dialect_kwargs attribute of DialectKWArgs

A collection of keyword arguments specified as dialect-specific options to this construct.

The arguments are present here in their original <dialect>_<kwarg> format. Only arguments that were actually passed are included; unlike the DialectKWArgs.dialect_options collection, which contains all options known by this dialect including defaults.

The collection is also writable; keys are accepted of the form <dialect>_<kwarg> where the value will be assembled into the list of options.

See also

DialectKWArgs.dialect_options - nested dictionary form

attribute sqlalchemy.schema.CheckConstraint.dialect_options

inherited from the DialectKWArgs.dialect_options attribute of DialectKWArgs

A collection of keyword arguments specified as dialect-specific options to this construct.

This is a two-level nested registry, keyed to <dialect_name> and <argument_name>. For example, the postgresql_where argument would be locatable as:

arg = my_object.dialect_options['postgresql']['where']

New in version 0.9.2.

See also

DialectKWArgs.dialect_kwargs - flat dictionary form

attribute sqlalchemy.schema.CheckConstraint.info

inherited from the SchemaItem.info attribute of SchemaItem

Info dictionary associated with the object, allowing user-defined data to be associated with this SchemaItem.

The dictionary is automatically generated when first accessed. It can also be specified in the constructor of some objects, such as Table and Column.

attribute sqlalchemy.schema.CheckConstraint.kwargs

inherited from the DialectKWArgs.kwargs attribute of DialectKWArgs

A synonym for DialectKWArgs.dialect_kwargs.

class sqlalchemy.schema.ForeignKey

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.

method sqlalchemy.schema.ForeignKey.__init__(column: _DDLColumnArgument, _constraint: ForeignKeyConstraint | None = None, use_alter: bool = False, name: _ConstraintNameArgument = None, onupdate: str | None = None, ondelete: str | None = None, deferrable: bool | None = None, initially: str | None = None, link_to_name: bool = False, match: str | None = None, info: _InfoType | None = None, comment: str | None = None, _unresolvable: bool = False, **dialect_kw: Any)

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 ForeignKeyConstraint.use_alter for further description.

  • match – Optional string. If set, emit MATCH <value> when issuing DDL for this constraint. Typical values include SIMPLE, PARTIAL and FULL.

  • info – Optional data dictionary which will be populated into the SchemaItem.info attribute of this object.

  • comment

    Optional string that will render an SQL comment on foreign key constraint creation.

    New in version 2.0.

  • **dialect_kw – Additional keyword arguments are dialect specific, and passed in the form <dialectname>_<argname>. The arguments are ultimately handled by a corresponding ForeignKeyConstraint. See the documentation regarding an individual dialect at Dialects for detail on documented arguments.

classmethod sqlalchemy.schema.ForeignKey.argument_for(dialect_name, argument_name, default)

inherited from the DialectKWArgs.argument_for() method of DialectKWArgs

Add a new kind of dialect-specific keyword argument for this class.

E.g.:

Index.argument_for("mydialect", "length", None)

some_index = Index('a', 'b', mydialect_length=5)

The DialectKWArgs.argument_for() method is a per-argument way adding extra arguments to the DefaultDialect.construct_arguments dictionary. This dictionary provides a list of argument names accepted by various schema-level constructs on behalf of a dialect.

New dialects should typically specify this dictionary all at once as a data member of the dialect class. The use case for ad-hoc addition of argument names is typically for end-user code that is also using a custom compilation scheme which consumes the additional arguments.

Parameters:
  • dialect_name – name of a dialect. The dialect must be locatable, else a NoSuchModuleError is raised. The dialect must also include an existing DefaultDialect.construct_arguments collection, indicating that it participates in the keyword-argument validation and default system, else ArgumentError is raised. If the dialect does not include this collection, then any keyword argument can be specified on behalf of this dialect already. All dialects packaged within SQLAlchemy include this collection, however for third party dialects, support may vary.

  • argument_name – name of the parameter.

  • default – default value of the parameter.

attribute sqlalchemy.schema.ForeignKey.column

Return the target Column referenced by this ForeignKey.

If no target column has been established, an exception is raised.

method sqlalchemy.schema.ForeignKey.copy(*, schema: str | None = None, **kw: Any) ForeignKey

Deprecated since version 1.4: The ForeignKey.copy() method is deprecated and will be removed in a future release.

attribute sqlalchemy.schema.ForeignKey.dialect_kwargs

inherited from the DialectKWArgs.dialect_kwargs attribute of DialectKWArgs

A collection of keyword arguments specified as dialect-specific options to this construct.

The arguments are present here in their original <dialect>_<kwarg> format. Only arguments that were actually passed are included; unlike the DialectKWArgs.dialect_options collection, which contains all options known by this dialect including defaults.

The collection is also writable; keys are accepted of the form <dialect>_<kwarg> where the value will be assembled into the list of options.

See also

DialectKWArgs.dialect_options - nested dictionary form

attribute sqlalchemy.schema.ForeignKey.dialect_options

inherited from the DialectKWArgs.dialect_options attribute of DialectKWArgs

A collection of keyword arguments specified as dialect-specific options to this construct.

This is a two-level nested registry, keyed to <dialect_name> and <argument_name>. For example, the postgresql_where argument would be locatable as:

arg = my_object.dialect_options['postgresql']['where']

New in version 0.9.2.

See also

DialectKWArgs.dialect_kwargs - flat dictionary form

method sqlalchemy.schema.ForeignKey.get_referent(table: FromClause) Column[Any] | None

Return the Column in the given Table (or any FromClause) referenced by this ForeignKey.

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

attribute sqlalchemy.schema.ForeignKey.info

inherited from the SchemaItem.info attribute of SchemaItem

Info dictionary associated with the object, allowing user-defined data to be associated with this SchemaItem.

The dictionary is automatically generated when first accessed. It can also be specified in the constructor of some objects, such as Table and Column.

attribute sqlalchemy.schema.ForeignKey.kwargs

inherited from the DialectKWArgs.kwargs attribute of DialectKWArgs

A synonym for DialectKWArgs.dialect_kwargs.

method sqlalchemy.schema.ForeignKey.references(table: Table) bool

Return True if the given Table is referenced by this ForeignKey.

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

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.

method sqlalchemy.schema.ForeignKeyConstraint.__init__(columns: _typing_Sequence[_DDLColumnArgument], refcolumns: _typing_Sequence[_DDLColumnArgument], name: _ConstraintNameArgument = None, onupdate: str | None = None, ondelete: str | None = None, deferrable: bool | None = None, initially: str | None = None, use_alter: bool = False, link_to_name: bool = False, match: str | None = None, table: Table | None = None, info: _InfoType | None = None, comment: str | None = None, **dialect_kw: Any) 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.

    The use of ForeignKeyConstraint.use_alter is particularly geared towards the case where two or more tables are established within a mutually-dependent foreign key constraint relationship; however, the MetaData.create_all() and MetaData.drop_all() methods will perform this resolution automatically, so the flag is normally not needed.

  • match – Optional string. If set, emit MATCH <value> when issuing DDL for this constraint. Typical values include SIMPLE, PARTIAL and FULL.

  • info – Optional data dictionary which will be populated into the SchemaItem.info attribute of this object.

  • comment

    Optional string that will render an SQL comment on foreign key constraint creation.

    New in version 2.0.

  • **dialect_kw – Additional keyword arguments are dialect specific, and passed in the form <dialectname>_<argname>. See the documentation regarding an individual dialect at Dialects for detail on documented arguments.

classmethod sqlalchemy.schema.ForeignKeyConstraint.argument_for(dialect_name, argument_name, default)

inherited from the DialectKWArgs.argument_for() method of DialectKWArgs

Add a new kind of dialect-specific keyword argument for this class.

E.g.:

Index.argument_for("mydialect", "length", None)

some_index = Index('a', 'b', mydialect_length=5)

The DialectKWArgs.argument_for() method is a per-argument way adding extra arguments to the DefaultDialect.construct_arguments dictionary. This dictionary provides a list of argument names accepted by various schema-level constructs on behalf of a dialect.

New dialects should typically specify this dictionary all at once as a data member of the dialect class. The use case for ad-hoc addition of argument names is typically for end-user code that is also using a custom compilation scheme which consumes the additional arguments.

Parameters:
  • dialect_name – name of a dialect. The dialect must be locatable, else a NoSuchModuleError is raised. The dialect must also include an existing DefaultDialect.construct_arguments collection, indicating that it participates in the keyword-argument validation and default system, else ArgumentError is raised. If the dialect does not include this collection, then any keyword argument can be specified on behalf of this dialect already. All dialects packaged within SQLAlchemy include this collection, however for third party dialects, support may vary.

  • argument_name – name of the parameter.

  • default – default value of the parameter.

attribute sqlalchemy.schema.ForeignKeyConstraint.column_keys

Return a list of string keys representing the local columns in this ForeignKeyConstraint.

This list is either the original string arguments sent to the constructor of the ForeignKeyConstraint, or if the constraint has been initialized with Column objects, is the string .key of each element.

attribute sqlalchemy.schema.ForeignKeyConstraint.columns: ReadOnlyColumnCollection[str, Column[Any]]

inherited from the ColumnCollectionMixin.columns attribute of ColumnCollectionMixin

A ColumnCollection representing the set of columns for this constraint.

method sqlalchemy.schema.ForeignKeyConstraint.contains_column(col: Column[Any]) bool

Return True if this constraint contains the given column.

Note that this object also contains an attribute .columns which is a ColumnCollection of Column objects.

method sqlalchemy.schema.ForeignKeyConstraint.copy(*, schema: str | None = None, target_table: Table | None = None, **kw: Any) ForeignKeyConstraint

Deprecated since version 1.4: The ForeignKeyConstraint.copy() method is deprecated and will be removed in a future release.

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

inherited from the HasConditionalDDL.ddl_if() method of HasConditionalDDL

apply a conditional DDL rule to this schema item.

These rules work in a similar manner to the ExecutableDDLElement.execute_if() callable, with the added feature that the criteria may be checked within the DDL compilation phase for a construct such as CreateTable. HasConditionalDDL.ddl_if() currently applies towards the Index construct as well as all Constraint constructs.

Parameters:
  • dialect – string name of a dialect, or a tuple of string names to indicate multiple dialect types.

  • callable_ – a callable that is constructed using the same form as that described in ExecutableDDLElement.execute_if.callable_.

  • state – any arbitrary object that will be passed to the callable, if present.

New in version 2.0.

See also

Controlling DDL Generation of Constraints and Indexes - background and usage examples

attribute sqlalchemy.schema.ForeignKeyConstraint.dialect_kwargs

inherited from the DialectKWArgs.dialect_kwargs attribute of DialectKWArgs

A collection of keyword arguments specified as dialect-specific options to this construct.

The arguments are present here in their original <dialect>_<kwarg> format. Only arguments that were actually passed are included; unlike the DialectKWArgs.dialect_options collection, which contains all options known by this dialect including defaults.

The collection is also writable; keys are accepted of the form <dialect>_<kwarg> where the value will be assembled into the list of options.

See also

DialectKWArgs.dialect_options - nested dictionary form

attribute sqlalchemy.schema.ForeignKeyConstraint.dialect_options

inherited from the DialectKWArgs.dialect_options attribute of DialectKWArgs

A collection of keyword arguments specified as dialect-specific options to this construct.

This is a two-level nested registry, keyed to <dialect_name> and <argument_name>. For example, the postgresql_where argument would be locatable as:

arg = my_object.dialect_options['postgresql']['where']

New in version 0.9.2.

See also

DialectKWArgs.dialect_kwargs - flat dictionary form

attribute sqlalchemy.schema.ForeignKeyConstraint.elements: List[ForeignKey]

A sequence of ForeignKey objects.

Each ForeignKey represents a single referring column/referred column pair.

This collection is intended to be read-only.

attribute sqlalchemy.schema.ForeignKeyConstraint.info

inherited from the SchemaItem.info attribute of SchemaItem

Info dictionary associated with the object, allowing user-defined data to be associated with this SchemaItem.

The dictionary is automatically generated when first accessed. It can also be specified in the constructor of some objects, such as Table and Column.

attribute sqlalchemy.schema.ForeignKeyConstraint.kwargs

inherited from the DialectKWArgs.kwargs attribute of DialectKWArgs

A synonym for DialectKWArgs.dialect_kwargs.

attribute sqlalchemy.schema.ForeignKeyConstraint.referred_table

The Table object to which this ForeignKeyConstraint references.

This is a dynamically calculated attribute which may not be available if the constraint and/or parent table is not yet associated with a metadata collection that contains the referred table.

class sqlalchemy.schema.HasConditionalDDL

define a class that includes the HasConditionalDDL.ddl_if() method, allowing for conditional rendering of DDL.

Currently applies to constraints and indexes.

Members

ddl_if()

New in version 2.0.

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

apply a conditional DDL rule to this schema item.

These rules work in a similar manner to the ExecutableDDLElement.execute_if() callable, with the added feature that the criteria may be checked within the DDL compilation phase for a construct such as CreateTable. HasConditionalDDL.ddl_if() currently applies towards the Index construct as well as all Constraint constructs.

Parameters:
  • dialect – string name of a dialect, or a tuple of string names to indicate multiple dialect types.

  • callable_ – a callable that is constructed using the same form as that described in ExecutableDDLElement.execute_if.callable_.

  • state – any arbitrary object that will be passed to the callable, if present.

New in version 2.0.

See also

Controlling DDL Generation of Constraints and Indexes - background and usage examples

class sqlalchemy.schema.PrimaryKeyConstraint

A table-level PRIMARY KEY constraint.

The PrimaryKeyConstraint object is present automatically on any Table object; it is assigned a set of Column objects corresponding to those marked with the Column.primary_key flag:

>>> my_table = Table('mytable', metadata,
...                 Column('id', Integer, primary_key=True),
...                 Column('version_id', Integer, primary_key=True),
...                 Column('data', String(50))
...     )
>>> my_table.primary_key
PrimaryKeyConstraint(
    Column('id', Integer(), table=<mytable>,
           primary_key=True, nullable=False),
    Column('version_id', Integer(), table=<mytable>,
           primary_key=True, nullable=False)
)

The primary key of a Table can also be specified by using a PrimaryKeyConstraint object explicitly; in this mode of usage, the “name” of the constraint can also be specified, as well as other options which may be recognized by dialects:

my_table = Table('mytable', metadata,
            Column('id', Integer),
            Column('version_id', Integer),
            Column('data', String(50)),
            PrimaryKeyConstraint('id', 'version_id',
                                 name='mytable_pk')
        )

The two styles of column-specification should generally not be mixed. An warning is emitted if the columns present in the PrimaryKeyConstraint don’t match the columns that were marked as primary_key=True, if both are present; in this case, the columns are taken strictly from the PrimaryKeyConstraint declaration, and those columns otherwise marked as primary_key=True are ignored. This behavior is intended to be backwards compatible with previous behavior.

For the use case where specific options are to be specified on the PrimaryKeyConstraint, but the usual style of using primary_key=True flags is still desirable, an empty PrimaryKeyConstraint may be specified, which will take on the primary key column collection from the Table based on the flags:

my_table = Table('mytable', metadata,
            Column('id', Integer, primary_key=True),
            Column('version_id', Integer, primary_key=True),
            Column('data', String(50)),
            PrimaryKeyConstraint(name='mytable_pk',
                                 mssql_clustered=True)
        )
classmethod sqlalchemy.schema.PrimaryKeyConstraint.argument_for(dialect_name, argument_name, default)

inherited from the DialectKWArgs.argument_for() method of DialectKWArgs

Add a new kind of dialect-specific keyword argument for this class.

E.g.:

Index.argument_for("mydialect", "length", None)

some_index = Index('a', 'b', mydialect_length=5)

The DialectKWArgs.argument_for() method is a per-argument way adding extra arguments to the DefaultDialect.construct_arguments dictionary. This dictionary provides a list of argument names accepted by various schema-level constructs on behalf of a dialect.

New dialects should typically specify this dictionary all at once as a data member of the dialect class. The use case for ad-hoc addition of argument names is typically for end-user code that is also using a custom compilation scheme which consumes the additional arguments.

Parameters:
  • dialect_name – name of a dialect. The dialect must be locatable, else a NoSuchModuleError is raised. The dialect must also include an existing DefaultDialect.construct_arguments collection, indicating that it participates in the keyword-argument validation and default system, else ArgumentError is raised. If the dialect does not include this collection, then any keyword argument can be specified on behalf of this dialect already. All dialects packaged within SQLAlchemy include this collection, however for third party dialects, support may vary.

  • argument_name – name of the parameter.

  • default – default value of the parameter.

attribute sqlalchemy.schema.PrimaryKeyConstraint.columns: ReadOnlyColumnCollection[str, Column[Any]]

inherited from the ColumnCollectionMixin.columns attribute of ColumnCollectionMixin

A ColumnCollection representing the set of columns for this constraint.

method sqlalchemy.schema.PrimaryKeyConstraint.contains_column(col: Column[Any]) bool

Return True if this constraint contains the given column.

Note that this object also contains an attribute .columns which is a ColumnCollection of Column objects.

method sqlalchemy.schema.PrimaryKeyConstraint.copy(*, target_table: Table | None = None, **kw: Any) ColumnCollectionConstraint

Deprecated since version 1.4: The ColumnCollectionConstraint.copy() method is deprecated and will be removed in a future release.

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

inherited from the HasConditionalDDL.ddl_if() method of HasConditionalDDL

apply a conditional DDL rule to this schema item.

These rules work in a similar manner to the ExecutableDDLElement.execute_if() callable, with the added feature that the criteria may be checked within the DDL compilation phase for a construct such as CreateTable. HasConditionalDDL.ddl_if() currently applies towards the Index construct as well as all Constraint constructs.

Parameters:
  • dialect – string name of a dialect, or a tuple of string names to indicate multiple dialect types.

  • callable_ – a callable that is constructed using the same form as that described in ExecutableDDLElement.execute_if.callable_.

  • state – any arbitrary object that will be passed to the callable, if present.

New in version 2.0.

See also

Controlling DDL Generation of Constraints and Indexes - background and usage examples

attribute sqlalchemy.schema.PrimaryKeyConstraint.dialect_kwargs

inherited from the DialectKWArgs.dialect_kwargs attribute of DialectKWArgs

A collection of keyword arguments specified as dialect-specific options to this construct.

The arguments are present here in their original <dialect>_<kwarg> format. Only arguments that were actually passed are included; unlike the DialectKWArgs.dialect_options collection, which contains all options known by this dialect including defaults.

The collection is also writable; keys are accepted of the form <dialect>_<kwarg> where the value will be assembled into the list of options.

See also

DialectKWArgs.dialect_options - nested dictionary form

attribute sqlalchemy.schema.PrimaryKeyConstraint.dialect_options

inherited from the DialectKWArgs.dialect_options attribute of DialectKWArgs

A collection of keyword arguments specified as dialect-specific options to this construct.

This is a two-level nested registry, keyed to <dialect_name> and <argument_name>. For example, the postgresql_where argument would be locatable as:

arg = my_object.dialect_options['postgresql']['where']

New in version 0.9.2.

See also

DialectKWArgs.dialect_kwargs - flat dictionary form

attribute sqlalchemy.schema.PrimaryKeyConstraint.info

inherited from the SchemaItem.info attribute of SchemaItem

Info dictionary associated with the object, allowing user-defined data to be associated with this SchemaItem.

The dictionary is automatically generated when first accessed. It can also be specified in the constructor of some objects, such as Table and Column.

attribute sqlalchemy.schema.PrimaryKeyConstraint.kwargs

inherited from the DialectKWArgs.kwargs attribute of DialectKWArgs

A synonym for DialectKWArgs.dialect_kwargs.

class sqlalchemy.schema.UniqueConstraint

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.

method sqlalchemy.schema.UniqueConstraint.__init__(*columns: _DDLColumnArgument, name: _ConstraintNameArgument = None, deferrable: bool | None = None, initially: str | None = None, info: _InfoType | None = None, _autoattach: bool = True, _column_flag: bool = False, _gather_expressions: List[_DDLColumnArgument] | None = None, **dialect_kw: Any) None

inherited from the sqlalchemy.schema.ColumnCollectionConstraint.__init__ method of ColumnCollectionConstraint

Parameters:
  • *columns – A sequence of column names or Column objects.

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

  • **dialect_kw – other keyword arguments including dialect-specific arguments are propagated to the Constraint superclass.

classmethod sqlalchemy.schema.UniqueConstraint.argument_for(dialect_name, argument_name, default)

inherited from the DialectKWArgs.argument_for() method of DialectKWArgs

Add a new kind of dialect-specific keyword argument for this class.

E.g.:

Index.argument_for("mydialect", "length", None)

some_index = Index('a', 'b', mydialect_length=5)

The DialectKWArgs.argument_for() method is a per-argument way adding extra arguments to the DefaultDialect.construct_arguments dictionary. This dictionary provides a list of argument names accepted by various schema-level constructs on behalf of a dialect.

New dialects should typically specify this dictionary all at once as a data member of the dialect class. The use case for ad-hoc addition of argument names is typically for end-user code that is also using a custom compilation scheme which consumes the additional arguments.

Parameters:
  • dialect_name – name of a dialect. The dialect must be locatable, else a NoSuchModuleError is raised. The dialect must also include an existing DefaultDialect.construct_arguments collection, indicating that it participates in the keyword-argument validation and default system, else ArgumentError is raised. If the dialect does not include this collection, then any keyword argument can be specified on behalf of this dialect already. All dialects packaged within SQLAlchemy include this collection, however for third party dialects, support may vary.

  • argument_name – name of the parameter.

  • default – default value of the parameter.

attribute sqlalchemy.schema.UniqueConstraint.columns: ReadOnlyColumnCollection[str, Column[Any]]

inherited from the ColumnCollectionMixin.columns attribute of ColumnCollectionMixin

A ColumnCollection representing the set of columns for this constraint.

method sqlalchemy.schema.UniqueConstraint.contains_column(col: Column[Any]) bool

Return True if this constraint contains the given column.

Note that this object also contains an attribute .columns which is a ColumnCollection of Column objects.

method sqlalchemy.schema.UniqueConstraint.copy(*, target_table: Table | None = None, **kw: Any) ColumnCollectionConstraint

Deprecated since version 1.4: The ColumnCollectionConstraint.copy() method is deprecated and will be removed in a future release.

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

inherited from the HasConditionalDDL.ddl_if() method of HasConditionalDDL

apply a conditional DDL rule to this schema item.

These rules work in a similar manner to the ExecutableDDLElement.execute_if() callable, with the added feature that the criteria may be checked within the DDL compilation phase for a construct such as CreateTable. HasConditionalDDL.ddl_if() currently applies towards the Index construct as well as all Constraint constructs.

Parameters:
  • dialect – string name of a dialect, or a tuple of string names to indicate multiple dialect types.

  • callable_ – a callable that is constructed using the same form as that described in ExecutableDDLElement.execute_if.callable_.

  • state – any arbitrary object that will be passed to the callable, if present.

New in version 2.0.

See also

Controlling DDL Generation of Constraints and Indexes - background and usage examples

attribute sqlalchemy.schema.UniqueConstraint.dialect_kwargs

inherited from the DialectKWArgs.dialect_kwargs attribute of DialectKWArgs

A collection of keyword arguments specified as dialect-specific options to this construct.

The arguments are present here in their original <dialect>_<kwarg> format. Only arguments that were actually passed are included; unlike the DialectKWArgs.dialect_options collection, which contains all options known by this dialect including defaults.

The collection is also writable; keys are accepted of the form <dialect>_<kwarg> where the value will be assembled into the list of options.

See also

DialectKWArgs.dialect_options - nested dictionary form

attribute sqlalchemy.schema.UniqueConstraint.dialect_options

inherited from the DialectKWArgs.dialect_options attribute of DialectKWArgs

A collection of keyword arguments specified as dialect-specific options to this construct.

This is a two-level nested registry, keyed to <dialect_name> and <argument_name>. For example, the postgresql_where argument would be locatable as:

arg = my_object.dialect_options['postgresql']['where']

New in version 0.9.2.

See also

DialectKWArgs.dialect_kwargs - flat dictionary form

attribute sqlalchemy.schema.UniqueConstraint.info

inherited from the SchemaItem.info attribute of SchemaItem

Info dictionary associated with the object, allowing user-defined data to be associated with this SchemaItem.

The dictionary is automatically generated when first accessed. It can also be specified in the constructor of some objects, such as Table and Column.

attribute sqlalchemy.schema.UniqueConstraint.kwargs

inherited from the DialectKWArgs.kwargs attribute of DialectKWArgs

A synonym for DialectKWArgs.dialect_kwargs.

function sqlalchemy.schema.conv(value: str, quote: bool | None = None) Any

Mark a string indicating that a name has already been converted by a naming convention.

This is a string subclass that indicates a name that should not be subject to any further naming conventions.

E.g. when we create a Constraint using a naming convention as follows:

m = MetaData(naming_convention={
    "ck": "ck_%(table_name)s_%(constraint_name)s"
})
t = Table('t', m, Column('x', Integer),
                CheckConstraint('x > 5', name='x5'))

The name of the above constraint will be rendered as "ck_t_x5". That is, the existing name x5 is used in the naming convention as the constraint_name token.

In some situations, such as in migration scripts, we may be rendering the above CheckConstraint with a name that’s already been converted. In order to make sure the name isn’t double-modified, the new name is applied using the conv() marker. We can use this explicitly as follows:

m = MetaData(naming_convention={
    "ck": "ck_%(table_name)s_%(constraint_name)s"
})
t = Table('t', m, Column('x', Integer),
                CheckConstraint('x > 5', name=conv('ck_t_x5')))

Where above, the conv() marker indicates that the constraint name here is final, and the name will render as "ck_t_x5" and not "ck_t_ck_t_x5"

Indexes

インデックスは、 Column のインラインの index キーワードを使って、1つの列に対して匿名で(自動生成された名前 ix_<columnlabel> )作成することができます。これはまた、別のUNIQUE制約を追加する代わりに、インデックス自体に一意性を適用するために unique の使用法を変更します。特定の名前を持つインデックスや複数の列を含むインデックスには、名前を必要とする Index 構文を使用します。

以下にいくつかの Index オブジェクトが関連付けられた Table を示します。”CREATEINDEX”のDDLはテーブルのcreate文の直後に発行されます。

metadata_obj = MetaData()
mytable = Table(
    "mytable",
    metadata_obj,
    # 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)

mytable.create(engine)
CREATE TABLE mytable ( col1 INTEGER, col2 INTEGER, col3 INTEGER, col4 INTEGER, col5 INTEGER, col6 INTEGER ) CREATE INDEX ix_mytable_col1 ON mytable (col1) CREATE UNIQUE INDEX ix_mytable_col2 ON mytable (col2) CREATE UNIQUE INDEX myindex ON mytable (col5, col6) CREATE INDEX idx_col34 ON mytable (col3, col4)

上記の例では、 Index 構文は、 Column オブジェクトを直接使用して、対応するテーブルに対して外部的に作成されることに注意してください。 Index は、 Table 内の”インライン”定義もサポートしており、列を識別するために文字列名を使用しています:

metadata_obj = MetaData()
mytable = Table(
    "mytable",
    metadata_obj,
    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),
)
i = Index("someindex", mytable.c.col5)
i.create(engine)
CREATE INDEX someindex ON mytable (col5)

Functional Indexes

Index は、ターゲットバックエンドでサポートされているように、SQLと関数式をサポートしています。降順の値を使用して列に対するインデックスを作成するには、 ColumnElement.desc() 修飾子を使用できます:

from sqlalchemy import Index

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

あるいは、PostgreSQLのような関数型インデックスをサポートするバックエンドでは、”case insensitive”インデックスを lower() 関数を使って作成することができます:

from sqlalchemy import func, Index

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

Index API

Object Name Description

Index

A table-level INDEX.

class sqlalchemy.schema.Index

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, typically by using the func construct in conjunction with table-bound Column objects:

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

An Index can also be manually associated with a Table, either through inline declaration or using Table.append_constraint(). When this approach is used, the names of the indexed columns can be specified as strings:

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

To support functional or expression-based indexes in this form, the text() construct may be used:

from sqlalchemy import text

Table("sometable", metadata,
                Column("name", String(50)),
                Column("address", String(100)),
                Index("some_index", text("lower(name)"))
        )

See also

Indexes - General information on Index.

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

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

Clustered Index Support - MSSQL-specific options available for the Index construct.

method sqlalchemy.schema.Index.__init__(name: str | None, *expressions: _DDLColumnArgument, unique: bool = False, quote: bool | None = None, info: _InfoType | None = None, _table: Table | None = None, _column_flag: bool = False, **dialect_kw: Any) None

Construct an index object.

Parameters:
  • name – The name of the index

  • *expressions – Column expressions to include in the index. The expressions are normally instances of Column, but may also be arbitrary SQL expressions which ultimately refer to a Column.

  • unique=False – Keyword only argument; if True, create a unique index.

  • quote=None – Keyword only argument; whether to apply quoting to the name of the index. Works in the same manner as that of Column.quote.

  • info=None – Optional data dictionary which will be populated into the SchemaItem.info attribute of this object.

  • **dialect_kw – Additional keyword arguments not mentioned above are dialect specific, and passed in the form <dialectname>_<argname>. See the documentation regarding an individual dialect at Dialects for detail on documented arguments.

classmethod sqlalchemy.schema.Index.argument_for(dialect_name, argument_name, default)

inherited from the DialectKWArgs.argument_for() method of DialectKWArgs

Add a new kind of dialect-specific keyword argument for this class.

E.g.:

Index.argument_for("mydialect", "length", None)

some_index = Index('a', 'b', mydialect_length=5)

The DialectKWArgs.argument_for() method is a per-argument way adding extra arguments to the DefaultDialect.construct_arguments dictionary. This dictionary provides a list of argument names accepted by various schema-level constructs on behalf of a dialect.

New dialects should typically specify this dictionary all at once as a data member of the dialect class. The use case for ad-hoc addition of argument names is typically for end-user code that is also using a custom compilation scheme which consumes the additional arguments.

Parameters:
  • dialect_name – name of a dialect. The dialect must be locatable, else a NoSuchModuleError is raised. The dialect must also include an existing DefaultDialect.construct_arguments collection, indicating that it participates in the keyword-argument validation and default system, else ArgumentError is raised. If the dialect does not include this collection, then any keyword argument can be specified on behalf of this dialect already. All dialects packaged within SQLAlchemy include this collection, however for third party dialects, support may vary.

  • argument_name – name of the parameter.

  • default – default value of the parameter.

method sqlalchemy.schema.Index.create(bind: _CreateDropBind, checkfirst: bool = False) None

Issue a CREATE statement for this Index, using the given Connection or Engine` for connectivity.

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

inherited from the HasConditionalDDL.ddl_if() method of HasConditionalDDL

apply a conditional DDL rule to this schema item.

These rules work in a similar manner to the ExecutableDDLElement.execute_if() callable, with the added feature that the criteria may be checked within the DDL compilation phase for a construct such as CreateTable. HasConditionalDDL.ddl_if() currently applies towards the Index construct as well as all Constraint constructs.

Parameters:
  • dialect – string name of a dialect, or a tuple of string names to indicate multiple dialect types.

  • callable_ – a callable that is constructed using the same form as that described in ExecutableDDLElement.execute_if.callable_.

  • state – any arbitrary object that will be passed to the callable, if present.

New in version 2.0.

See also

Controlling DDL Generation of Constraints and Indexes - background and usage examples

attribute sqlalchemy.schema.Index.dialect_kwargs

inherited from the DialectKWArgs.dialect_kwargs attribute of DialectKWArgs

A collection of keyword arguments specified as dialect-specific options to this construct.

The arguments are present here in their original <dialect>_<kwarg> format. Only arguments that were actually passed are included; unlike the DialectKWArgs.dialect_options collection, which contains all options known by this dialect including defaults.

The collection is also writable; keys are accepted of the form <dialect>_<kwarg> where the value will be assembled into the list of options.

See also

DialectKWArgs.dialect_options - nested dictionary form

attribute sqlalchemy.schema.Index.dialect_options

inherited from the DialectKWArgs.dialect_options attribute of DialectKWArgs

A collection of keyword arguments specified as dialect-specific options to this construct.

This is a two-level nested registry, keyed to <dialect_name> and <argument_name>. For example, the postgresql_where argument would be locatable as:

arg = my_object.dialect_options['postgresql']['where']

New in version 0.9.2.

See also

DialectKWArgs.dialect_kwargs - flat dictionary form

method sqlalchemy.schema.Index.drop(bind: _CreateDropBind, checkfirst: bool = False) None

Issue a DROP statement for this Index, using the given Connection or Engine for connectivity.

attribute sqlalchemy.schema.Index.info

inherited from the SchemaItem.info attribute of SchemaItem

Info dictionary associated with the object, allowing user-defined data to be associated with this SchemaItem.

The dictionary is automatically generated when first accessed. It can also be specified in the constructor of some objects, such as Table and Column.

attribute sqlalchemy.schema.Index.kwargs

inherited from the DialectKWArgs.kwargs attribute of DialectKWArgs

A synonym for DialectKWArgs.dialect_kwargs.