SQLAlchemy supports creating partial indexes in postgresql.
Is it possible to create a partial unique index through SQLAlchemy?
Imagine a table/model as so:
class ScheduledPayment(Base):
invoice_id = Column(Integer)
is_canceled = Column(Boolean, default=False)
I'd like a unique index where there can be only one "active" ScheduledPayment for a given invoice.
I can create this manually in postgres:
CREATE UNIQUE INDEX only_one_active_invoice on scheduled_payment
(invoice_id, is_canceled) where not is_canceled;
I'm wondering how I can add that to my SQLAlchemy model using SQLAlchemy 0.9.
is_canceled
being part of the index definition. From the postgres docs about partial indexes: "enforces uniqueness among the rows that satisfy the index predicate, without constraining those that do not". So,Index('only_one_active_invoice', invoice_id, unique=True, postgresql_where=~is_canceled)
where onlyinvoice_id
is used in the definition would be enough, because we only want to consider non-cancelled invoices, right? – Baeyer