zoukankan      html  css  js  c++  java
  • 四十八:数据库之alembic常用命令和经典错误的解决办法

    常用命令:
    1、init:创建一个alembic仓库
    2、reversion:创建一个新的版本
    3、--autogenerate:自动将当前模型的修改,生成迁移脚本
    4、-m:message,可以记录本次迁移做了哪些修改,
    5、upgrade:将指定版本的迁移文件映射到数据库中,会执行版本文件中的upgrade函数,如果有多个迁移脚本没有被映射到数据库,name会执行多个映射脚本
    6、head:代表最新的迁移脚本的版本号
    7、downgrade:会执行指定版本的迁移文件中的downgrade函数
    8、heads:展示head指向的脚本文件版本号
    9、history:列出所有的迁移版本及其信息
    10、current:展示当前数据库中的版本号

    经典错误:
    1、FAILED:Target database is not up to date
    原因:heads和current不同,current落后于heads的版本
    解决办法:将current移动到head上:alembic upgrade head
    2、FAILED:Can't locate revision identified by 'xxxx'
    原因:数据库中存在的版本号不存在迁移脚本中
    解决办法:删除数据库的alembic_version表中的数据,重新执行alembic upgrade head
    3、执行alembic upgrade head时报某个表已存在的错误
    原因:执行这个命令的时候,会执行所有的迁移脚本,因为数据库中已经存在了这个表,然后迁移脚本中又包含了创建表的代码
    解决办法:1.删除versions中所有的迁移文件、2.修改迁移文件脚本中创建表的代码为pass

    准备工作

    from sqlalchemy import Column, String, Integer, create_engine
    from sqlalchemy.ext.declarative import declarative_base

    # 数据库类型+连接数据库的插件,这里使用的pymysql
    DB_URI = 'mysql+pymysql://root:123456@127.0.0.1:3306/test'

    engine = create_engine(DB_URI)
    Base = declarative_base(engine)


    class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True, autoincrement=True)
    username = Column(String(50), nullable=False)

    def __repr__(self):
    return f'username: {self.username}'


    Base.metadata.drop_all() # 删除所有表
    Base.metadata.create_all() # 创建表

    alembic revision --autogenerate -m 'first_commit'

    alembic upgrade head(最新) 、 alembic upgrade version(指定版本)

    增加字段

    减少字段

    查看历史版本

    查看当前版本

  • 相关阅读:
    艾伟:Memcached深度分析 狼人:
    项目一 三角形类4
    Flex 的DataGrid列 的字体,根据不同情况 渲染不同颜色
    yum 失败(This system is not registered with RHN.)解决
    FirePHP调试指南
    项目总结:复杂树状菜单结点增改删(ZTree)
    ./configure: error: the HTTP rewrite module requires the PCRE library.
    使用GDB调试Android NDK native(C/C++)程序
    三角形类1
    我为什么不喜欢网赚和SEO
  • 原文地址:https://www.cnblogs.com/zhongyehai/p/11832030.html
Copyright © 2011-2022 走看看