gpt4 book ai didi

arrays - 检查表中 varchar[] 和 varchar[][] 列的约束

转载 作者:行者123 更新时间:2023-11-29 12:58:49 24 4
gpt4 key购买 nike

对于文字游戏,我正在尝试向 VARCHAR 数组添加 CHECK 约束:

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 关键字应该在右侧?

谁能推荐一种在这里实现检查约束的方法?

最佳答案

是的,不可能使用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]$')),
...

关于arrays - 检查表中 varchar[] 和 varchar[][] 列的约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35798431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com