Create Version Table with Alembic

  • Share this:

Code introduction


The function uses the Alembic library to create a new version table for a database engine, and adds some basic fields such as version number and creation time. It also updates Alembic's version control file.


Technology Stack : Alembic, SQLAlchemy

Code Type : Function

Code Difficulty : Advanced


                
                    
def generate_version_table(engine, version_table_name="version_table"):
    """
    为指定的数据库引擎创建一个新的版本表。

    :param engine: 数据库连接引擎
    :param version_table_name: 新版本表的名字,默认为"version_table"
    """
    import alembic
    from alembic import op
    import sqlalchemy

    # 定义版本表的名称
    table_name = version_table_name

    # 创建一个新的版本表
    op.create_table(
        table_name,
        sqlalchemy.Column("version_num", sqlalchemy.String(length=32), primary_key=True),
        sqlalchemy.Column("created_time", sqlalchemy.DateTime, default=sqlalchemy.func.now())
    )

    # 将新版本表添加到Alembic的元数据中
    op.alter_table(
        table_name,
        op.AddColumn("current", sqlalchemy.Boolean, default=True)
    )

    # 更新Alembic的版本控制文件
    op.create_version_table()

    print(f"Version table '{table_name}' created successfully.")