将“null”视为表唯一约束中的不同值

Jam*_*ull 10 python postgresql sqlalchemy

我有一个表,用于为客户端定义默认和自定义选项。如果该custom_id字段具有值,则它代表唯一自定义作业的记录。如果为空,则该记录代表客户端的默认选项。

我的问题是我想在两种情况下强制执行唯一性:

  1. custom_idclient并且option都非空
  2. clientoption非空,但custom_id为空

下面的表定义适用于第一种情况,但不适用于第二种情况,因为 null 不被视为值。有没有办法让 null 被视为一个值?

class OptionTable(Base):
    __tablename__ = "option_table"
    __table_args__ = (
        UniqueConstraint("custom", "client", "option", name="uix_custom_client_option"),
    )

    id = Column(Integer, primary_key=True)
    custom_id = Column(Integer, ForeignKey("custom.id"), nullable=True)
    client = Column(String, nullable=False)
    option = Column(String, nullable=False)

Run Code Online (Sandbox Code Playgroud)

以下是一些示例数据以及按顺序添加它们后的结果:

+----+----------+----------+--------+---------------------------------------------+
| id | CustomID |  Client  | Option |                   result                    |
+----+----------+----------+--------+---------------------------------------------+
|  1 | 123      | MegaCorp | Apple  | OK                                          |
|  2 | 123      | MegaCorp | Apple  | not unique                                  |
|  3 | NULL     | MegaCorp | Apple  | OK                                          |
|  4 | NULL     | MegaCorp | Google | OK                                          |
|  5 | NULL     | MegaCorp | Google | this one should fail, but currently doesn't |
+----+----------+----------+--------+---------------------------------------------+
Run Code Online (Sandbox Code Playgroud)

这个相关的答案正是我正在寻找的,使用 MySQL。理想的解决方案是使用 sqlalchemy 来完成此操作。

Jam*_*ull 7

根据此答案中推荐的方法,解决方案是创建两个部分索引

使用 sqlalchemy 作为问题中的示例,如下所示:

class OptionTable(Base):
    __tablename__ = "option_table"

    id = Column(Integer, primary_key=True)
    custom_id = Column(Integer, ForeignKey("custom.id"), nullable=True)
    client = Column(String, nullable=False)
    option = Column(String, nullable=False)

    __table_args__ = (
        Index(
            "uix_custom_client_option", 
            "custom_id", 
            "client", 
            "option", 
            unique=True, 
            postgresql_where=custom_id.isnot(None)
        ),
        Index(
            "uix_client_option", 
            "client",  
            "option", 
            unique=True, 
            postgresql_where=custom_id.is_(None)
        ),
    )
Run Code Online (Sandbox Code Playgroud)