【问题标题】:How to work with postgres exclusion constraints in alembic如何在 alembic 中使用 postgres 排除约束
【发布时间】:2015-04-17 09:11:00
【问题描述】:

有没有办法在 Alembic 中创建具有 postgresql 排除约束的表,而无需编写文字 SQL?

例如,考虑这个表:

CREATE TABLE reservation (
during tsrange,
EXCLUDE USING gist (during WITH &&)
);

排除约束似乎不在 alembic 中可用的约束类型之列。

由于 SQLAlchemy 支持ExcludeConstraints

from sqlalchemy.dialects.postgresql import ExcludeConstraint, TSRANGE

class RoomBooking(Base):

    __tablename__ = 'room_booking'

    room = Column(Integer(), primary_key=True)
    during = Column(TSRANGE())

    __table_args__ = (
        ExcludeConstraint(('room', '='), ('during', '&&')),
    )

但 alembic 似乎无法识别它们,我想知道是否有其他方法可以在我的架构修订历史中反映此类排除约束。

【问题讨论】:

    标签: postgresql sqlalchemy alembic


    【解决方案1】:

    遇到了同样的问题。蒸馏器中的解决方案:

    您需要在脚本顶部导入排除约束:

    from sqlalchemy.dialects.postgresql import ExcludeConstraint
    
    op.create_table('mission_event_schedule',
                       sa.Column('id', sa.Integer(), nullable=False),
                       sa.Column('ts_range', postgresql.TSTZRANGE(), nullable=True),
                       sa.PrimaryKeyConstraint('id'),
                       ExcludeConstraint(('ts_range','&&'))
                       )
    

    【讨论】:

    • 如何将 ExcludeConstraint 添加到现有表中?
    【解决方案2】:

    如果您想使用 ExcludeConstraint 更新现有表,0.9 版具有create_exclude_constraint。 参考:create_exclude_constraint

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 2023-02-01
      • 2021-10-13
      • 1970-01-01
      • 2016-08-22
      相关资源
      最近更新 更多