在Postgresql中设置文本数组的检查约束

Gan*_*thy 5 regex arrays postgresql constraints

我有一个名为的表student,其中包含idname作为字段PostgreSQL

Create table student (id int, name text[]);
Run Code Online (Sandbox Code Playgroud)

我需要为该name字段添加约束。这意味着它只必须接受该字段的字符。但是字段名称是一个文本数组。

我尝试了此检查约束:

Alter table student 
add constraint stud_const check (ALL(name) NOT LIKE '%[^a-zA-Z]%');
Run Code Online (Sandbox Code Playgroud)

但这会引发此错误:

ERROR:  syntax error atERROR:  syntax error at or near "all"
LINE 1: ... student add constraint stud_const check (all(name) ...
 or near "all"
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?该constraint应设置为整个数组

Clo*_*eto 4

unnest数组必须将其与 a 匹配regular expression

select bool_and (n ~ '^[a-zA-Z]*$')
from unnest(array['John','Mary']) a(n)
;
 bool_and 
----------
 t
Run Code Online (Sandbox Code Playgroud)

bool_and。由于无法在检查约束中使用子查询,因此将其包装在函数中:

create function check_text_array_regex (
    a text[], regex text
) returns boolean as $$

    select bool_and (n ~ regex)
    from unnest(a) s(n);

$$ language sql immutable;
Run Code Online (Sandbox Code Playgroud)

并在检查约束中使用该函数:

create table student (
    id serial,
    name text[] check (check_text_array_regex (name, '^[a-zA-Z]*$'))
);
Run Code Online (Sandbox Code Playgroud)

测试一下:

insert into student (name) values (array['John', 'Mary']);
INSERT 0 1

insert into student (name) values (array['John', 'Mary2']);
ERROR:  new row for relation "student" violates check constraint "student_name_check"
DETAIL:  Failing row contains (2, {John,Mary2}).
Run Code Online (Sandbox Code Playgroud)