- 安装:pip install alembic
- 初始化alembic:
(venv) F:\Code\AllProject\devInfo\models>alembic init alembic
Creating directory F:\Code\AllProject\devInfo\models\alembic ... done
Creating directory F:\Code\AllProject\devInfo\models\alembic\versions ... done
Generating F:\Code\AllProject\devInfo\models\alembic.ini ... done
Generating F:\Code\AllProject\devInfo\models\alembic\env.py ... done
Generating F:\Code\AllProject\devInfo\models\alembic\README ... done
Generating F:\Code\AllProject\devInfo\models\alembic\script.py.mako ... done
Please edit configuration/connection/logging settings in 'F:\\Code\\AllProject\\devInfo\\models\\alembic.ini' before proceeding.
- 修改配置
定义sqlalchemy.url,写法和sqlalchemy中定义engine一样
sqlalchemy.url = mysql://root:123.com@127.0.0.1/allproject
- 修改alembic/env.py文件,修改metadata定义
# target_metadata = None
import os,sys
sys.path.append(os.path.realpath('.'))
from baseobj import Base
target_metadata=Base.metadata
- 数据库结构修改
- 生成版本文件,在alembic下的version下面生成一个文件,版本号_描述
(venv) F:\models>alembic revision --autogenerate -m "test update db"
INFO [alembic.runtime.migration] Context impl MySQLImpl.
INFO [alembic.runtime.migration] Will assume non-transactional DDL.
INFO [alembic.autogenerate.compare] Detected removed table 'mib'
INFO [alembic.autogenerate.compare] Detected removed table 'device'
INFO [alembic.autogenerate.compare] Detected removed table 'board'
INFO [alembic.autogenerate.compare] Detected removed table 'ips'
Generating F:\models\alembic\versions\45c578f737cc_test_update_db.py ... done
- 升级数据库:head表示最新版本文件,也可以直接指定版本号
(venv) F:\models>alembic upgrade head
INFO [alembic.runtime.migration] Context impl MySQLImpl.
INFO [alembic.runtime.migration] Will assume non-transactional DDL.
INFO [alembic.runtime.migration] Running upgrade -> 45c578f737cc, test update db
- 降级数据库,alembic downgrade xxxx-1,-1表示上一个版本
(venv) F:\models>alembic downgrade 45c578f737cc-1
INFO [alembic.runtime.migration] Context impl MySQLImpl.
INFO [alembic.runtime.migration] Will assume non-transactional DDL.
INFO [alembic.runtime.migration] Running downgrade 45c578f737cc -> , test update db
- 手动编辑版本文件
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
#添加行,board为表名,test_column为新加字段
op.add_column('board',sa.Column('test_column',sa.Integer))
def downgrade():
#降级删除指定表指定列
op.drop_column('board','test_column')