skip to content

Why do teams set SQLAlchemy's MetaData(naming_convention=...), and what names do its ix, uq, ck, fk and pk templates produce?

level: middleimportance: should knowfreq 40%

answer

  1. names fixed in Python, not by the database
  2. only ix is named by default
  3. templates with %(table_name)s tokens
  4. ck usually wants an explicit name

basics

~20 s

MetaData(naming_convention=...) gives every unnamed constraint and index a predictable name when its Table is built, so later DDL can refer to it. Without it SQLAlchemy names only indexes; other unnamed constraints get whatever name the database assigns.

solid answer

~40 s

`MetaData(naming_convention={...})` maps the keys `ix`, `uq`, `ck`, `fk` and `pk` (or the constraint classes) to string templates such as `"fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s"`. When a constraint or index without a name is attached to a `Table`, SQLAlchemy fills the template at construction time, so `unique=True` on `accounts.email` becomes `uq_accounts_email`. The default convention is only `{"ix": "ix_%(column_0_label)s"}`, so an unnamed `UniqueConstraint`, `ForeignKey`, `CheckConstraint` or primary key otherwise reaches the database unnamed and the backend picks a name that may differ per backend. Predictable names matter because dropping or altering a constraint later needs its name. A `ck` template using `%(constraint_name)s` requires an explicit `name=`, and a generated name over the dialect's identifier limit is truncated with a four-character hash suffix.

code

python · 34 lines
python
from sqlalchemy import CheckConstraint, Column, ForeignKey, Integer, MetaData, Numeric, String, Table
from sqlalchemy.dialects import postgresql
from sqlalchemy.schema import CreateIndex, CreateTable

metadata = MetaData(
    naming_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",
    }
)

accounts = Table(
    "accounts",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("email", String(255), nullable=False, unique=True),
)

invoices = Table(
    "invoices",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("account_id", ForeignKey("accounts.id"), nullable=False, index=True),
    Column("total", Numeric(12, 2), nullable=False),
    CheckConstraint("total >= 0", name="total_nonnegative"),
)

dialect = postgresql.dialect()
print(CreateTable(invoices).compile(dialect=dialect))
for index in invoices.indexes:
    print(CreateIndex(index).compile(dialect=dialect))

go deeper

for a junior

Know that MetaData(naming_convention=...) maps ix, uq, ck, fk and pk to name templates, and that plain MetaData() names only indexes.

for a middle

Explain the tokens, why names are fixed at Table construction, why ck templates use %(constraint_name)s, and how long generated names are truncated with a hash suffix.

for a senior

Expect the drift case: a convention added to an old schema names constraints that do not exist in the database, so plan the rename or pin the old names with conv().

for a principal

Treat the convention as a one-time decision for the shared package's MetaData, set before the first table ships, because changing it later means renaming constraints in every database.

## The problem a convention solves A constraint in SQL can be created without a name; the database then invents one. SQLAlchemy follows suit: an unnamed `UniqueConstraint`, `ForeignKey`, `CheckConstraint` or `PrimaryKeyConstraint` is emitted as plain `UNIQUE (...)`, `FOREIGN KEY (...)` and so on. That works until something must refer to the constraint by name: - `DROP CONSTRAINT` and most `ALTER` forms need the exact name; - different backends invent different names, so the same Python schema yields different names on PostgreSQL in production and SQLite in tests; - a migration tool that drafts changes from your `MetaData` can only write a name it can see in Python. The `MetaData.naming_convention` argument closes that gap by naming constraints in Python, at the moment each one is attached to its `Table`. ## The keys and the tokens The dictionary's keys are the short codes below (the `Index` class or a `Constraint` subclass also works as a key), and the values are `%`-style templates. | key | applies to | typical template | |---|---|---| | `ix` | `Index`, including `Column(index=True)` | `ix_%(column_0_label)s` | | `uq` | `UniqueConstraint`, including `Column(unique=True)` | `uq_%(table_name)s_%(column_0_name)s` | | `ck` | `CheckConstraint` | `ck_%(table_name)s_%(constraint_name)s` | | `fk` | `ForeignKeyConstraint`, including `ForeignKey()` | `fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s` | | `pk` | `PrimaryKeyConstraint` | `pk_%(table_name)s` | The tokens available include: - `%(table_name)s` and `%(referred_table_name)s`; - `%(column_0_name)s`, `%(column_0_label)s` (the table name and column name joined, as in `invoices_account_id`) and `%(column_0_key)s`; - `%(referred_column_0_name)s` for foreign keys; - multi-column forms such as `%(column_0_N_name)s` (all names joined by underscores) and `%(column_0N_name)s` (joined without them); - `%(constraint_name)s`, the name you passed explicitly; - a custom token, defined by adding a key whose value is a callable taking the constraint and the table. ## Defaults and edge cases 1. **The default convention is `{"ix": "ix_%(column_0_label)s"}`.** Plain `MetaData()` names indexes from `index=True` and leaves every other constraint unnamed. 2. **An explicit name usually wins.** `UniqueConstraint("email", name="accounts_email_key")` keeps that name when the `uq` template has no `%(constraint_name)s` token. 3. **`%(constraint_name)s` embellishes and demands a name.** With `"ck": "ck_%(table_name)s_%(constraint_name)s"`, `CheckConstraint("total >= 0", name="total_nonnegative")` becomes `ck_invoices_total_nonnegative`. An unnamed `CheckConstraint` raises `InvalidRequestError` ("Naming convention including %(constraint_name)s token requires that constraint is explicitly named.") as soon as the `Table` is built. A check written as a raw string gives `%(column_0_name)s` no column to find (the name comes out as `ck_invoices_`), which is why `ck` conventions usually take this form. 4. **`conv()` marks a name as final.** Wrapping a name in `sqlalchemy.schema.conv` tells SQLAlchemy it is already converted, so no template is applied, which is how an existing database's odd names are kept. 5. **Long names are truncated deterministically.** A generated name longer than the dialect's identifier limit (63 characters on PostgreSQL) is cut and given a four-character suffix from an md5 hash, so the same schema always gets the same name. An explicit name that is too long is not truncated; compiling it raises `IdentifierError`. ## Why the timing matters For ordinary constraints and indexes, names are computed when the object joins its `Table`, not when DDL is emitted. Two consequences: - `invoices.constraints` and `invoices.indexes` already carry their final names in Python, and anything that reads the `MetaData` (a migration tool's autogenerate included) copies those exact strings; - the convention must be on the `MetaData` before the tables are declared. Put it in the shared package's single `MetaData(...)` call so both services, and every test database, produce the same names. ## Reading the names back Because names exist before any DDL, you can check them in a plain unit test with no database: - `invoices.constraints` is a set of the table's constraint objects, each with a `.name`; - `invoices.indexes` holds the `Index` objects, so `index=True` on `account_id` shows up as `ix_invoices_account_id`; - compiling `CreateTable(invoices)` against a dialect shows each `CONSTRAINT <name>` clause as the database will receive it. A test that asserts no constraint in the shared `MetaData` has `name` set to `None` keeps a new unnamed one from slipping in. ## Adopting it on an existing schema Turning a convention on for a database created without one does not rename anything already in it: the Python objects now carry names such as `fk_invoices_account_id_accounts` while the database holds the names the backend invented. Either rename the live constraints once, or declare the old ones with explicit `conv()` names, so that later DDL refers to names that exist.

  • Why do ck conventions usually use %(constraint_name)s instead of %(column_0_name)s?
    A `CheckConstraint` is an arbitrary expression, often a raw string such as `"total >= 0"`, so SQLAlchemy may find no `Column` in it to supply column zero. `%(column_0_name)s` works only when the expression uses a `Column` or `column()` object. Requiring an explicit short name and wrapping it as `ck_%(table_name)s_%(constraint_name)s` works for every check.
  • You enable a naming convention on a schema that has run for a year without one. What breaks?
    Nothing in the database changes, but the `MetaData` now names constraints differently from the live ones, so any DDL generated from it, such as a drop or an alter, targets names that do not exist. Rename the live constraints once to match, or pin the existing names with `conv()` until a migration renames them.

  • SQLAlchemy names every constraint automatically even without a naming convention
  • Naming conventions are applied by the database when CREATE TABLE runs
  • A ck template with %(constraint_name)s works for unnamed check constraints
  • Turning on a convention renames the constraints already in the database
  • Generated names longer than the identifier limit make SQLAlchemy raise an error