For Alembic autogenerate, why should a SQLAlchemy MetaData carry a naming_convention before the first revision is drafted?
answer
- who picks a constraint's name
- a downgrade that cannot run
- None as a constraint name
- op.f() and the uq/fk/ck keys
basics
~20 sWithout a convention, unique, foreign-key and CHECK constraints get whatever name the database invents, or none, so autogenerate drafts them as None and later drops cannot target them. A naming_convention makes names predictable; adopted late, it churns existing ones.
solid answer
~40 sSQLAlchemy's default `naming_convention` covers indexes only (`"ix": "ix_%(column_0_label)s"`), so `unique=True`, a `ForeignKey` or an unnamed `CheckConstraint` reaches the database without a name and the database picks one, `customer_email_key` on PostgreSQL, none at all on SQLite. Autogenerate then drafts `op.create_unique_constraint(None, 'customer', ['email'])`, and the matching `op.drop_constraint(None, ...)` in `downgrade()` cannot run; Alembic 1.20 marks it with a WARNING comment and a `UserWarning`. Put `MetaData(naming_convention={...})` with `uq`, `fk`, `ck`, `pk` and `ix` keys on the declarative `Base` and the draft renders `op.f('uq_customer_email')`, a name every environment shares. Do it before the first revision: added later, every unique constraint and index whose database name differs is drafted as a drop and re-create.
code
python · 29 linesfrom sqlalchemy import MetaData, String, create_engine, text
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from alembic.autogenerate import produce_migrations, render_python_code
from alembic.migration import MigrationContext
class Base(DeclarativeBase):
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",
})
class Customer(Base):
__tablename__ = "customer"
id: Mapped[int] = mapped_column(primary_key=True)
email: Mapped[str] = mapped_column(String(255), unique=True)
engine = create_engine("sqlite://")
with engine.begin() as conn:
conn.execute(text("CREATE TABLE customer (id INTEGER NOT NULL PRIMARY KEY, email VARCHAR(255) NOT NULL)"))
ctx = MigrationContext.configure(conn, opts={"target_metadata": Base.metadata})
script = produce_migrations(ctx, Base.metadata)
print(render_python_code(script.upgrade_ops))
print(render_python_code(script.downgrade_ops))go deeper
Remember that constraints need names to be dropped, that SQLAlchemy names only indexes by default, and that the convention lives on the declarative Base's MetaData.
Explain why an unnamed unique constraint produces a downgrade that cannot run, what op.f() marks, and why %(constraint_name)s forces explicit CHECK names.
Show you can plan a late adoption: which objects autogenerate will redraft as drop and re-create, and how to turn that churn into one reviewed rename revision.
Treat the convention as a day-one project standard, chosen once for every database the code runs on, because changing it later costs a migration on every environment.
## Who names a constraint A constraint in SQL has a name, and `ALTER TABLE ... DROP CONSTRAINT` needs it. When SQLAlchemy emits `CREATE TABLE` for a column declared `unique=True`, a `ForeignKey`, or a `CheckConstraint` with no `name=`, it sends no name, and the **database invents one**: - PostgreSQL uses its own pattern, such as `customer_email_key` for a unique constraint and `invoice_customer_id_fkey` for a foreign key; - SQLite keeps the constraint **unnamed**; - other backends use other patterns, some of them opaque generated codes. The same model therefore produces different constraint names on different databases, and nothing in the Python code records them. ## What autogenerate does with unnamed constraints Alembic's documentation lists **anonymously named constraints** among the things autogenerate cannot handle and tells you to give constraints names. In practice: 1. Adding `unique=True` to a column drafts `op.create_unique_constraint(None, 'customer', ['email'])`. `upgrade()` runs, and the database picks the name. 2. The generated `downgrade()` contains `op.drop_constraint(None, 'customer', type_='unique')`, which cannot run because DROP CONSTRAINT needs a name. Since **Alembic 1.20**, autogenerate writes a `# WARNING: constraint name is None` comment above that line and emits a `UserWarning` when the file is generated. 3. Months later, removing or changing that constraint means looking up what each database called it, and writing a revision that works on all of them. On SQLite there is a further cost: batch migrations rebuild the table and can only drop a constraint they can find by name. ## The fix: a naming convention on the metadata `MetaData(naming_convention=...)` takes a dictionary from constraint kind to a template, and SQLAlchemy names every constraint it creates from it: | Key | Applies to | Typical template | |---|---|---| | `ix` | `Index`, `index=True` | `ix_%(column_0_label)s` | | `uq` | `UniqueConstraint`, `unique=True` | `uq_%(table_name)s_%(column_0_name)s` | | `ck` | `CheckConstraint` | `ck_%(table_name)s_%(constraint_name)s` | | `fk` | `ForeignKey` | `fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s` | | `pk` | primary key | `pk_%(table_name)s` | With declarative mapping, the dictionary goes on the base: `class Base(DeclarativeBase): metadata = MetaData(naming_convention={...})`. Because `env.py` passes `Base.metadata` as `target_metadata`, Alembic's operations also apply the convention to any constraint created with `None` as its name. **SQLAlchemy's default convention is `{"ix": "ix_%(column_0_label)s"}`**, indexes only. Unique, foreign-key, CHECK and primary-key constraints stay unnamed until you add keys for them. ## What the draft looks like with a convention Autogenerate now renders `op.create_unique_constraint(op.f('uq_customer_email'), 'customer', ['email'])` and a downgrade of `op.drop_constraint(op.f('uq_customer_email'), 'customer', type_='unique')`. **`op.f()`** marks a name as final, so the convention is not applied to it a second time. You can also use `op.f()` yourself to reach a constraint whose real name does not follow the convention. A `ck` template that uses `%(constraint_name)s` needs a name to interpolate: an unnamed `CheckConstraint` under such a convention makes SQLAlchemy raise `InvalidRequestError: Naming convention including %(constraint_name)s token requires that constraint is explicitly named.` ## Spotting unnamed constraints in a draft Before a revision is committed, look for: - `None` as the first argument of `op.create_unique_constraint()`, `op.create_foreign_key()` or `op.create_check_constraint()`; - the `# WARNING: constraint name is None` comment above an `op.drop_constraint()` in `downgrade()`; - the `UserWarning` that the revision command prints while generating such a file; - `sa.UniqueConstraint('email')` or `sa.ForeignKeyConstraint(...)` without `name=` inside a drafted `op.create_table()`. Each one is a constraint whose name will be decided by whichever database runs the revision. ## Why "before the first revision" The convention changes the names the **models** expect, not the names already in the database. Autogenerate matches unique constraints and indexes by name, so after a late adoption it drafts a drop plus a re-create for each one whose database name differs, `customer_email_key` against `uq_customer_email`. Foreign keys are matched by their columns and target, so they are not redrafted. You then choose between: - shipping that churn once, as a reviewed revision that renames each constraint; - shaping the convention to match the names already in the database. Either costs a deliberate decision. Setting the convention before the first `alembic revision --autogenerate` costs nothing.
- What does op.f() mean in an Alembic revision, and when would you write it yourself?`op.f()` marks a string as an already-final constraint name, so the naming convention is not applied to it again. Autogenerate wraps converted names in it. You write it by hand to reach a constraint whose real name breaks the convention, such as `op.drop_constraint(op.f('some_check_const'), 't1', type_='check')`.
- Your ck convention uses %(constraint_name)s and someone declares CheckConstraint('amount >= 0') with no name. What happens?SQLAlchemy raises `InvalidRequestError` when the constraint is attached to its table: "Naming convention including %(constraint_name)s token requires that constraint is explicitly named." The token has nothing to interpolate, so every CHECK must get `name=`. That is the point: the convention cannot invent a meaningful CHECK name.
- SQLAlchemy names unique and foreign-key constraints by default, so a convention changes nothing.
- Every database names an unnamed constraint the same way, so the names are predictable anyway.
- op.drop_constraint(None, ...) drops whichever constraint matches the columns.
- A naming convention can be added at any time without drafting extra changes.
- op.f() applies the naming convention to a name.
Assumes Alembic 1.20, which added the WARNING comment and UserWarning for a rendered drop_constraint() whose name is None.