Postgresql check constraint on all individual elements in array using function -


if have table

create table foo ( bar text[] not null check ..... ); 

and function

create function baz(text) returns boolean $$ ..... 

how add check constraint foo table such every element in bar field validates baz function?

i'm thinking need create function

create function array_baz(arg text[]) returns boolean $$      x ( select baz(unnest(arg)) s_arg )     select not exists (select 1 x s_arg = false) $$ language sql strict immutable;   create table foo (bar text[] not null check ( array_baz(bar) = true ) ); 

however, i'm sure i'm reinventing wheel here , there's cuter way of doing this. psql trick missing? map function nice

create table foo (bar text[] not null check (true = all(map('baz', bar))); 

but far search efforts fruitless.

you can want in more 1 way. if want use all(...) quantifiers, need suitable operator. that, first need function perform want:

imagine want check texts don't have uppercase letter in them. you'd define function like:

create function doesnt_have_uppercase(b boolean, t text) /* compares b result of `t` not having non-lowercase character */     returns boolean     immutable     strict     language sql $$     select (t = lower(t)) = b $$ ; 

based on it, create operator:

create operator =%= (     procedure = doesnt_have_uppercase,     leftarg = boolean,     rightarg = text ) ; 

you need operator because any , all quantifiers need following structure:

expression operator all(array) 

at point, can define:

create table foo  (      bar text[] not null,     constraint bar_texts_cant_have_uppercase check(true =%= all(bar)) ); 

which lead following behaviour:

insert foo     (bar) values     (array['this pass', 'this too']) ; 
 1 rows affected 
insert foo     (bar) values     (array['that pass', 'but prevent it']) ; 
 error:  new row relation "foo" violates check constraint "bar_texts_cant_have_uppercase" detail:  failing row contains ({"that pass","but prevent it"}). 

check @ dbfiddle here


i seek less tortuous route, however:

create function doesnt_have_uppercase(t text[]) /* returns true if elements of t don't have uppercase letter */     returns boolean     immutable     strict     language sql $$     select (not exists (select 1 unnest(t) q q <> lower(q))) $$ ;  create table foo  (      bar text[] not null,     constraint bar_texts_cant_have_uppercase check(doesnt_have_uppercase(bar)) ); 

this behaves previous example (except if of elements of array null).

dbfiddle here


Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -