In Alembic, after models rename a table, add a column, change a column's type and add a named CHECK constraint, what does autogenerate draft?
answer
- names, not intentions
- a rename looks like two tables
- compare_type now on by default
- CHECK detection is an opt-in plugin
basics
~20 sAlembic drafts the new column and the type change correctly, turns the table rename into op.create_table() plus op.drop_table(), which would lose the rows, and leaves out the CHECK constraint, because CHECK detection is off by default.
solid answer
~40 sAutogenerate compares names, so a renamed table appears as a new table plus a missing one: the draft holds `op.create_table('billing_document', ...)` and `op.drop_table('invoice')`, which would discard every row. You replace the pair with `op.rename_table('invoice', 'billing_document')`; a renamed column comes out the same way, as `add_column` plus `drop_column`. The new column is drafted as `op.add_column(...)`, with `nullable=True` when its annotation is `Mapped[str | None]`. The type change is drafted as `op.alter_column(..., existing_type=..., type_=...)`, because `compare_type` has defaulted to `True` since Alembic 1.12. The named CHECK constraint on an existing table is missing: in Alembic 1.20, CHECK detection is the opt-in plugin `alembic.ext.checkconstraint_byname`, so you add `op.create_check_constraint()` by hand. Server default changes are skipped too unless `compare_server_default=True`.
code
python · 21 linesfrom alembic import op
import sqlalchemy as sa
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('billing_document',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('customer_id', sa.Integer(), nullable=False),
sa.Column('amount', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['customer_id'], ['customer.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.drop_table('invoice')
op.add_column('customer', sa.Column('phone', sa.String(length=30), nullable=True))
op.alter_column('customer', 'email',
existing_type=sa.VARCHAR(length=100),
type_=sa.String(length=255),
existing_nullable=False)
# ### end Alembic commands ###go deeper
Remember the headline: a renamed table or column comes out as a drop plus an add, and you must edit it into op.rename_table() or alter_column(new_column_name=...).
Explain name-based matching, compare_type's default and its both-sides-have-the-argument rule, and why CHECK constraints and server defaults need opt-in settings.
Show that you audit a draft against the list of model changes, catch destructive drops before review, and know the CHECK plugin's name-only matching and spurious removals.
Decide which comparisons the team enables in env.py and which blind spots stay a reviewer's job, weighing false positives against changes that leave no trace in the draft.
## The scenario A team changes its SQLAlchemy models in one sitting: - the `Invoice` class becomes `BillingDocument`, and `__tablename__` changes from `invoice` to `billing_document`; - `Customer` gains `phone: Mapped[str | None] = mapped_column(String(30))`; - `Customer.email` widens from `String(100)` to `String(255)`; - `Customer` gets `CheckConstraint("length(email) > 3", name="ck_customer_email_len")` in `__table_args__`. Then someone runs `alembic revision --autogenerate`. The console prints `Detected added table 'billing_document'`, `Detected removed table 'invoice'`, `Detected added column 'customer.phone'` and `Detected type change from VARCHAR(length=100) to String(length=255) on 'customer.email'`. Nothing mentions the CHECK constraint. ## Why a rename becomes a drop and an add Autogenerate matches tables and columns **by name**. It sees a table called `billing_document` in the metadata that the database lacks, and a table called `invoice` in the database that the metadata lacks. Nothing records that one used to be the other, so it drafts: 1. `op.create_table('billing_document', ...)`, an empty new table; 2. `op.drop_table('invoice')`, which deletes the old table and **every row in it**. Run as drafted, the revision succeeds and the data is gone. Alembic's documentation lists table and column renames under what autogenerate **cannot detect** and says they must be hand-edited into a name change. The fix is `op.rename_table('invoice', 'billing_document')` in `upgrade()` and the reverse in `downgrade()`. A column rename is drafted as `op.add_column()` plus `op.drop_column()` and becomes `op.alter_column('customer', 'email', new_column_name='email_address')`. ## What it gets right - **New column**: `op.add_column('customer', sa.Column('phone', sa.String(length=30), nullable=True))`. The `nullable=True` comes from the `Optional` annotation; nullability changes on existing columns are detected as well. - **Type change**: `op.alter_column('customer', 'email', existing_type=sa.VARCHAR(length=100), type_=sa.String(length=255), existing_nullable=False)`. Type comparison is controlled by `compare_type` in `context.configure()`, which has defaulted to `True` since **Alembic 1.12**. It compares the outer type first, then arguments such as length and precision, but **only arguments both sides carry**: a model `String()` against a database `VARCHAR(100)` produces no change. Notice the `existing_type` and `existing_nullable` arguments in the drafted `alter_column()`. They describe the column as it is now, and some backends need them: MySQL restates the whole column definition on every alter, so without `existing_nullable` a column whose nullability is not being changed would be reset to NULL. Keep them when you hand-edit an alter. ## What it leaves out | Change | Default behaviour | How to get it | |---|---|---| | Named CHECK on an existing table | not drafted | write `op.create_check_constraint()` by hand, or enable the plugin | | CHECK expression edited, same name | never drafted, even with the plugin | hand-written drop and create | | Server default added or changed | not drafted | `compare_server_default=True` | | Table or column rename | drafted as drop plus add | hand-edit to a rename | CHECK detection arrived in Alembic 1.19.0 as a default plugin; **1.19.2 made it opt-in** and renamed it `alembic.ext.checkconstraint_byname`. Enabled, it compares CHECK constraints **by name only**, so an edited expression under an unchanged name is invisible, and an unnamed CHECK in the metadata is skipped while the database's own name for it can be reported as a spurious removal. A CHECK declared on a brand-new table is different: `op.create_table()` renders the whole `Table`, constraints included. ## The corrected revision The reviewed `upgrade()` keeps the generated `add_column` and `alter_column`, replaces the create/drop pair with `op.rename_table()`, and adds `op.create_check_constraint('ck_customer_email_len', 'customer', 'length(email) > 3')`. `downgrade()` gets the mirror image. Compiled for PostgreSQL, the result is `ALTER TABLE invoice RENAME TO billing_document`, `ALTER TABLE customer ADD COLUMN phone VARCHAR(30)`, `ALTER TABLE customer ALTER COLUMN email TYPE VARCHAR(255)` and `ALTER TABLE customer ADD CONSTRAINT ck_customer_email_len CHECK (length(email) > 3)`. ## Why the tool does not guess A drop of `invoice` and a create of `billing_document` with identical columns looks like a rename to a human, but it could equally be a deliberate replacement: a new table, the old one retired, data moved by a separate step. Alembic's design is to draft only what it can detect reliably and leave intent to the author. The same principle explains the CHECK constraint gap: CHECK expressions come back from the database rewritten in each backend's own form, so comparing them as text would report changes on nearly every run. ## The habit this teaches Read every `drop_table` and `drop_column` in a draft and ask whether it is really a rename. Then list the model changes you made and check that each one appears, because a missing CHECK or server default leaves no trace in the file.
- Why does Alembic's autogenerate draft a change for a model String(50) against a database VARCHAR(100), but nothing for a model String() against the same column?The default type comparison compares an argument such as length only when both sides carry it. `String(50)` against `VARCHAR(100)` differs and is drafted; `String()` has no length, so Alembic skips the comparison, since it cannot tell a backend's default length from a deliberate one, and drafts nothing. A callable passed as `compare_type` can apply stricter rules.
- How do you make Alembic draft named CHECK constraints, and when is that a bad idea?List `"alembic.ext.checkconstraint_byname"` in `autogenerate_plugins` beside `"alembic.autogenerate.*"`. It matches by name only, so edited expressions are never drafted, and an unnamed CHECK, including one a `Boolean` or `Enum` type creates with `create_constraint=True`, is skipped on the model side while the database's generated name shows up as a spurious removal. Use it only when every CHECK is named.
- Why does Alembic leave compare_server_default off by default?Server default comparison works for simple cases but cannot always give accurate results, because a database may report a default in a different form from the one the model wrote. Alembic keeps it off so a team can try it against its own schema first; it accepts `True` or a custom callable when the defaults are worth tracking.
Comparing two guest lists by name alone: a guest who changed surname shows up as one guest missing and one stranger added, and only someone who knows the guest can say it is the same person.
- Autogenerate notices a table rename and emits op.rename_table() for it.
- compare_type is off by default, so column type changes never reach the draft.
- Autogenerate always drafts newly added CHECK constraints on existing tables.
- A drop_table followed by create_table is harmless because the rows are copied over.
- If the draft says nothing about a server default, the database already has it.
Assumes Alembic 1.20 with SQLAlchemy 2.1: compare_type has defaulted to True since Alembic 1.12, and CHECK constraint detection became an opt-in plugin in 1.19.2.