在Postgres上使用sqlalchemy创建部分唯一索引

bri*_*anz 22 python postgresql sqlalchemy postgresql-9.2

SQLAlchemy支持在postgresql中创建部分索引.

是否可以通过SQLAlchemy 创建部分唯一索引

想象一下表/模型如下:

class ScheduledPayment(Base):
     invoice_id = Column(Integer)
     is_canceled = Column(Boolean, default=False)
Run Code Online (Sandbox Code Playgroud)

我想要一个唯一的索引,其中给定发票只能有一个"活动"的ScheduledPayment.

我可以在postgres中手动创建:

CREATE UNIQUE INDEX only_one_active_invoice on scheduled_payment 
     (invoice_id, is_canceled) where not is_canceled;
Run Code Online (Sandbox Code Playgroud)

我想知道如何使用SQLAlchemy 0.9将其添加到我的SQLAlchemy模型中.

van*_*van 34

class ScheduledPayment(Base):
    id = Column(Integer, primary_key=True)
    invoice_id = Column(Integer)
    is_canceled = Column(Boolean, default=False)

    __table_args__ = (
        Index('only_one_active_invoice', invoice_id, is_canceled,
              unique=True,
              postgresql_where=(~is_canceled)),
    )
Run Code Online (Sandbox Code Playgroud)

  • 这个问题是对我自己的理智检查。是否可以在索引定义中不包含“is_canceled”的情况下定义索引。来自[关于部分索引的postgres文档](https://www.postgresql.org/docs/8/indexes-partial.html#INDEXES-PARTIAL-EX3):**“强制满足索引谓词的行之间的唯一性,而不限制那些不“**”的人。因此,定义中仅使用“invoice_id”的“Index('only_one_active_invoice',invoice_id,unique=True,postgresql_where=~is_canceled)”就足够了,因为我们只想考虑未取消的发票,对吧? (5认同)

sas*_*sas 7

如果有人通过寻找设置部分唯一约束来停止,其中列可以选择NULL,这是如何:

__table_args__ = (
    db.Index(
        'uk_providers_name_category',
        'name', 'category',
        unique=True,
        postgresql_where=(user_id.is_(None))),
    db.Index(
        'uk_providers_name_category_user_id',
        'name', 'category', 'user_id',
        unique=True,
        postgresql_where=(user_id.isnot(None))),
)
Run Code Online (Sandbox Code Playgroud)

where user_id列是可以的NULL,我希望在所有三列中强制执行唯一约束(name, category, user_id),NULL只是其中一个允许的值user_id.