Search code examples
postgresqlsqlalchemyalembic

How to work with postgres exclusion constraints in alembic


Is there a way to create a table with a postgresql exclusion constraint in Alembic without writing literal SQL?

Consider, for example, this table:

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

Exclusion constraints do not seem to be among among the available constraint types in alembic.

As SQLAlchemy supports 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', '&&')),
    )

but alembic does not seem to recognize them, I'm wondering if there are other ways to reflect such exclusion constraints in my schema revision history.


Solution

  • Ran into the same problem. The solution in the alembic:

    You need to import the exclusion constraint on the top of the script:

    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','&&'))
                       )