Alembic autogenerate drafts op.drop_table() for a table your SQLAlchemy models still define, and for tables another system owns: what causes each, and how do you fix it?
answer
- what is in Base.metadata right now
- a class registers when its module runs
- everything reflected is fair game
- include_name before reflection, include_object after
basics
~20 sThe model's module was never imported, so its table is missing from Base.metadata; other tables are reflected but appear in no model. Import every model module in env.py, and exclude foreign tables with an include_name hook.
solid answer
~40 sA declarative class adds its `Table` to `Base.metadata` only when its module is imported. If env.py imports `Base` but never reaches `models/invoice.py`, autogenerate sees an `invoice` table in the database and none in `target_metadata`, and drafts `op.drop_table('invoice')`; the fix is a models package that imports every module, imported by env.py. Separately, autogenerate reflects every table in the connection's default schema, so tables another system created, such as a task queue's, also appear as removals. An `include_name(name, type_, parent_names)` hook passed to `context.configure()` returning `False` for those names filters them before reflection. Prefer an explicit exclusion list over the common `name in target_metadata.tables` filter: that filter also hides the import bug, and it stops autogenerate from ever drafting a drop for a model you deliberately deleted.
code
python · 20 lines# migrations/env.py (excerpt)
from myapp.models import Base # models/__init__.py imports every model module
target_metadata = Base.metadata
EXTERNAL_TABLES = {"job_queue", "job_queue_history"}
def include_name(name, type_, parent_names):
if type_ == "table":
return name not in EXTERNAL_TABLES
return True
# ... inside run_migrations_online():
# context.configure(
# connection=connection,
# target_metadata=target_metadata,
# include_name=include_name,
# )go deeper
Know that a model's table appears in Base.metadata only after its module is imported, and that a drafted drop_table must be questioned before review.
Explain the two hooks: include_name filters reflected names before reflection, include_object sees objects from both sides after reflection.
Diagnose which cause produced the drop, and explain why the name-in-metadata filter masks import bugs and blocks deliberate drops, preferring an explicit exclusion list.
Push foreign tables into their own schema or an agreed exclusion list in the shared env.py, so no developer's draft ever proposes dropping another system's data.
## Two different reasons for the same line Autogenerate drafts `op.drop_table('x')` when table `x` exists in the reflected database and not in `target_metadata`. That condition has two common causes, and the fixes differ. ## Cause 1: the model was never imported With SQLAlchemy's declarative mapping, a class such as `class Invoice(Base)` adds a `Table` named `invoice` to `Base.metadata` **at the moment its `class` statement executes**, which is when its module is imported. `Base.metadata` holds no table whose module has not been imported yet. A typical layout splits models across modules: `myapp/models/base.py`, `customer.py`, `invoice.py`. If env.py does `from myapp.models.base import Base` and the import chain happens to reach `customer.py` but not `invoice.py`, then: 1. `Base.metadata.tables` contains `customer` only; 2. the database still has `invoice`; 3. autogenerate drafts `op.drop_table('invoice')`, and the `downgrade()` recreates it. **Fix**: give the models one entry point. A `myapp/models/__init__.py` that imports `Base` and every model module, and an env.py that imports from that package, guarantee the metadata is complete. Diagnose it by printing `sorted(Base.metadata.tables)` from env.py. ## Cause 2: tables the application does not own Autogenerate compares the **whole schema** it reflects: every table in the connection's default schema, plus every other schema when `include_schemas=True` (default `False`). Tables created by something other than these models, such as a job scheduler's tables, an external tool's bookkeeping tables, or a reporting table another team maintains, are absent from the metadata and are drafted as drops on every run. **Fix**: tell autogenerate to ignore them with a hook in `context.configure()`. ## The two filtering hooks | Hook | Signature | Sees | When it runs | |---|---|---|---| | `include_name` | `(name, type_, parent_names)` | names of **reflected** objects only: schemas, tables, columns, indexes, unique and foreign-key constraints | before the object is reflected | | `include_object` | `(object, name, type_, reflected, compare_to)` | `SchemaItem` objects from **both** the database and the metadata | after full reflection | - `include_name` is the cheaper, recommended way to skip schemas and tables by name; `parent_names` carries `schema_name`, `table_name` and `schema_qualified_table_name` where relevant, and the default schema's name is passed as `None`. - `include_object` suits finer rules, such as skipping a model column flagged in `Column.info`, because it can see metadata-side objects too. Its cost is that a database object it rejects has already been reflected. ## The filter that hides your bugs A widely copied `include_name` returns `name in target_metadata.tables` for every table. It does silence foreign tables, but it also: - **hides cause 1**: a table whose model was not imported is filtered out instead of drafted as a drop, so the import bug never surfaces; - **hides real drops**: when you delete a model on purpose, autogenerate can no longer draft `op.drop_table()` for it, and someone has to remember to write it by hand. An **explicit exclusion list**, a set of known foreign table names or a prefix rule, keeps autogenerate honest about the application's own tables. Schema separation is cleaner still: keep foreign tables in another schema and leave `include_schemas` at `False`. ## Confirming which cause you have 1. Print `sorted(Base.metadata.tables)` at the top of env.py and run the revision command: if the table is missing there, it is an import problem. 2. If the table is not one any model ever described, it belongs to someone else, and a filter or a separate schema is the answer. 3. After the fix, run autogenerate again and confirm that the drop has disappeared from the draft. ## Reviewing a draft that drops tables `op.drop_table()` in a draft is never routine: 1. check that the model was deleted on purpose, not left unimported; 2. check that the table is not a rename, which autogenerate also renders as a drop plus a create; 3. check whether the rows need to be archived or migrated first. A drop that survives those three questions belongs in the revision. A drop that fails any of them is a sign that the environment, not the draft, needs fixing.
- When would you use Alembic's include_object instead of include_name?When the rule needs the object itself or the model side. `include_object` receives `SchemaItem` objects from both the metadata and the database, with a `reflected` flag, so it can skip a model column marked in `Column.info` or an index of a certain shape. `include_name` sees only reflected names, but runs before reflection, so it is cheaper for skipping whole schemas or tables.
- How do you keep Alembic's autogenerate out of other schemas while still comparing the default one?Leave `include_schemas` at its default `False`, and only the connection's default schema is scanned. If you need several schemas, set it to `True` and return `True` from `include_name` for `type_ == "schema"` only for the names you want, remembering that the default schema arrives as `None`.
- A drafted drop_table always means someone deleted the model class.
- include_name receives the model's Table objects as well as reflected ones.
- Filtering every table not in target_metadata.tables has no side effects.
- Autogenerate compares only the tables named in alembic.ini.
- Importing Base is enough, since Base.metadata finds subclasses lazily.