Creating partial unique index with sqlalchemy on Postgres

前端 未结 3 987
难免孤独
难免孤独 2020-12-03 10:15

SQLAlchemy supports creating partial indexes in postgresql.

Is it possible to create a partial unique index through SQLAlchemy?

Imagine a table/model as so:<

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 10:40

    In case someone stops by looking to set up a partial unique constraint with a column that can optionally be NULL, here's how:

    __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))),
    )
    

    where user_id is a column that can be NULL and I want a unique constraint enforced across all three columns (name, category, user_id) with NULL just being one of the allowed values for user_id.

提交回复
热议问题