gpt4 book ai didi

python - Alembic 忽略特定表

转载 作者:行者123 更新时间:2023-12-03 17:09:54 28 4
gpt4 key购买 nike

我正在使用 alembic 根据用户定义的 sqlalchemy 模型管理数据库迁移。我的挑战是 我希望 alembic 忽略对特定表集的任何创建、删除或更改。
注:我的 Q 与这个问题类似 Ignoring a model when using alembic autogenerate但不同之处在于我想从模型定义之外控制 alembic。
这是我想忽略的示例表:

from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base(metadata=MetaData())

class Ignore1(Base):
"""
Signed in to the account...
"""
__tablename__ = 'ignore_1'
__table_args__ = {
'info':{'skip_autogenerate':True}
}
id = Column(Integer, primary_key=True)
foo = Column(String(20), nullable=True)
示例代码(不能解决我的问题):
alembic/env.py
# Ideally this is stored in my actual database, but for now, let's assume we have a list...
IGNORE_TABLES = ['ignore_1', 'ignore_2']

def include_object(object, name, type_, reflected, compare_to):
"""
Should you include this table or not?
"""

if type_ == 'table' and (name in IGNORE_TABLES or object.info.get("skip_autogenerate", False)):
return False

elif type_ == "column" and object.info.get("skip_autogenerate", False):
return False

return True

# Then add to config
context.configure(
...
include_object=include_object,
...
)

最佳答案

我找到了解决我的问题的方法!
我的错误在于我的 context 的实例化对象在 env.py

def run_migrations_offline():
...
context.configure(
url=url,
target_metadata=target_metadata,
include_object=include_object,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)

with context.begin_transaction():
context.run_migrations()
我没有将此更改应用于在线迁移的上下文:
def run_migrations_online():
...
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)

with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
# THE FOLLOWING LINE WAS MISSING FROM MY ORIGINAL CODE
include_object=include_object, # <----------------------- THIS!
)
...
希望遇到这个问题并经历类似困惑的其他人可以通读我的问题和以下解决方案,并认识到绝望只是救赎的一个小愚蠢调整。

关于python - Alembic 忽略特定表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65184035/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com