Creating a Version Table with Alembic

  • Share this:

Code introduction


This function uses the Alembic library's op.create_table method to create a new version table for the specified table name. It accepts a database engine and a table name as parameters and creates a new table in the database with two columns: id and name.


Technology Stack : Python, Alembic, SQLAlchemy

Code Type : Function

Code Difficulty : Intermediate


                
                    
def generate_version_table(engine, table_name):
    """
    Generates a new version table for the given table name using Alembic's op.create_table.

    Parameters:
    engine (Engine): The database engine to use.
    table_name (str): The name of the table to create.
    """
    import alembic
    from alembic import op
    import sqlalchemy

    # Define the column types
    columns = [
        sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
        sqlalchemy.Column('name', sqlalchemy.String(50), nullable=False)
    ]

    # Create the table
    op.create_table(table_name, sqlalchemy.schema.Table(
        table_name,
        sqlalchemy.schema.MetaData(),
        *columns
    ))