Set validation limit for text array in Postgresql

I have a table called student, with idand nameas fields in PostgreSQL:

Create table student (id int, name text[]);

I need to add a field constraint name. This means that it should only accept a character for this field. But the field name is a text array.

I tried this restriction:

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

But this causes this error:

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

How can I solve this problem? constraintmust be set to the whole array .

+4
source share
1 answer

An unnestarray is needed to match regular expression:

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

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;

:

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

:

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}).
+2

Source: https://habr.com/ru/post/1649896/


All Articles