Generating Migration Scripts with Alembic

  • Share this:

Code introduction


This code defines a function that generates a new migration script for a specified table in a database using Alembic. It first configures Alembic, then checks if the table exists, and if it does, generates a migration script.


Technology Stack : Alembic, SQLAlchemy, declarative_base, sessionmaker

Code Type : The type of code

Code Difficulty :


                
                    
from alembic import command
from alembic.config import Config
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

def generate_migrate_script(database_url, table_name):
    """
    This function generates a new migration script for a specified table in a database using Alembic.
    """

    # Define the Alembic configuration
    config = Config()
    config.set_main_option('sqlalchemy.url', database_url)

    # Create an engine
    engine = create_engine(database_url)
    Base = declarative_base()

    # Reflect the table to ensure it's known to Alembic
    Base.metadata.reflect(engine)

    # Check if the table exists to avoid duplicate migrations
    if table_name not in Base.metadata.tables:
        print(f"Table {table_name} does not exist. Cannot generate migration.")
        return

    # Generate the migration script
    command.autogenerate(config, [engine])

    print(f"Migration script generated for table {table_name}")