Dependency Resolution
Database schema objects have complex interdependencies. A foreign key depends on the referenced table existing. An index depends on its table. A view depends on the tables it queries. pgtofu uses topological sorting to determine the correct execution order.The Dependency Graph
pgtofu builds a directed acyclic graph (DAG) of dependencies:Topological Sorting
pgtofu uses Kahn’s algorithm for topological sorting:Example
Given these changes:- Add table
users - Add column
orders.user_id - Add foreign key
fk_orders_user(references users) - Add index
idx_orders_user_id
- Add table
users - Add column
orders.user_id - Add foreign key
fk_orders_user - Add index
idx_orders_user_id
Dependency Categories
Explicit Dependencies
Dependencies declared in the schema:| Object | Depends On |
|---|---|
| Foreign Key | Referenced table and columns |
| Index | Table it indexes |
| Trigger | Table and trigger function |
| View | Tables/views it queries |
| Constraint | Table it belongs to |
Implicit Dependencies
Dependencies inferred from object types:| Object Type | Must Come After |
|---|---|
| Tables | Extensions, Types, Sequences |
| Views | Tables, other Views |
| Functions | Types, Tables |
| Triggers | Functions, Tables |
| Constraints | Tables (and referenced tables for FKs) |
| Indexes | Tables |
| Hypertables | Tables |
| Policies | Hypertables |
Type Dependencies
Custom types must be created before columns using them:Creation vs. Deletion Order
Creation Order
Objects are created in dependency order (dependencies first):Deletion Order
Objects are deleted in reverse dependency order (dependents first):Handling Foreign Keys
Foreign keys create inter-table dependencies:users(no external dependencies)orders(depends onusers)order_items(depends onorders)
Circular Dependencies
Some schemas have circular foreign key references:Detection
pgtofu detects cycles during topological sort. If the sorted result has fewer nodes than the graph, a cycle exists.Resolution Strategies
- Deferrable Constraints (recommended):
- Split Migrations:
- Create tables without circular FKs
- Add circular FKs in separate migration
View Dependencies
Views can depend on other views:- Creates
active_usersfirst - Creates
active_user_orderssecond
- Drops
active_user_ordersfirst - Drops
active_userssecond
Function Dependencies
Functions may depend on types or other functions:Graph Implementation
pgtofu uses a generic directed graph implementation:Debugging Dependencies
To understand why changes are ordered a certain way:- Run
pgtofu diffto see changes - Check the
depends_onfield in each change - Trace the dependency chain
See Also
- Schema Diffing - How changes are detected
- Migration Generation - How DDL is created
- Architecture - Internal implementation details