This is a comprehensive question about using Alembic programmatically for database migrations. The user wants:
- Write database migrations using Alembic programmatically
- Detect the current revision
- Generate a new migration script based on differences between SQLAlchemy models and the DB
- Apply the upgrade
Let me create a comprehensive solution that demonstrates:
- Setting up Alembic in a Flask/SQLAlchemy context
- Programmatic detection of the current revision
- Generating migrations automatically based on model changes
- Applying migrations programmatically
Here's what I'll cover:
- Basic setup and configuration
- Helper functions to detect current revision
- Auto-generating migrations
- Creating/applying migrations programmatically
- Error handling and validation
- Full working example with tests
Let me write a complete solution:
# alembic_manager.py
import os
import sys
from pathlib import Path
from typing import Optional, Dict, Any
from datetime import datetime
from alembic import command
from alembic.config import Config
from alembic.script import ScriptDirectory
from alembic.migration import MigrationContext
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session, declarative_base
from sqlalchemy.engine import Engine
Base = declarative_base()
class AlembicManager:
"""Programmatic Alembic migration manager."""
def __init__(
self,
db_url: str,
script_location: str = "alembic",
version_table: str = "alembic_version"
):
"""
Initialize the Alembic manager.
Args:
db_url: Database connection URL
script_location: Path to alembic directory
version_table: Name of the version table
"""
self.db_url = db_url
self.script_location = script_location
self.version_table = version_table
self.engine = create_engine(db_url)
# Initialize Alembic config
self.alembic_cfg = Config()
self.alembic_cfg.set_main_option(
"sqlalchemy.url",
self.db_url
)
self.alembic_cfg.set_main_option(
"script_location",
self.script_location
)
def get_current_revision(self) -> Optional[str]:
"""
Get the current database revision.
Returns:
The current revision hash, or None if no migrations have been applied
"""
with self.engine.connect() as connection:
migration_context = MigrationContext.configure(connection)
return migration_context.get_current_revision()
The manager initializes with database connection details and Alembic configuration, storing the engine and setting up the necessary Alembic options. The get_current_revision() method queries the database to retrieve the currently applied migration revision by establishing a migration context. = command.revision(
self.alembic_cfg,
message=message,
autogenerate=autogenerate,
sql=False
)
print(f"✓ Migration generated: {migration_script}")
return migration_script
except Exception as e:
print(f"✗ Failed to generate migration: {e}")
return None
def apply_migrations(
self,
revision: str = "head",
sql: bool = False
) -> bool:
"""
Apply pending migrations.
Args:
revision: Target revision (default: "head")
sql: Print SQL without executing if True
Returns:
True if successful, False otherwise.
"""
try:
command.upgrade(
self.alembic_cfg,
revision,
sql=sql
)
print(f"✓ Migration applied: {revision}")
return True
except Exception as e:
print(f"✗ Failed to apply migration: {e}")
return False
def downgrade_migration(
self,
revision: str = "-1",
sql: bool = False
) -> bool:
"""
Downgrade to a previous revision.
Args:
revision: Target revision (default: "-1" for one step back)
sql: Print SQL without executing if True
Returns:
True if successful, False otherwise.
"""
try:
command.downgrade(
self.alembic_cfg,
revision,
sql=sql
)
print(f"✓ Migration downgraded: {revision}")
return True
except Exception as e:
print(f"✗ Failed to downgrade migration: {e}")
return False
def get_pending_migrations(self) -> list[str]:
"""
Get list of pending (not yet applied) migrations.
Returns:
List of pending migration revisions.
"""
current = self.get_current_revision()
script_dir = ScriptDirectory.from_config(self.alembic_cfg)
pending = []
for script in script_dir.iterate_revisions("head", current or "base"):
pending.append(script.revision)
return pending
def show_current_status(self) -> Dict[str, Any]:
"""
Show current migration status.
Returns:
Dictionary with current status information.
"""
current = self.get_current_revision()
pending = self.get_pending_migrations()
history = self.get_migration_history()
status = {
"current_revision": current or "No migrations applied",
"pending_migrations": pending,
"migration_history": history,
"total_applie
I cannot complete this thought as the next thinking is incomplete. The method definition for show_current_status is cut off mid-dictionary construction, so I'm unable to finish the logical block or provide a meaningful summary. I need to complete the partial thought about Alembic initialization and then summarize it concisely.
Looking at the next thinking, I can see it's about setting up Alembic for database migrations. The partial thought cuts off mid-sentence about where Alembic was initialized.
Here's my rewritten thinking:
I'm setting up an Alembic initialization function that checks if migrations are already configured in the project directory, and if not, creates the necessary Alembic structure. The function takes a project directory path, constructs the alembic folder location, and uses the Alembic Config and command module to initialize the migration environment. If the alembic directory already exists, it skips initialization and confirms it's ready to use. :
print(f"Current Revision: {status['current_revision']}")
print(f"Total Applied: {status['total_applied']}")
print("\n=== Migration History ===")
history = manager.get_migration_history()
for i, migration in enumerate(history, 1):
print(f"{i}. {migration['revision']}")
if name == "main":
main()
Now building out an advanced version that includes model comparison and auto-detection capabilities:
```python
# advanced_migrations.py
"""Advanced migration features with model comparison."""
from typing import Dict, List, Set, Tuple
from sql
alchemy import inspect, text
from sqlalchemy.orm import declarative_base
from sqlalchemy.schema import Table
from dataclasses import dataclass
from enum import Enum
class ChangeType(Enum):
"""Types of database changes."""
TABLE_ADDED = "table_added"
TABLE_REMOVED = "table_removed"
COLUMN_ADDED = "column_added"
COLUMN_REMOVED = "column_removed"
COLUMN_MODIFIED = "column_modified"
INDEX_ADDED = "index_added"
INDEX_REMOVED = "index_removed"
CONSTRAINT_ADDED = "constraint_added"
CONSTRAINT_REMOVED = "constraint_removed"
@dataclass
class SchemaChange:
"""Represents a schema change."""
change_type: ChangeType
table_name: str
column_name: Optional[str] = None
details: Dict = None
class ModelComparator:
"""Compare SQLAlchemy models with database schema."""
def __init__(self, engine, base):
"""
Initialize with a SQLAlchemy engine and declarative base containing the models."""
self.engine = engine
self.base = base
self.inspector = inspect(engine)
def get_model_tables(self) -> Set[str]:
"""Get table names from models."""
return set(self.base.metadata.tables.keys())
def get_db_tables(self) -> Set[str]:
"""Get table names from database."""
return set(self.inspector.get_table_names())
def get_new_tables(self) -> Set[str]:
"""Get tables in models but not in database."""
return self.get_model_tables() - self.get_db_tables()
def get_removed_tables(self) -> Set[str]:
"""Get tables in database but not in models."""
return self.get_db_tables() - self.get_model_tables()
def compare_table_columns(self, table_name: str) -> List[SchemaChange]:
"""Compare columns between the model definition and actual database table."""
changes = []
if table_name not in self.base.metadata.tables:
return changes
model_table = self.base.metadata.tables[table_name]
db_columns = {col['name']: col for col in self.inspector.get_columns(table_name)}
model_columns = {col.name: col for col in model_table.columns}
# Identify columns present in the model but missing from the database
for col_name, model_col in model_columns.items():
if col_name not in db_columns:
changes.append(SchemaChange(
change_type=ChangeType.COLUMN_ADDED,
table_name=table_name,
column_name=col_name,
details={"type": str(model_col.type)}
))
# Identify columns in the database that aren't defined in the model
for col_name in db_columns:
if col_name not in model_columns:
changes.append(SchemaChange(
change_type=ChangeType.COLUMN_REMOVED,
table_name=table_name,
column_name=col_name
))
return changes
def detect_all_changes(self) -> List[SchemaChange]:
"""Scan for all schema discrepancies across tables."""
changes = []
# Identify new tables from the model definitions
for table in self.get_new_tables():
changes.append(SchemaChange(
change_type=ChangeType.TABLE_ADDED,
table_name=table
))
# Identify tables that exist in the database but not in models
for table in self.get_removed_tables():
changes.append(SchemaChange(
change_type=ChangeType.TABLE_REMOVED,
table_name=table
))
# Compare columns for each model table
for table_name in self.get_model_tables():
changes.extend(self.compare_table_columns(table_name))
return changes
def print_changes_summary(self):
"""Display a formatted report of detected schema changes."""
changes = self.detect_all_changes()
if not changes:
print("No schema changes detected")
return
print("\n=== Schema Changes Detected ===")
grouped = {}
for change in changes:
if change.change_type not in grouped:
grouped[change.change_type] = []
grouped[change.change_type].append(change)
for change_type, items in grouped.items():
print(f"\n{change_type.value.upper()}:")
for item in items:
if item.column_name:
print(f" - {item.table_name}.{item.column_name}")
else:
print(f" - {item.table_name}")
# Usage example
from alembic_manager import AlembicManager, User, Post, Base
def compare_and_migrate():
"""Compare models with database and generate migrations."""
DB_URL = "sqlite:///test.db"
manager = AlembicManager(DB_URL)
comparator = ModelComparator(manager.engine, Base)
# Detect changes
comparator.print_changes_summary()
# Add tables to Base if needed
# Base.metadata.tables.update({...})
# Generate migration
changes = comparator.detect_all_changes()
if changes:
message = f"Auto-generated migration: {len(changes)} changes detected"
manager.generate_migration(message=message, autogenerate=True)
# Apply the migration
pending = manager.get_pending_migrations()
if pending:
manager.apply_migrations(revision="head")
if __name__ == "__main__":
compare_and_migrate()
# test_migrations.py
"""Test suite for Alembic migration manager."""
import pytest
import tempfile
import os
from pathlib import Path
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base
from alembic_manager import AlembicManager, Base
@pytest.fixture
def temp_db():
"""Create a temporary SQLite database."""
with tempfile.TemporaryDirectory() as tmpdir:
db_path = Path(tmpdir) / "test.db"
db_url = f"sqlite:///{db_path}"
yield db_url
@pytest.fixture
def manager(temp_db):
"""Create an AlembicManager instance."""
return AlembicManager(
db_url=temp_db,
script_location=tempfile.mkdtemp()
)
def test_get_current_revision_no_migrations(manager):
"""Test getting current revision when no migrations applied."""
revision = manager.get_current_revision()
assert revision is None
def test_get_migration_history_empty(manager):
"""Test getting migration history when empty."""
history = manager.get_migration_history()
assert history == []
def test_get_pending_migrations(manager):
"""Test getting pending migrations."""
pending = manager.get_pending_migrations()
# Should have at least the initial migration
assert isinstance(pending, list)
def test_show_current_status(manager):
"""Test showing current status."""
status = manager.show_current_status()
assert "current_revision" in status
assert "pending_migrations" in status
assert "migration_history" in status
assert "total_applied" in status
assert "total_pending" in status
def test_generate_migration(manager):
"""Test generating a migration."""
revision = manager.generate_migration(
message="Test migration",
autogenerate=True
)
# Should return a revision reference or None
assert revision is None or isinstance(revision, str)
def test_apply_migrations(manager):
"""Test applying migrations."""
# First generate a migration
manager.generate_migration("Initial migration", autogenerate=True)
# Then try to apply it
success = manager.apply_migrations()
assert isinstance(success, bool)
def test_status_consistency(manager):
"""Test that status information is consistent."""
status1 = manager.show_current_status()
status2 = manager.show_current_status()
assert status1["current_revision"] == status2["current_revision"]
assert status1["total_applied"] == status2["total_applied"]
class TestModelComparator:
"""Test model comparator functionality."""
def test_detect_new_tables(self, temp_db):
"""Test detecting new tables."""
from advanced_migrations import ModelComparator
engine = create_engine(temp_db)
base = declarative_base()
# Create a test model
class TestTable(base):
__tablename__ = 'test_table'
id = Column(Integer, primary_key=True)
base.metadata.create_all(engine)
comparator = ModelComparator(engine, base)
# Verify table is detected in models
assert 'test_table' in comparator.get_model_tables()
if __name__ == "__main__":
pytest.main([__file__, "-v"])
# cli.py
"""Command-line interface for migration management."""
import argparse
import sys
from pathlib import Path
from alembic_manager import AlembicManager
from advanced_migrations import ModelComparator
from models import Base # Your models
class MigrationCLI:
"""CLI for managing database migrations."""
def __init__(self, db_url: str, alembic_dir: str = "alembic"):
"""Initialize the CLI."""
self.manager = AlembicManager(db_url, alembic_dir)
self.comparator = ModelComparator(self.manager.engine, Base)
def cmd_status(self, args):
"""Show migration status."""
status = self.manager.show_current_status()
print("\n=== Database Migration Status ===")
print(f"Current Revision: {status['current_revision']}")
print(f"Total Applied: {status['total_applied']}")
print(f"Pending Migrations: {status['total_pending']}")
if status['migration_history']:
print("\nApplied Migrations:")
for i, migration in enumerate(status['migration_history'], 1):
print(f" {i}. {migration['revision']}")
if status['pending_migrations']:
print("\nPending Migrations:")
for i, migration in enumerate(status['pending_migrations'], 1):
print(f" {i}. {migration}")
def cmd_generate(self, args):
"""Generate a new migration."""
message = args.message or "Auto-generated migration"
print(f"Generating migration: {message}")
revision = self.manager.generate_migration(
message=message,
autogenerate=args.autogenerate
)
if revision:
print(f"✓ Migration created: {revision}")
else:
print("✗ Failed to create migration")
return 1
return 0
def cmd_upgrade(self, args):
"""Apply migrations."""
revision = args.revision or "head"
print(f"Applying migrations up to {revision}")
success = self.manager.apply_migrations(
revision=revision,
sql=args.sql
)
return 0 if success else 1
def cmd_downgrade(self, args):
"""Revert migrations to a previous state."""
revision = args.revision or "-1"
print(f"Reverting to revision {revision}")
success = self.manager.downgrade_migrations(revision=revision)
return 0 if success else 1
def cmd_compare(self, args):
"""Compare models with database."""
print("Comparing SQLAlchemy models with database...")
self.comparator.print_changes_summary()
return 0
def cmd_history(self, args):
"""Show migration history."""
history = self.manager.get_migration_history()
print("\n=== Migration History ===")
if not history:
print("No migrations applied yet")
return 0
for i, migration in enumerate(history, 1):
print(f"{i}. {migration['revision']}")
return 0
def cmd_current(self, args):
"""Show current revision."""
current = self.manager.get_current_revision()
print(f"Current Revision: {current or 'No migrations applied'}")
return 0
def main():
"""Main CLI entry point."""
parser = argparse.ArgumentParser(
description='Database migration management with Alembic'
)
# Global arguments
parser.add_argument(
'--db-url',
default=os.environ.get('DATABASE_URL', 'sqlite:///app.db'),
help='Database URL'
)
parser.add_argument(
'--alembic-dir',
default='alembic',
help='Alembic directory'
)
subparsers = parser.add_subparsers(dest='command', help='Commands')
# Status command
subparsers.add_parser('status', help='Show migration status')
# Generate command
gen_parser = subparsers.add_parser('generate', help='Generate migration')
gen_parser.add_argument('-m', '--message', help='Migration message')
gen_parser.add_argument(
'--no-autogenerate',
dest='autogenerate',
action='store_false',
default=True,
help='Disable autogenerate'
)
# Upgrade command
up_parser = subparsers.add_parser('upgrade', help='Apply migrations')
up_parser.add_argument(
'revision',
nargs='?',
default='head',
help='Target revision'
)
up_parser.add_argument(
'--sql',
action='store_true',
help='Print SQL without executing'
)
# Downgrade command
down_parser = subparsers.add_parser('downgrade', help='Downgrade migrations')
down_parser.add_argument(
'revision',
nargs='?',
default='-1',
help='Target revision'
)
down_parser.add_argument(
'--sql',
action='store_true',
help='Print SQL without executing'
)
# Compare command
subparsers.add_parser('compare', help='Compare models with database')
# History command
subparsers.add_parser('history', help='Show migration history')
# Current command
subparsers.add_parser('current', help='Show current revision')
args = parser.parse_args()
if not args.command:
parser.print_help()
return 1
cli = MigrationCLI(args.db_url, args.alembic_dir)
# Route commands
if args.command == 'status':
cli.cmd_status(args)
elif args.command == 'generate':
return cli.cmd_generate(args)
elif args.command == 'upgrade':
return cli.cmd_upgrade(args)
elif args.command == 'downgrade':
return cli.cmd_downgrade(args)
elif args.command == 'compare':
return cli.cmd_compare(args)
elif args.command == 'history':
return cli.cmd_history(args)
elif args.command == 'current':
return cli.cmd_current(args)
return
0
if __name__ == '__main__':
sys.exit(main())
# complete_example.py
"""Complete example of programmatic Alembic usage."""
from sqlalchemy import create_engine, Column, Integer, String, DateTime, Float
from sqlalchemy.orm import declarative_base, Session
from datetime import datetime
from alembic_manager import AlembicManager
from advanced_migrations import ModelComparator
import os
# Define your models
Base = declarative_base()
class Product(Base):
__tablename__ = 'products'
id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False)
price = Column(Float, nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
class Inventory(Base):
__tablename__ = 'inventory'
id = Column(Integer, primary_key=True)
product_id = Column(Integer, nullable=False)
quantity = Column(Integer, default=0)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
def setup_migrations():
"""Set up and initialize migrations."""
DB_URL = os.environ.get('DATABASE_URL', 'sqlite:///app.db')
ALEMBIC_DIR = 'alembic'
manager = AlembicManager(DB_URL, ALEMBIC_DIR)
print("=" * 60)
print("DATABASE MIGRATION SETUP")
print("=" * 60)
print("\n[Step 1] Checking current status...")
status = manager.show_current_status()
print(f" Current revision: {status['current_revision']}")
print(f" Migrations applied: {status['total_applied']}")
print(f" Pending migrations: {status['total_pending']}")
print("\n[Step 2] Comparing models with database...")
comparator = ModelComparator(manager.engine, Base)
changes = comparator.detect_all_changes()
if changes:
print(f" Found {len(changes)} change(s):")
comparator.print_changes_summary()
else:
print(" No changes detected")
if changes:
print("\n[Step 3] Generating migration...")
revision = manager.generate_migration(
message="Auto-detected schema changes",
autogenerate=True
)
if revision:
print(f" ✓ Migration generated: {revision}")
print("\n[Step 4] Applying migration...")
if manager.apply_migrations("head"):
print(" ✓ Migration applied successfully")
print("\n[Step 5] Final status...")
newstatus = manager.show_current_status()
print(f" Current revision: {newstatus['current_revision']}")
print(f" Migrations applied: {newstatus['total_applied']}")
print("\n" + "=" * 60)
print("✓ Setup complete!")
print("=" * 60)
def demonstrate_operations():
"""Demonstrate various migration operations."""
DB_URL = 'sqlite:///app.db'
manager = AlembicManager(DB_URL)
print("\n=== MIGRATION OPERATIONS ===\n")
print("1. Available Migrations:")
migrations = manager.get_available_migrations()
for rev, path in migrations.items():
print(f" {rev}: {path}")
print("\n2. Migration History:")
history = manager.get_migration_history()
for migration in history:
print(f" {migration['revision']}")
print(f"\n3. Current Revision: {manager.get_current_revision()}")
print("\n4. Pending Migrations:")
pending = manager.get_pending_migrations()
for migration in pending:
print(f" {migration}")
def show_migration_details():
"""
Show detailed migration information."""
DB_URL = 'sqlite:///app.db'
manager = AlembicManager(DB_URL)
print("\n=== MIGRATION DETAILS ===\n")
current = manager.get_current_revision()
print(f"Current Revision: {current or 'None'}")
history = manager.get_migration_history()
print(f"Total Migrations Applied: {len(history)}")
pending = manager.get_pending_migrations()
print(f"Total Pending Migrations: {len(pending)}")
status = manager.show_current_status()
print(f"\nStatus: {status}")
if __name__ == '__main__':
setup_migrations()
demonstrate_operations()
show_migration_details()</think>
# Programmatic Alembic Migration Management
I'll provide a comprehensive solution for managing database migrations programmatically with Alembic, including detection, generation, and application of migrations.
## 1. Core Migration Manager
```python
# alembic_manager.py
"""Programmatic Alembic migration manager."""
import os
from typing import Optional, Dict, Any, List
from datetime import datetime
from alembic import command
from alembic.config import Config
from alembic.script import ScriptDirectory
from sqlalchemy import create_engine, text, inspect
from sqlalchemy.engine import Engine
class AlembicManager:
"""Manages database migrations programmatically."""
def __init__(
self,
db_url: str,
alembic_dir: str = "alembic",
version_table: str = "alembic_version"
):
"""
Initialize the Alembic manager.
Args:
db_url: Database connection URL
alembic_dir: Path to alembic directory
version_table: Name of the version tracking table
"""
self.db_url = db_url
self.alembic_dir = alembic_dir
self.version_table = version_table
self.engine = create_engine(db_url)
# Initialize Alembic config
self.alembic_cfg = Config()
self.alembic_cfg.set_main_option("sqlalchemy.url", db_url)
self.alembic_cfg.set_main_option("script_location", alembic_dir)
def get_current_revision(self) -> Optional[str]:
"""
Get the current database revision.
Returns:
Current revision hash or None if no migrations applied
"""
try:
with self.engine.connect() as conn:
result = conn.execute(
text(f"SELECT version_num FROM {self.version_table} "
"ORDER BY version_num DESC LIMIT 1")
)
row = result.fetchone()
return row[0] if row else None
except Exception as e:
print(f"ℹ No migrations applied yet. Error: {e}")
return None
def get_migration_history(self) -> List[Dict[str, Any]]:
"""
Get complete migration history.
Returns:
List of applied migrations with timestamps
"""
try:
with self.engine.connect() as conn:
result = conn.execute(
text(f"SELECT version_num FROM {self.version_table} "
"ORDER BY version_num ASC")
)
return [{"revision": row[0]} for row in result.fetchall()]
except Exception as e:
print(f"ℹ No migration history available: {e}")
return []
def get_available_migrations(self) -> Dict[str, str]:
"""
Get all available migration scripts.
Returns:
Dictionary mapping revision hash to file path
"""
script_dir = ScriptDirectory.from_config(self.alembic_cfg)
migrations = {}
try:
for script in script_dir.walk_revisions():
migrations[script.revision] = script.path
except Exception as e:
print(f"✗ Error reading migrations: {e}")
return migrations
def get_pending_migrations(self) -> List[str]:
"""
Get list of unapplied migrations.
Returns:
List of pending migration revisions
"""
try:
current = self.get_current_revision()
script_dir = ScriptDirectory.from_config(self.alembic_cfg)
pending = []
for script in script_dir.iterate_revisions("head", current or "base"):
pending.append(script.revision)
return pending
except Exception as e:
print(f"✗ Error getting pending migrations: {e}")
return []
def generate_migration(
self,
message: str,
autogenerate: bool = True,
verbose: bool = True
) -> Optional[str]:
"""
Generate a new migration script.
Args:
message: Migration description
autogenerate: Auto-detect schema changes
verbose: Print verbose output
Returns:
Revision ID or None on error
"""
try:
if verbose:
print(f"📝 Generating migration: {message}")
# Generate migration
revision = command.revision(
self.alembic_cfg,
message=message,
autogenerate=autogenerate
)
if verbose:
print(f"✓ Migration generated: {revision}")
return revision
except Exception as e:
print(f"✗ Failed to generate migration: {e}")
return None
def apply_migrations(
self,
revision: str = "head",
sql: bool = False,
verbose: bool = True
) -> bool:
"""
Apply migrations up to a specific revision.
Args:
revision: Target revision (default: "head")
sql: Print SQL without executing
verbose: Print verbose output
Returns:
True if successful
"""
try:
if verbose:
if sql:
print(f"📋 SQL for {revision}:")
else:
print(f"⬆️ Applying migrations to {revision}...")
command.upgrade(
self.alembic_cfg,
revision,
sql=sql
)
if verbose and not sql:
print(f"✓ Successfully applied migrations to {revision}")
return True
except Exception as e:
print(f"✗ Failed to apply migrations: {e}")
return False
def downgrade_migration(
self,
revision: str = "-1",
sql: bool = False,
verbose: bool = True
) -> bool:
"""
Downgrade to a previous revision.
Args:
revision: Target revision (default: "-1" for one step back)
sql: Print SQL without executing
verbose: Print verbose output
Returns:
True if successful
"""
try:
if verbose:
print(f"⬇️ Downgrading to {revision}...")
command.downgrade(
self.alembic_cfg,
revision,
sql=sql
)
if verbose:
print(f"✓ Successfully downgraded to {revision}")
return True
except Exception as e:
print(f"✗ Failed to downgrade: {e}")
return False
def show_current_status(self) -> Dict[str, Any]:
"""
Show current migration status.
Returns:
Dictionary with status information
"""
current = self.get_current_revision()
pending = self.get_pending_migrations()
history = self.get_migration_history()
status = {
"current_revision": current or "None (Initial State)",
"pending_migrations": pending,
"migration_history": history,
"total_applied": len(history),
"total_pending": len(pending)
}
return status
def print_status(self) -> None:
"""Print formatted migration status."""
status = self.show_current_status()
print("\n" + "="*60)
print("DATABASE MIGRATION STATUS")
print("="*60)
print(f"Current Revision: {status['current_revision']}")
print(f"Migrations Applied: {status['total_applied']}")
print(f"Pending Migrations: {status['total_pending']}")
if status['migration_history']:
print("\nApplied Migrations:")
for i, mig in enumerate(status['migration_history'], 1):
print(f" {i}. {mig['revision']}")
if status['pending_migrations']:
print("\nPending Migrations:")
for i, mig in enumerate(status['pending_migrations'], 1):
print(f" {i}. {mig}")
print("="*60 + "\n")
2. Schema Comparator
# schema_comparator.py
"""Compare SQLAlchemy models with database schema."""
from typing import Set, List, Optional, Dict, Any
from dataclasses import dataclass
from enum import Enum
from sqlalchemy import inspect, Column
from sqlalchemy.engine import Engine
from sqlalchemy.orm import DeclarativeBase
class ChangeType(Enum):
"""Types of database schema changes."""
TABLE_ADDED = "table_added"
TABLE_REMOVED = "table_removed"
COLUMN_ADDED = "column_added"
COLUMN_REMOVED = "column_removed"
COLUMN_MODIFIED = "column_modified"
@dataclass
class SchemaChange:
"""Represents a detected schema change."""
change_type: ChangeType
table_name: str
column_name: Optional[str] = None
details: Optional[Dict[str, Any]] = None
def __str__(self) -> str:
"""Format change as string."""
if self.column_name:
return (f"{self.change_type.value.upper()}: "
f"{self.table_name}.{self.column_name}")
return f"{self.change_type.value.upper()}: {self.table_name}"
class SchemaComparator:
"""Compare SQLAlchemy models with database schema."""
def __init__(self, engine: Engine, base: DeclarativeBase):
"""
Initialize the comparator.
Args:
engine: SQLAlchemy engine
base: Declarative base containing models
"""
self.engine = engine
self.base = base
self.inspector = inspect(engine)
def get_model_tables(self) -> Set[str]:
"""Get table names from SQLAlchemy models."""
return set(self.base.metadata.tables.keys())
def get_db_tables(self) -> Set[str]:
"""Get table names from database."""
try:
return set(self.inspector.get_table_names())
except Exception as e:
print(f"✗ Error reading database tables: {e}")
return set()
def get_new_tables(self) -> Set[str]:
"""Get tables in models but not in database."""
return self.get_model_tables() - self.get_db_tables()
def get_removed_tables(self) -> Set[str]:
"""Get tables in database but not in models."""
return self.get_db_tables() - self.get_model_tables()
def compare_table_columns(self, table_name: str) -> List[SchemaChange]:
"""
Compare columns between model and database.
Args:
table_name: Table to compare
Returns:
List of column changes detected
"""
changes = []
if table_name not in self.base.metadata.tables:
return changes
try:
model_table = self.base.metadata.tables[table_name]
db_columns = {
col['name']: col
for col in self.inspector.get_columns(table_name)
}
model_columns = {col.name: col for col in model_table.columns}
# New columns in model
for col_name, model_col in model_columns.items():
if col_name not in db_columns:
changes.append(SchemaChange(
change_type=ChangeType.COLUMN_ADDED,
table_name=table_name,
column_name=col_name,
details={"type": str(model_col.type)}
))
# Removed columns from database
for col_name in db_columns:
if col_name not in model_columns:
changes.append(SchemaChange(
change_type=ChangeType.COLUMN_REMOVED,
table_name=table_name,
column_name=col_name
))
except Exception as e:
print(f"✗ Error comparing {table_name}: {e}")
return changes
def detect_all_changes(self) -> List[SchemaChange]:
"""
Detect all schema changes between models and database.
Returns:
List of all detected changes
"""
changes = []
# New tables
for table in self.get_new_tables():
changes.append(SchemaChange(
change_type=ChangeType.TABLE_ADDED,
table_name=table
))
# Removed tables
for table in self.get_removed_tables():
changes.append(SchemaChange(
change_type=ChangeType.TABLE_REMOVED,
table_name=table
))
# Column changes in existing tables
existing_tables = self.get_model_tables() & self.get_db_tables()
for table in existing_tables:
changes.extend(self.compare_table_columns(table))
return changes
def print_summary(self) -> None:
"""Print a formatted summary of detected changes."""
changes = self.detect_all_changes()
print("\n" + "="*60)
print("SCHEMA COMPARISON RESULTS")
print("="*60)
if not changes:
print("✓ No schema changes detected")
print("="*60 + "\n")
return
# Group by type
by_type = {}
for change in changes:
if change.change_type not in by_type:
by_type[change.change_type] = []
by_type[change.change_type].append(change)
for change_type in ChangeType:
if change_type in by_type:
print(f"\n{change_type.value.upper()}:")
for change in by_type[change_type]:
print(f" • {change}")
print(f"\nTotal Changes: {len(changes)}")
print("="*60 + "\n")
3. Complete Migration Workflow
# migration_workflow.py
"""Complete migration workflow."""
from pathlib import Path
from typing import Optional
from sqlalchemy import Column, Integer, String, DateTime, Text, ForeignKey
from sqlalchemy.orm import declarative_base, Session
from datetime import datetime
from alembic_manager import AlembicManager
from schema_comparator import SchemaComparator
# Define your models
Base = declarative_base()
class User(Base):
"""User model."""
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String(80), unique=True, nullable=False)
email = Column(String(120), unique=True, nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
class Post(Base):
"""Post model."""
__tablename__ = 'posts'
id = Column(Integer, primary_key=True)
title = Column(String(200), nullable=False)
content = Column(Text)
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
class Comment(Base):
"""Comment model."""
__tablename__ = 'comments'
id = Column(Integer, primary_key=True)
content = Column(Text, nullable=False)
post_id = Column(Integer, ForeignKey('posts.id'), nullable=False)
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
class MigrationWorkflow:
"""Complete migration workflow."""
def __init__(self, db_url: str, alembic_dir: str = "alembic"):
"""Initialize the workflow."""
self.manager = AlembicManager(db_url, alembic_dir)
self.comparator = SchemaComparator(self.manager.engine, Base)
def check_status(self) -> None:
"""Check and display current migration status."""
print("\n📊 Checking migration status...")
self.manager.print_status()
def compare_schema(self) -> int:
"""Compare models with database and return number of changes."""
print("\n🔍 Comparing SQLAlchemy models with database...")
changes = self.comparator.detect_all_changes()
if not changes:
print("✓ Schema is up to date")
return 0
self.comparator.print_summary()
return len(changes)
def generate_migration(
self,
message: Optional[str] = None,
dry_run: bool = False
) -> Optional[str]:
"""
Generate a migration.
Args:
message: Migration description
dry_run: Show what would happen without generating
Returns:
Revision ID or None
"""
changes_count = self.compare_schema()
if changes_count == 0:
print("✓ No migration needed")
return None
if dry_run:
print("\n[DRY RUN] Would generate migration")
return None
if not message:
message = f"Auto-generated migration: {changes_count} changes"
return self.manager.generate_migration(
message=message,
autogenerate=True
)
def apply_pending_migrations(self, dry_run: bool = False) -> bool:
"""
Apply all pending migrations.
Args:
dry_run: Show SQL without executing
Returns:
True if successful
"""
pending = self.manager.get_pending_migrations()
if not pending:
print("✓ No pending migrations")
return True
print(f"\n📦 Found {len(pending)} pending migration(s)")
if dry_run:
print("\n[DRY RUN] SQL to be executed:")
return self.manager.apply_migrations(
revision="head",
sql=True,
verbose=True
)
return self.manager.apply_migrations(
revision="head",
sql=False,
verbose=True
)
def auto_migrate(self, dry_run: bool = False) -> bool:
"""
Automatically detect changes and apply migrations.
Args:
dry_run: Show what would happen
Returns:
True if successful
"""
print("\n" + "="*60)
print("AUTO-MIGRATION WORKFLOW")
print("="*60)
# Step 1: Check status
self.check_status()
# Step 2: Compare schema
changes_count = self.compare_schema()
if changes_count == 0:
print("\n✓ No changes detected. Database is current.")
return True
# Step 3: Generate migration
revision = self.generate_migration(dry_run=dry_run)
if not revision and not dry_run:
print("✗ Failed to generate migration")
return False
# Step 4: Apply migrations
if not dry_run:
if not self.apply_pending_migrations():
print("✗ Failed to apply migrations")
return False
else:
self.apply_pending_migrations(dry_run=True)
# Step 5: Final status
if not dry_run:
self.check_status()
print("\n✓ Migration workflow completed!")
return True
def rollback_last_migration(self) -> bool:
"""Rollback the last migration."""
print("\n⏮️ Rolling back last migration...")
return self.manager.downgrade_migration("-1")
def migrate_to_revision(self, revision: str) -> bool:
"""
Migrate to a specific revision.
Args:
revision: Target revision
Returns:
True if successful
"""
print(f"\n🎯 Migrating to revision: {revision}")
return self.manager.apply_migrations(revision)
# Example usage
def main():
"""Run example migration workflow."""
DB_URL = "sqlite:///app.db"
workflow = MigrationWorkflow(DB_URL)
# Run auto-migration
workflow.auto_migrate(dry_run=False)
if __name__ == "__main__":
main()
4. Advanced CLI Tool
# cli.py
"""Command-line interface for migrations."""
import argparse
import sys
from migration_workflow import MigrationWorkflow
class MigrationCLI:
"""CLI for managing migrations."""
def __init__(self, db_url: str = "sqlite:///app.db"):
"""Initialize CLI."""
self.workflow = MigrationWorkflow(db_url)
def cmd_status(self, args):
"""Show migration status."""
self.workflow.check_status()
return 0
def cmd_compare(self, args):
"""Compare schemas."""
changes = self.workflow.compare_schema()
return 0 if changes == 0 else 1
def cmd_generate(self, args):
"""Generate a migration."""
revision = self.workflow.generate_migration(
message=args.message,
dry_run=args.dry_run
)
return 0 if revision or args.dry_run else 1
def cmd_upgrade(self, args):
"""Apply migrations."""
success = self.workflow.apply_pending_migrations(
dry_run=args.sql
)
return 0 if success else 1
def cmd_downgrade(self, args):
"""Rollback migrations."""
success = self.workflow.rollback_last_migration()
return 0 if success else 1
def cmd_auto(self, args):
"""Automatically migrate."""
success = self.workflow.auto_migrate(dry_run=args.dry_run)
return 0 if success else 1
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(
description="Database migration management"
)
parser.add_argument(
"--db-url",
default="sqlite:///app.db",
help="Database URL"
)
subparsers = parser.add_subparsers(dest="command", help="Commands")
# Status command
subparsers.add_parser("status", help="Show migration status")
# Compare command
subparsers.add_parser("compare", help="Compare with database")
# Generate command
gen_parser = subparsers.add_parser("generate", help="Generate migration")
gen_parser.add_argument("-m", "--message", help="Migration message")
gen_parser.add_argument("--dry-run", action="store_true")
# Upgrade command
up_parser = subparsers.add_parser("upgrade", help="Apply migrations")
up_parser.add_argument("--sql", action="store_true", help="Print SQL only")
# Downgrade command
subparsers.add_parser("downgrade", help="Rollback last migration")
# Auto command
auto_parser = subparsers.add_parser("auto", help="Auto-migrate")
auto_parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()
if not args.command:
parser.print_help()
return 1
cli = MigrationCLI(args.db_url)
# Route commands
commands = {
"status": cli.cmd_status,
"compare": cli.cmd_compare,
"generate": cli.cmd_generate,
"upgrade": cli.cmd_upgrade,
"downgrade": cli.cmd_downgrade,
"auto": cli.cmd_auto,
}
handler = commands.get(args.command)
return handler(args) if handler else 1
if __name__ == "__main__":
sys.exit(main())
5. Usage Examples
# Show migration status
python cli.py status
# Compare models with database
python cli.py compare
# Generate migration (auto-detect changes)
python cli.py generate -m "Add user table"
# Apply pending migrations
python cli.py upgrade
# Rollback last migration
python cli.py downgrade
# Auto-detect and apply migrations
python cli.py auto
# Dry run (show SQL without executing)
python cli.py upgrade --sql
python cli.py auto --dry-run
This solution provides:
- ✅ Revision detection - Get current database revision
- ✅ Schema comparison - Detect differences between models and DB
- ✅ Auto-generation - Generate migrations based on changes
- ✅ Programmatic control - Full Python API for migrations
- ✅ CLI tool - Command-line interface
- ✅ Dry run - Preview changes before applying
- ✅ History tracking - Complete migration history
- ✅ Upgrade/downgrade - Apply or rollback migrations