On PostgreSQL, SQLAlchemy's metadata.drop_all() raises CircularDependencyError for accounts and invoices tables whose foreign keys reference each other, though create_all() worked. Why, and how do you fix it?
answer
- a cycle cannot be topologically sorted
- CREATE can add a constraint afterwards
- DROP CONSTRAINT needs a name
- an fk template or use_alter
basics
~20 screate_all() breaks the cycle with ALTER TABLE ... ADD FOREIGN KEY, which needs no name. drop_all() must break it with ALTER TABLE ... DROP CONSTRAINT, which does. Name the cycle's foreign keys, ideally through an fk naming convention.
solid answer
~40 s`MetaData.sorted_tables` cannot order tables that reference each other; it warns and ignores those foreign keys. `create_all()` handles that on backends with ALTER by creating both tables without the cycle's constraints and then emitting `ALTER TABLE ... ADD FOREIGN KEY`, which PostgreSQL accepts unnamed and names itself. `drop_all()` needs the reverse, `ALTER TABLE ... DROP CONSTRAINT <name>`, but SQLAlchemy only knows names given in Python, so with unnamed constraints it raises `CircularDependencyError` asking for names. The fix is to name them: an `"fk"` entry in `MetaData(naming_convention=...)` names every foreign key, or pass `name=` on the `ForeignKey`. `use_alter=True` on one side marks the known cycle so the sort stops warning, but dropping it still needs a name.
code
plaintext · 1 linesqlalchemy.exc.CircularDependencyError: Can't sort tables for DROP; an unresolvable foreign key dependency exists between tables: accounts, invoices. Please ensure that the ForeignKey and ForeignKeyConstraint objects involved in the cycle have names so that they can be dropped using DROP CONSTRAINT.go deeper
Recall that tables are created and dropped in foreign-key order, and that tables referencing each other have no such order.
Explain why create_all() can add an unnamed foreign key with ALTER while drop_all() needs DROP CONSTRAINT with a name, and what use_alter=True changes.
Diagnose it from the error's table list, fix it with an fk naming convention, rename live constraints that predate it, and explain why SQLite tests never showed it.
Use the incident to justify a naming convention set once in the shared MetaData, so cycles and later constraint changes never depend on database-invented names.
## The schema that triggers it In the accounts-and-invoices package, `invoices.account_id` references `accounts.id`, and later someone adds `accounts.last_invoice_id` referencing `invoices.id` so an account page can show its latest bill. The two tables now depend on each other: a **foreign-key cycle**. Neither can be created first with its constraint inline, and neither can be dropped first while the other's constraint points at it. ## How SQLAlchemy orders DDL `create_all()` and `drop_all()` sort tables topologically by foreign key, the order `metadata.sorted_tables` exposes. A cycle has no topological order, so: - **`sorted_tables`** emits a warning ("Cannot correctly sort tables; there are unresolvable cycles between tables ...") and sorts as if the cycle's foreign keys did not exist. The warning text says it may become an error in a future release. - **`create_all()`** on a backend with `ALTER` support separates the cycle's constraints. It emits both `CREATE TABLE` statements without them, then `ALTER TABLE invoices ADD FOREIGN KEY(...)` and `ALTER TABLE accounts ADD FOREIGN KEY(...)`. An unnamed `ADD FOREIGN KEY` is valid SQL; PostgreSQL invents a name. - **`drop_all()`** must remove those constraints before dropping either table, and the only statement for that is `ALTER TABLE ... DROP CONSTRAINT <name>`. SQLAlchemy does not read the database's invented names back, so when no foreign key in the cycle has a Python-side name there is nothing it can drop to break the cycle, and the sort fails with `CircularDependencyError`. Naming one constraint of a two-table cycle is enough: `drop_all()` drops that one by `ALTER` and the other goes with its table. - **SQLite** has no usable `ALTER` for constraints. `create_all()` keeps the foreign keys inline, and `drop_all()` only warns that it cannot sort for DROP and drops in an unsorted order. ## Fixing it 1. **Name the foreign keys through the convention.** Add `"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s"` to the shared `MetaData(naming_convention=...)`. Every `ForeignKey` now has a name in Python, and `drop_all()` emits `ALTER TABLE invoices DROP CONSTRAINT fk_invoices_account_id_accounts` and the matching statement for `accounts` before the two `DROP TABLE` statements. 2. **Or name them one by one** with `ForeignKey("invoices.id", name="fk_accounts_last_invoice_id")` or a `ForeignKeyConstraint(..., name=...)`. 3. **Mark the known cycle with `use_alter=True`** on one side, typically the newer, nullable reference `accounts.last_invoice_id`. On a backend with `ALTER` that constraint is then always created and dropped by a separate `ALTER TABLE`, the other stays inline, and `sorted_tables` no longer warns. `use_alter` does not remove the naming requirement: dropping an unnamed `use_alter` constraint raises `CompileError` ("Can't emit DROP CONSTRAINT for constraint ...; it has no name"). 4. **For a database already created without names**, the Python names will not match the live ones. Rename the live constraints to the convention's names first, or `drop_all()` will issue `DROP CONSTRAINT` for names that do not exist. ## Where this bites in practice - **Test suites** that call `drop_all()` in teardown fail after the cycle is introduced, even though every test passed with the old schema. - **SQLite test runs hide it.** Locally the drop only warns, so the error first appears on a PostgreSQL CI database. - **Code that reads `sorted_tables` directly**, such as a fixture deleting rows in reverse order, gets the cycle warning, and a test run that turns warnings into errors fails there. `create_all()` itself does not warn. | situation | create_all() on PostgreSQL | drop_all() on PostgreSQL | |---|---|---| | cycle, unnamed foreign keys | CREATEs, then unnamed ADD FOREIGN KEY | `CircularDependencyError` | | cycle, fk naming convention | CREATEs, then named ADD CONSTRAINT | DROP CONSTRAINT by name, then DROP TABLE | | `use_alter=True` without a name | inline FK plus one ALTER | `CompileError`, no name | ## Preventing the next one - Put the `fk` template in the shared `MetaData` before the first table ships, so no foreign key is ever unnamed. - Treat a new foreign key that points from a parent back at a child, such as a "latest" or "default" reference, as a cycle to review, and decide whether it deserves `use_alter=True`. - Run the teardown path (`drop_all()`) at least once per pipeline against the backend production uses, not only SQLite. ## Diagnosing it quickly Read the error's table list: it names the tables in the cycle. Then look for a `ForeignKey` in each pointing at the other, check `fk.constraint.name` on each (it is `None` when unnamed), and confirm the `MetaData` has an `fk` template. A mock engine from `create_mock_engine()` prints the DDL `drop_all()` would emit without touching a database.
- Why does the same drop_all() pass on SQLite in local tests?SQLite's dialect reports no ALTER support, so `drop_all()` cannot plan `DROP CONSTRAINT` at all. Instead of raising it warns that it cannot sort tables for DROP and drops them in an unsorted order, which SQLite allows because foreign keys are not enforced unless the connection enables them. The error appears only on a backend such as PostgreSQL.
- When would you choose use_alter=True over relying on the automatic cycle handling?When the cycle is intentional and permanent. Marking one side with `use_alter=True` documents it, makes that constraint always go through `ALTER` on backends that support it, and stops the `sorted_tables` warning, which matters if warnings are turned into errors. Give it a name too, or dropping it raises `CompileError`.
- PostgreSQL forbids dropping tables whose foreign keys reference each other
- create_all() would also fail, so the schema itself is invalid
- use_alter=True alone fixes drop_all() without naming the constraint
- SQLAlchemy reads the database-assigned constraint names back before dropping
- Passing checkfirst=False to drop_all() avoids the sort