skip to content

As a lead, what rules do you set for Alembic autogenerate on a SQLAlchemy team: who reviews drafts, and what goes into the shared env.py?

level: principalimportance: should knowfreq 30%

answer

  1. a draft, never the deliverable
  2. blind spots become checklist items
  3. one env.py, decided once
  4. process_revision_directives for house rules

basics

~20 s

Treat every autogenerated revision as a draft the author edits and a schema-aware reviewer approves, with a checklist for autogenerate's blind spots. Standardise env.py once: naming convention, compare options, table filters, batch rendering and revision hooks.

solid answer

~40 s

I make the rule explicit: autogenerate writes a draft, the author owns the final script, and a reviewer who knows the schema approves every revision, with extra scrutiny for `drop_table`, `drop_column`, type changes on large tables and NOT NULL columns added to populated ones. The checklist covers what autogenerate cannot see: renames drafted as drop plus add, CHECK constraints and server defaults under the default settings, and data steps between schema changes. The shared env.py is decided once: a `naming_convention` on `Base.metadata` from day one, a conscious choice on `compare_server_default`, an explicit `include_name` exclusion list, `render_as_batch` if SQLite runs anywhere, and a `process_revision_directives` hook that drops empty drafts. The trade-off is review time against data loss; I scale scrutiny with risk rather than reviewing a new nullable column like a dropped table.

code

python · 19 lines
python
# migrations/env.py, inside run_migrations_online()
def process_revision_directives(context, revision, directives):
    if getattr(config.cmd_opts, "autogenerate", False):
        script = directives[0]
        if script.upgrade_ops.is_empty():
            directives[:] = []
            print("No schema changes detected; no revision written.")

with connectable.connect() as connection:
    context.configure(
        connection=connection,
        target_metadata=target_metadata,
        compare_server_default=True,
        render_as_batch=connection.dialect.name == "sqlite",
        process_revision_directives=process_revision_directives,
    )

    with context.begin_transaction():
        context.run_migrations()

go deeper

for a junior

Know that a draft is never applied unread, and that someone other than the author reviews each revision before it merges.

for a middle

Explain which env.py options exist, compare_type, compare_server_default, include_name and render_as_batch, and what each adds to or removes from a draft.

for a senior

Show the checklist you review against: destructive operations, missing CHECKs and defaults, NOT NULL on populated tables, type rewrites and unusable downgrades.

for a principal

Argue how strict the policy should be: review cost versus data-loss risk, which blind spots to configure away and which to leave to people, and how much hook code the team can maintain.

## The decision a lead owns Alembic's documentation is blunt: autogenerate is **not intended to be perfect**, and its candidate migrations must always be reviewed and corrected by hand. A team still has to decide what that means in practice: who reviews, against what checklist, and which comparisons the tool itself is configured to make. There is no single right answer; the options trade review time, false alarms and tool complexity against the risk of shipping a migration that destroys data. ## Policy: who writes, who reviews 1. **The author owns the script.** Autogenerate produces a starting point; the developer reads every line, fixes renames, adds what is missing and writes any data step. 2. **A schema-aware reviewer approves.** Someone who knows the tables, their sizes and their consumers reviews every file in the versions directory. Many teams enforce this with a code-owner rule on that directory. 3. **Scrutiny scales with risk.** A new nullable column needs a glance. A `drop_table`, `drop_column`, a type change on a large table, or a NOT NULL column on a populated table needs the full checklist. The cost is reviewer time and a slower path for small changes. The alternative, merging drafts unread, saves minutes until a rename ships as `create_table` plus `drop_table`. ## The reviewer's checklist - every `drop_table` or `drop_column`: a deliberate deletion, a rename, or a model that env.py failed to import? - every model change in the pull request: is it in the draft? CHECK constraints and server defaults leave no trace under the default settings; - type changes: does this database rewrite the table for it, and for how long? - `nullable=False` on an existing column: what happens to rows that hold NULL today? - constraint names: real names, or `None` in a downgrade that cannot run? - `downgrade()`: does it restore the previous shape, or is the revision deliberately one-way? ## The shared env.py | Setting | Default | What a team decides | |---|---|---| | `naming_convention` on `Base.metadata` | indexes only | full uq/fk/ck/pk/ix keys before the first revision | | `compare_type` | `True` | keep it; replace with a callable only for custom types | | `compare_server_default` | `False` | enable only after testing it against your schema for false positives | | `include_name` / `include_object` | none | an explicit list or schema for tables you do not own | | `render_as_batch` | `False` | `True` if SQLite runs anywhere in the workflow | | `autogenerate_plugins` | `["alembic.autogenerate.*"]` | add the CHECK plugin only if every CHECK is named | | `process_revision_directives` | none | house rules applied to every draft | Two of these deserve care. **`compare_server_default`** catches default changes but can report changes that are not real; turning it on without a trial teaches people to ignore drafts. The **CHECK plugin**, `alembic.ext.checkconstraint_byname`, has been opt-in since Alembic 1.19.2; it matches by name only and reports spurious removals for unnamed constraints, so it belongs only on a schema where a convention names everything. ## Encoding house rules in hooks `process_revision_directives(context, revision, directives)` receives the generated `MigrationScript` objects before anything is written. A team can: - drop the draft when `script.upgrade_ops.is_empty()` by setting `directives[:] = []`, so an unchanged schema writes no file; - rewrite or strip operations, for example removing index drops for tables being dropped anyway, as Alembic's cookbook shows. `[post_write_hooks]` in `alembic.ini` can run the team's code formatter over every generated file, so drafts arrive in house style and review diffs stay small. A drift check in continuous integration, which runs the same comparison without writing a file, completes the loop and belongs with the deploy tooling. ## Where to stop More automation is not free. Every hook is code that runs in every developer's revision command and has to be maintained across Alembic upgrades. A small team on one database may be better served by the plain template, a naming convention and a disciplined review than by a dozen custom rules. Settings also drift: an option one developer flips locally changes what their drafts contain, so the comparison options belong in the committed env.py, not in personal habits. The lead's job is to pick the smallest set of settings that turns autogenerate's known blind spots into either a configured comparison or a checklist line, and to write down which is which.

  • Would you let a team skip autogenerate and write every Alembic revision by hand?
    It is a defensible choice for a small, stable schema or a team that distrusts generated code, but it costs time and invites typos in column definitions that autogenerate gets right. I prefer autogenerate plus review: it reliably catches added tables, columns, nullability and type changes, and the reviewer concentrates on the known blind spots.
  • How do you stop Alembic from writing an empty revision when nothing changed?
    Pass a `process_revision_directives` hook to `context.configure()`. When the command ran with `--autogenerate` and `directives[0].upgrade_ops.is_empty()` is true, set `directives[:] = []`; Alembic then writes no file.

  • Autogenerated revisions are generated code, so reviewing them is optional.
  • Turning on every comparison option makes the draft an exact diff of the schema.
  • A run that drafts nothing proves the database matches the models exactly.
  • Each developer should tune env.py comparison options for their own changes.
  • The CHECK plugin should be on everywhere because it detects changed expressions.

Assumes Alembic 1.20 with SQLAlchemy 2.1; the CHECK constraint plugin has been opt-in since Alembic 1.19.2, and compare_type has defaulted to True since 1.12.