In SQLAlchemy, how do you decide between declaring a legacy billing database's tables as Table objects and reflecting them at startup, when another team owns that database?
answer
- who owns the schema
- startup queries and availability
- what reflection cannot recover
- test databases without the legacy one
- declare what you write
basics
~20 sDeclare the tables your code writes or depends on closely: declared Table objects are reviewable and work offline. Reflect wide, read-only schemas another team changes, accepting startup catalog queries, lost Python-side detail and drift found only at query time.
solid answer
~40 sIt turns on ownership, change rate and testing. Declared `Table` objects in a shared package are reviewed like code, import without a database, can build a test schema with `create_all()`, and carry your `naming_convention`; their cost is drift, since nothing tells you when the owner alters a table. Reflection with `autoload_with` or `MetaData.reflect(only=[...])` always matches the live schema, but every process start issues catalog queries and needs the database reachable, it loses Python-side defaults and `Column.info`, its types are the dialect's own, and a dropped column surfaces only when a statement touches it. My default: declare what we write and query heavily; reflect wide, read-only legacy tables with `only=` and column overrides; and run a scheduled comparison against a copy of the real schema so drift becomes a ticket, not an outage.
go deeper
Know that a Table can be written by hand or reflected from the database, and that both work in the same Core statements.
Name what reflection loses (Python-side defaults, info, sequence links) and what it costs at startup, and how only= and column overrides narrow it.
Show the failure modes: a crash loop when reflection runs while the database is down, and a dropped column that fails at query time instead of at deploy.
Set a rule the team can follow: declare what you write, reflect narrow read-only sets, detect drift on a schedule, and revisit when ownership of the schema moves.
## The choice in front of the team A legacy billing database predates the services that now read it. Its owner is another team, it holds dozens of tables, and your two services need `accounts`, `invoices` and a few ledger tables. SQLAlchemy Core can describe those tables in two ways: - **Declared**: `Table("invoices", metadata, Column(...), ...)` written in a package both services import. - **Reflected**: `Table("invoices", metadata, autoload_with=engine)` or `metadata.reflect(engine, only=[...])`, run when the process starts, building the same kind of `Table` from the live catalog. Both produce objects that `select()`, `insert()` and the rest of Core accept, so the decision is about cost and risk, not capability. ## What each option costs | concern | declared tables | reflected at startup | |---|---|---| | source of truth | the code, reviewed in pull requests | the live database | | database needed to import | no | yes, at every process start | | startup cost | none | catalog queries per process, more with `resolve_fks` pulling neighbours | | Python-side `default=`, `Column.info` | kept | lost | | types | exactly what you wrote | the dialect's own, e.g. `NUMERIC(precision=12, scale=2)` | | empty test schema via `create_all()` | yes | only by reflecting a real copy first, and its DDL may not match the original | | constraint names | follow your `naming_convention` | whatever the database holds | | schema drift | silent until a query fails | absorbed until code names a column that vanished | ## Where reflection hurts - **Availability coupling.** A service that reflects at import cannot even start when the legacy database is slow or down, which turns a dependency outage into a crash loop of every replica. - **Startup multiplication.** Each worker process reflects on its own, so many processes started together all query the catalog at once. - **Lost intent.** Reflection rebuilds only what the database stores; Python-side defaults, the `info` dictionary and a column's `Sequence` association are gone, and server defaults come back in the database's own spelling. - **Late failure.** If the owner drops `invoices.legacy_ref`, the reflected `Table` simply lacks it; the code that uses `invoices.c.legacy_ref` fails when it runs, not at deploy. A table the owner dropped stays in a long-lived `MetaData`, since `reflect()` takes no action for vanished tables. ## Where declaring hurts - **Drift is silent.** When the owner widens a column or adds a NOT NULL column without a default, nothing in your code notices until an `INSERT` fails. - **Upkeep.** Dozens of wide tables you only read are a lot of code to keep accurate. - **Names.** To refer to an existing constraint you must reproduce its database name, usually with `conv()`, because your naming convention would invent a different one. ## A policy a lead can defend 1. **Declare what you write.** Tables your services insert into or update belong in the shared package, with explicit types and named constraints, because write paths fail hardest on a mismatch. 2. **Reflect the wide, read-only remainder lazily and narrowly**: `MetaData.reflect(engine, only=[...])` for the tables a feature reads, with `Column` overrides where a type or a missing primary key matters (a view needs one passed explicitly). 3. **Detect drift on a schedule, not at startup.** A job uses `inspect(engine)` against a copy of the real schema and compares `get_columns()` and `get_foreign_keys()` with the declared tables, opening a ticket on a mismatch, so drift reaches a person before it reaches a request. 4. **Test against something real.** Declared tables let unit tests build a schema with `create_all()`; the reflected part needs a copy of the owner's schema, so keep those tests few and explicit. 5. **Revisit when ownership changes.** If your team takes over the database, move every table to declared objects and put changes through migrations. ## Questions to ask before choosing - Who changes this schema, how often, and do they tell you first? - Do we write to these tables, or only read them? - How many processes start at once, and may they start while the database is down? - Can our tests run without the legacy database?
- The other team drops a column your reflected invoices table used. When and how does your service find out?Only when a statement touches it. After the next restart the reflected `Table` no longer has the column, so code that builds `invoices.c.legacy_ref` raises at that point, and a process still running on the old reflection sends SQL the database rejects. A scheduled comparison with `inspect(engine)` would have reported it earlier.
- Why not reflect once at build time and ship the result?Reflected `Table` objects are not code you can review; to ship them you would turn them into declared `Table` source, which is declaring with a head start. That is a reasonable migration path, but the output still needs a review for types, defaults and constraint names before it becomes the shared package.
- Reflection keeps Python-side column defaults, so nothing is lost
- Reflected tables cannot be used in Core select() or insert()
- Declared tables detect schema drift automatically at startup
- MetaData.reflect() removes tables that the owner has dropped
- Reflection at startup costs nothing because SQLAlchemy caches it across processes