Alembic管理Sqlite3数据库版本
1. 初始化
-
在'.db'同级目录下键入
alembic init alembic
,生成alembic文件夹。 -
修改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 Base
和from client.app.models import BackUpAlive, ZipFile, AiModel
需修改成自己模块内容。 -
修改和alembic文件夹同级的
alembic.ini
:sqlalchemy.url = sqlite:///dbname.db
其中dbname.db改成自己的数据库文件绝对路径。
2. 迁移升级
-
自动生成迁移文件:
alembic revision --autogenerate -m "upgrade commit content"
-
更新数据库:
-
增加列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. 回退版本
-
无删除的字段的情况:
alembic downgrade -1
-
有删除字段的情况,由于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