Generate Alembic Migration Script for Adding Column

  • Share this:

Code introduction


This function generates an Alembic migration script to add a new column to an existing table.


Technology Stack : Alembic, SQLAlchemy

Code Type : Alembic Migration Script Generator

Code Difficulty : Intermediate


                
                    
def create_migration_script(table_name, column_name, column_type):
    """
    Generates an Alembic migration script for adding a new column to an existing table.

    :param table_name: Name of the table to which the column will be added.
    :param column_name: Name of the column to add.
    :param column_type: Data type of the column to add.
    """
    import alembic
    from alembic import op
    import sqlalchemy

    # Define the operation to add a column to the table
    def upgrade():
        op.add_column(table_name, sqlalchemy.Column(column_name, column_type))

    def downgrade():
        op.drop_column(table_name, column_name)

    # Execute the migration script
    alembic.command.upgrade("head")