Migrations¶
Ferro integrates with Alembic, the industry-standard migration tool for Python, to provide robust and reliable schema management.
Integration Overview¶
Instead of reinventing a migration system, Ferro utilizes a SQLAlchemy bridge. This bridge translates Ferro's internal model registry into an in-memory SQLAlchemy MetaData object, which Alembic then uses to detect changes.
Installation¶
Ensure you have installed the migration dependencies:
Using get_metadata()¶
To connect Ferro to Alembic, you must update your env.py file (typically found in the migrations/ directory created by alembic init).
The get_metadata() function automatically discovers all registered Ferro models and returns a SQLAlchemy MetaData object.
# migrations/env.py
from ferro.migrations import get_metadata
from my_app.models import User, Post # Ensure models are imported to register them
# Pass the Ferro-generated metadata to Alembic
target_metadata = get_metadata()
Workflow¶
- Initialize Alembic: Run
alembic init migrationsif you haven't already. - Define Models: Create your Ferro models as usual.
- Generate Migration: Run the autogenerate command:
- Apply Migration: Update your database:
Precision Mapping¶
Ferro's migration bridge ensures high fidelity between your code and the database:
- Nullability: Automatically detects whether a field is required or optional (e.g.,
strvsstr | None). - Complex Types: Correctly maps Enums, Decimals, UUIDs, and JSON fields to the appropriate database-native types.
- Constraints: Translates
primary_key,unique, andindexmetadata (fromFerroFieldorferro.Field) directly into the migration script. - Foreign Keys: Automatically generates
FOREIGN KEYconstraints, including customon_deletebehaviors likeCASCADEorSET NULL. - Join Tables: Automatically discovers and includes hidden join tables for Many-to-Many relationships.