Postgres 9.2 - 添加条件约束检查

the*_*ebe 13 postgresql drupal constraints postgresql-9.2

我正在使用PostgreSQL 9.2并且需要在列上添加条件约束.基本上我想确保当另外两列具有特定值时,列是错误的.

gid          | int_unsigned           | not null default 0
realm        | character varying(255) | not null default ''::character varying
grant_update | smallint_unsigned      | not null default (0)::smallint
grant_delete | smallint_unsigned      | not null default (0)::smallint
Run Code Online (Sandbox Code Playgroud)

例:

alter table node_access add constraint block_anonymous_page_edit
check (grant_update = 0 WHERE (gid = 1 AND realm = 'nodeaccess_rid'));
Run Code Online (Sandbox Code Playgroud)

这应该做的是确保当gid为1并且realm = nodeaccess_rid时,grant_update等于0.但是,我认为不是做我想要的,而是试图让所有列都模仿这些值.本质上,它试图确保grant_update始终为0,gid始终为1,而realm始终为nodeaccess_rid.我得到的错误是:

ERROR:  check constraint "block_anonymous_page_edit" is violated by some row
Run Code Online (Sandbox Code Playgroud)

编辑

我认为这必须是一个在更新时触发的函数.

编辑

我在上面的问题中添加了一行,然后通过以下评论更新了已批准的解决方案.

Erw*_*ter 18

一旦你围绕逻辑思考,这是一个相当简单的CHECK约束:

CREATE TABLE tbl (
   gid          int      NOT NULL DEFAULT 0
  ,realm        text     NOT NULL DEFAULT ''
  ,grant_update smallint NOT NULL DEFAULT 0
  ,CHECK (gid <> 1
          OR realm <> 'nodeaccess_rid'
          OR grant_update = 0)
);
Run Code Online (Sandbox Code Playgroud)

测试:

INSERT INTO tbl(gid, realm, grant_update)
VALUES (1, 'nodeaccess_rid', 0);          -- works

INSERT INTO tbl(gid, realm, grant_update)
VALUES (1, 'nodeaccess_rid', 1);           -- check violation!

INSERT INTO tbl(gid, realm, grant_update)
VALUES (1, 'some_string',    1);           -- works

INSERT INTO tbl(gid, realm, grant_update)
VALUES (2, 'nodeaccess_rid', 1);           -- works
Run Code Online (Sandbox Code Playgroud)