具有多个模式的 Alembic 操作
Alembic operations with multiple schemas
注意:这个问题我已经找到了答案,但想分享它以帮助其他面临同样问题的人。
我试图在我的多模式 postgresql 数据库中执行一些 alembic
操作,例如 .add_column
或 .alter_table
(尽管对于 .create_table
或 .drop_table
)。例如:op.add_column('table_name', 'new_column_name')
但是,我遇到了同样的错误,基本上是找不到 table 名称。据我了解,这是因为 alembic
无法识别架构并在 public 架构中搜索 table。然后,我尝试将 table_name 中的模式指定为 'schema_name.table_name'
但没有成功。
我遇到过类似的问题 or Alembic support for multiple Postgres schemas,但没有找到满意的答案。
在alembic
documentation中搜索后,发现实际上有一个用于不同操作的模式参数。例如:
op.add_column('table_name', 'column_name', schema='schema_name')
如果已在声明性 SQLAlchemy 模型中定义,Alembic 将自动从 table 中选取模式。
例如,使用以下设置:
# models.py
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class SomeClass(Base):
__tablename__ = 'some_table'
id = Column(Integer, primary_key=True)
name = Column(String(50))
__table_args__ = {"schema": "my_schema"}
# alembic/env.py
from models import Base
target_metadata = Base.metadata
[...]
运行:
alembic revision --autogenerate -m "test"
将生成具有指定架构的默认迁移脚本:
def upgrade_my_db():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('some_table',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=50), nullable=True),
sa.PrimaryKeyConstraint('id'),
schema='my_schema'
)
# ### end Alembic commands ###
注意:这个问题我已经找到了答案,但想分享它以帮助其他面临同样问题的人。
我试图在我的多模式 postgresql 数据库中执行一些 alembic
操作,例如 .add_column
或 .alter_table
(尽管对于 .create_table
或 .drop_table
)。例如:op.add_column('table_name', 'new_column_name')
但是,我遇到了同样的错误,基本上是找不到 table 名称。据我了解,这是因为 alembic
无法识别架构并在 public 架构中搜索 table。然后,我尝试将 table_name 中的模式指定为 'schema_name.table_name'
但没有成功。
我遇到过类似的问题
在alembic
documentation中搜索后,发现实际上有一个用于不同操作的模式参数。例如:
op.add_column('table_name', 'column_name', schema='schema_name')
如果已在声明性 SQLAlchemy 模型中定义,Alembic 将自动从 table 中选取模式。
例如,使用以下设置:
# models.py
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class SomeClass(Base):
__tablename__ = 'some_table'
id = Column(Integer, primary_key=True)
name = Column(String(50))
__table_args__ = {"schema": "my_schema"}
# alembic/env.py
from models import Base
target_metadata = Base.metadata
[...]
运行:
alembic revision --autogenerate -m "test"
将生成具有指定架构的默认迁移脚本:
def upgrade_my_db():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('some_table',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=50), nullable=True),
sa.PrimaryKeyConstraint('id'),
schema='my_schema'
)
# ### end Alembic commands ###