如何使用alembic中的postgres排除约束

Jul*_*ian 7 postgresql sqlalchemy alembic

有没有办法在没有编写文字SQL的情况下在Alembic中创建一个带有postgresql排除约束的表?

例如,考虑一下这个表:

CREATE TABLE reservation (
during tsrange,
EXCLUDE USING gist (during WITH &&)
);
Run Code Online (Sandbox Code Playgroud)

排除约束似乎不属于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', '&&')),
    )
Run Code Online (Sandbox Code Playgroud)

但是alembic似乎没有认出它们,我想知道是否还有其他方法可以在我的架构修订历史中反映这种排除约束.

小智 7

陷入同样的​​问题.在alembic中的解决方案:

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

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','&&'))
                   )
Run Code Online (Sandbox Code Playgroud)