Python Alembic:自动生成迁移不';行不通
我想用alembic进行自动生成迁移时出错 项目树:Python Alembic:自动生成迁移不';行不通,python,sqlalchemy,alembic,Python,Sqlalchemy,Alembic,我想用alembic进行自动生成迁移时出错 项目树: - alembic.ini - axis.py - tree.txt - alembic - env.py - README - script.py.mako versions axis.py 从sqlalchemy导入创建引擎 导入pymysql 从sqlalchemy.ext.declarative导入声明性基础 从sqlalchemy导入列、整数、字符串、Fore
- alembic.ini
- axis.py
- tree.txt
-
alembic
- env.py
- README
- script.py.mako
versions
axis.py
从sqlalchemy导入创建引擎
导入pymysql
从sqlalchemy.ext.declarative导入声明性基础
从sqlalchemy导入列、整数、字符串、ForeignKey、UniqueConstraint
Base=声明性_Base()
引擎=创建引擎('mysql+pymysql://root:*******$@localhost/amatdb_test')
#执行测试的轴
类轴(基):
__tablename_uu='Axis'
id\u轴=列(整数,主键=真)
名称\u轴=列(字符串(10),可空=假)
env.py
从logging.config导入fileConfig
从sqlalchemy导入引擎从配置
从sqlalchemy导入池
从alembic导入上下文
导入系统
导入操作系统
sys.path.insert(0,os.getcwd())
打印(系统路径)
从轴导入基
打印(基本.元数据.已排序的表)
#这是Alembic配置对象,它提供
#访问正在使用的.ini文件中的值。
config=context.config
#解释Python日志记录的配置文件。
#这条线路基本上设置了伐木工人。
fileConfig(config.config文件名)
#在此处添加模型的元数据对象
#对于“自动生成”支持
#从myapp导入mymodel
#target_metadata=mymodel.Base.metadata
target_metadata=Base.metadata
#根据env.py的需要定义的配置中的其他值,
#可获得:
#my\u important\u option=config.get\u main\u选项(“my\u important\u选项”)
# ... 等
def运行_迁移_脱机():
“”“在“脱机”模式下运行迁移。
这将仅使用URL配置上下文
而不是发动机,尽管发动机是可以接受的
这里也是。跳过引擎创建
我们甚至不需要DBAPI。
此处对context.execute()的调用将向
脚本输出。
"""
url=config.get\u main\u选项(“sqlalchemy.url”)
context.configure(
url=url,
target\u metadata=target\u metadata,
文字绑定=真,
方言_opts={“paramstyle”:“named”},
)
使用context.begin_transaction():
context.run_migrations()
def运行迁移在线()
“”“在“联机”模式下运行迁移。
在这个场景中,我们需要创建一个引擎
并将连接与上下文关联。
"""
可连接=引擎配置中的引擎配置(
config.get_节(config.config_ini_节),
prefix=“sqlalchemy.”,
poolclass=pool.NullPool,
)
使用connectable.connect()作为连接:
context.configure(
连接=连接,目标\元数据=目标\元数据
)
使用context.begin_transaction():
context.run_migrations()
如果context.is_offline_mode():
脱机运行迁移
其他:
运行_迁移_联机()
解释我的问题
首先,我使用:alembic revision--autogenerate创建了我的第一个自动生成迁移
迁移文件似乎是正确的
创建表
修订ID:dcd02a3f6ff9
修订:
创建日期:2020-06-03 08:47:48.198022
"""
从alembic导入op
将sqlalchemy作为sa导入
#Alembic使用的修订标识符。
修订版='dcd02a3f6ff9'
向下修订=无
分支标签=无
依赖=无
def升级():
#####由Alembic自动生成的命令-请调整###
op.create_表格(“轴”,
sa.Column('id_axis',sa.Integer(),nullable=False),
sa.Column('name_axis',sa.String(长度=10),nullable=False),
sa.PrimaryKeyConstraint('id_轴')
)
#####结束Alembic命令###
def降级():
#####由Alembic自动生成的命令-请调整###
升降台(“轴”)
#####结束Alembic命令###
然后,我运行:alembic升级头
我的数据库已创建
因此,我向表轴添加了一个名为“test”的新列
test=列(字符串(10),默认值=无)
我第二次运行:alembic revision--autogenerate
我获得了这个迁移文件
“A输出科隆测试数据轴
修订编号:283ca08aec66
修订:dcd02a3f6ff9
创建日期:2020-06-03 08:49:19.717515
"""
从alembic导入op
将sqlalchemy作为sa导入
从sqlalchemy.dialogs导入mysql
#Alembic使用的修订标识符。
修订版='283ca08aec66'
向下修订='dcd02a3f6ff9'
分支标签=无
依赖=无
def升级():
#####由Alembic自动生成的命令-请调整###
op.create_表格(“轴”,
sa.Column('id_axis',sa.Integer(),nullable=False),
sa.Column('name_axis',sa.String(长度=10),nullable=False),
sa.Column('test',sa.String(长度=10),nullable=True),
sa.PrimaryKeyConstraint('id_轴')
)
升降台(“轴”)
#####结束Alembic命令###
def降级():
#####由Alembic自动生成的命令-请调整###
op.create_表格(“轴”,
sa.Column('id_axis',mysql.INTEGER(),autoincrement=True,nullable=False),
sa.Column('name_axis',mysql.VARCHAR(长度=10),nullable=False),
sa.PrimaryKeyConstraint('id_轴'),
mysql\u collate='utf8mb4\u 0900\u ai\u ci',
mysql\u default\u charset='utf8mb4',
mysql_engine='InnoDB'
)
升降台(“轴”)
#####结束Alembic命令###
如您所见,alembic尝试重新创建表轴。所以,当我运行时:alembic升级头
我得到一个错误,因为axis已经存在
我错过了什么
为什么Alembic无法检测现有表?
感谢您的时间和考虑尝试使用小写表格名称,即
axis
而不是axis
。我不确定mysql是否支持大写的表名,但这可能是造成问题的原因
作为一个可能发生的例子,mysql可能会自动将名称小写,这样alembic第一次比较Axis时
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = alembic
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# timezone to use when rendering the date
# within the migration file as well as the filename.
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; this defaults
# to alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path
# version_locations = %(here)s/bar %(here)s/bat alembic/versions
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
sqlalchemy.url = mysql+pymysql://root:**********$@localhost/amatdb_test
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks=black
# black.type=console_scripts
# black.entrypoint=black
# black.options=-l 79
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S