是否可以使用CHECK约束来测试jsonb数组中的对象?

时间:2017-04-29 19:21:41

标签: postgresql postgresql-9.6

我有以下域名:

CREATE DOMAIN foo AS JSONB
  NOT NULL
  CONSTRAINT is_valid CHECK (
    jsonb_typeof(VALUE) = 'array'
    -- AND is each element of array an obj 
    -- AND does each element of array have a key "id"
  );

我尝试了几种ALL(),jsonb的变种? ' key'和array_agg(jsonb_array_elements(VALUE)) 但我无法找到完成这项测试的方法。

2 个答案:

答案 0 :(得分:1)

使用存储的功能:

cardsLST.RemoveAt(3)

答案 1 :(得分:1)

t=# create or replace function s89(_v jsonb) returns boolean as $$
declare
 _r boolean;
 _c int;
 _t text;
begin
  with b as (
    with t as (
      select _v "value"
    )
    select
      jsonb_array_elements(value)->>'id' id
    , jsonb_array_length(value) c
    from t
    )
    select array_length(array_agg(id),1) = c,c,array_agg(id)::text into _r, _c,_t
    from b
    where id is not null
    group by c;
    raise info '%',_c||_t;
  return _r;
end;
$$ language plpgsql
;
CREATE FUNCTION
t=# select s89('[{"id":3},{"id":4},4]'::jsonb);
INFO:  3{3,4}
 s89
-----
 f
(1 row)

t=# select s89('[{"id":3},{"idr":4}]'::jsonb);
INFO:  2{3}
 s89
-----
 f
(1 row)

t=# select s89('[{"id":3},{"id":4}]'::jsonb);
INFO:  2{3,4}
 s89
-----
 t
(1 row)

t=# CREATE DOMAIN foo AS JSONB
  NOT NULL
  CONSTRAINT is_valid CHECK (
    jsonb_typeof(VALUE) = 'array' and s89(VALUE)
  );