检查表

时间:2016-03-04 14:25:01

标签: arrays postgresql check-constraints postgresql-9.5 check-constraint

对于文字游戏,我试图将CHECK约束添加到VARCHAR数组:

CREATE TABLE words_games (
        gid SERIAL PRIMARY KEY,
        created timestamptz NOT NULL,

        player1 integer REFERENCES words_users(uid) ON DELETE CASCADE NOT NULL,
        player2 integer REFERENCES words_users(uid) ON DELETE CASCADE,

        played1 timestamptz,
        played2 timestamptz,

        hand1 varchar[7] NOT NULL CHECK (ALL(hand1) ~ '^[*A-Z]$'),
        hand2 varchar[7] NOT NULL CHECK (ALL(hand2) ~ '^[*A-Z]$'),
        pile  varchar[116] NOT NULL CHECK (ALL(pile) ~ '^[*A-Z]$'),

        board varchar[15][15] NOT NULL CHECK (ALL(board) ~ '^[.A-Z]$'),
        style integer NOT NULL CHECK (1 <= style AND style <= 4)
);

但是会出现语法错误:

ERROR:  syntax error at or near "ALL"
LINE 8:         hand1 varchar[7] NOT NULL CHECK (ALL(hand1) ~ '^[A-Z...
                                                 ^

可能是因为ALL关键字应该在右侧?

有人可以推荐一种在这里实施检查约束的方法吗?

1 个答案:

答案 0 :(得分:2)

是的,使用all()any()函数作为左对比参数是不可能的。改为创建函数:

create or replace function check_array_regexp_all(text[], text) returns boolean as $$
  select bool_and(x) from (select unnest($1) ~ $2 as x) t;
$$ language sql immutable;

并将其用于约束:

...
hand1 varchar[7] NOT NULL CHECK (check_array_regexp_all(hand1, '^[*A-Z]$')),
...