Alembic管理Sqlite3数据库版本

1. 初始化

  1. 在'.db'同级目录下键入alembic init alembic,生成alembic文件夹。

  2. 修改alembic文件夹下env.py,添加以下内容:

    import os
    import sys
    
    basedir = os.path.split(os.getcwd())[0]
    sys.path.append(basedir)
    from client.app.database import Base
    from client.app.models import BackUpAlive, ZipFile, AiModel
    
    # target_metadata = mymodel.Base.metadata
    # target_metadata = None
    target_metadata = Base.metadata
    

    其中from client.app.database import Basefrom client.app.models import BackUpAlive, ZipFile, AiModel需修改成自己模块内容。

  3. 修改和alembic文件夹同级的alembic.ini:

    sqlalchemy.url = sqlite:///dbname.db
    

    其中dbname.db改成自己的数据库文件绝对路径。

2. 迁移升级

  1. 自动生成迁移文件:

    alembic revision --autogenerate -m "upgrade commit content"

  2. 更新数据库:

    • 增加列nullable = True的情况:

      alembic upgrade head

    • 增加列nullable = False的情况:

      需先修改alembic/versions中对应py文件的upgrade(),例:

      def upgrade():
          # ### commands auto generated by Alembic - please adjust! ###
          op.add_column('users', sa.Column('is_admin', sa.Boolean(), nullable=False))
          # ### end Alembic commands ###
      

      修改后:

      def upgrade():
          # ### commands auto generated by Alembic - please adjust! ###
          op.add_column('users', sa.Column('is_admin', sa.Boolean(), nullable=True))
          op.execute("UPDATE users SET is_admin = false")
          op.alter_column('users', 'is_admin', nullable=False)
          # ### end Alembic commands ###
      

      之后执行:

      alembic upgrade head

3. 回退版本

  1. 无删除的字段的情况:

    alembic downgrade -1

  2. 有删除字段的情况,由于sqlite3无drop关键字需先修改alembic/versions中对应py文件的downgrade(),例:

    def downgrade():
        # ### commands auto generated by Alembic - please adjust! ###
        op.drop_column('AiModel', 'test')
        # ### end Alembic commands ###
    

    修改成:

    def downgrade():
        # ### commands auto generated by Alembic - please adjust! ###
        with op.batch_alter_table('AiModel') as batch_op:
            batch_op.drop_column('test')
        # ### end Alembic commands ###
    

    之后执行:

    alembic downgrade -1

posted @ 2020-12-22 17:50  Coodyzのblog  阅读(612)  评论(0编辑  收藏  举报