SQLAlchemy Alembic

  1. 安裝:pip install alembic
  2. 初始化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.
  3. 修改配置
    • 修改文件(alembic.ini):
    定義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
  4. 數據庫結構修改
  5. 生成版本文件,在alembic下的version下面生成一個文件,版本號_描述
  6. (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
  7. 升級數據庫: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
  8. 降級數據庫,alembic downgrade xxxx-1,-1表示上一個版本
  9. (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
  10. 手動編輯版本文件
    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')
相關文章
相關標籤/搜索