参考网址 – 1
文档
sqlachemy-postgres
alembic的一些更新语句
安装alembic
- pip3 pip install alembic 直接安装,它需要三个依赖包,PIP会自动处理。
初始化
在项目的根目录执行
- alembic init YOUR_ALEMBIC_DIR
随后你的项目目录应该会新增一个alembic.ini文件以及一个YOUR_ALEMBIC_DIR目录,最好指定一个符合自己项目风格的命名。 - alembic.ini 提供了一些基本的配置
- env.py 每次执行Alembic都会加载这个模块,主要提供项目Sqlalchemy Model 的连接
- script.py.mako 迁移脚本生成模版
- versions 存放生成的迁移脚本目录
- 修改编辑alembic.ini文件去指定Alembic的数据库连接
自动生成迁移脚本
-
修改env.py 文件
配置YOUR_ALEMBIC_DIR/env.py文件,修改target_metadata = None为你的元信息对象。
这里我就直接导入了,但是在导入的过程中由于目录问题,所以一个额外的Hack。# Hack for model import import os import sys sys.path.insert(0, os.path.realpath(".")) # add your model's MetaData object here # for 'autogenerate' support # from myapp import my model # target_metadata = None from model import Base target_metadata = Base.metadata
-
执行命令 (自动生成迁移脚本)
$ alembic revision --autogenerate -m "add weibo token fields for user" INFO [alembic.migration] Context impl MySQLImpl. INFO [alembic.migration] Will assume non-transactional DDL. INFO [alembic.autogenerate] Detected added column 'user.weibo_expires' INFO [alembic.autogenerate] Detected added column 'user.weibo_token' Generating migrate/versions/3117ba3f1f1f_add_weibo_token_expires_for_user.py...done
-
alembic stamp head
-
alembic upgrade head 生成表/更新表
-
alembic history 查看历史记录
-
修改字段名
def upgrade(): ### commands auto generated by Alembic - please adjust! ### # 把 user 表里的 name 列重命名为 username op.alter_column('user', 'name', new_column_name='username', existing_type=mysql.VARCHAR(length=20)) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.alter_column('user', 'username', new_column_name='name', existing_type=mysql.VARCHAR(length=20)) ### end Alembic commands ###
-
增加字段
def upgrade():
op.add_column('sys_user_alembic_1', sa.Column('belong_to', sa.String(256)), schema='infosys')
def downgrade():
op.drop_column('sys_user_alembic_1', 'belong_to', schema='infosys')