通过自定义域的并发自定义域数组

时间:2018-01-31 19:10:29

标签: postgresql sql-domain

有关从其他自定义域创建域的文档say nothing

我只需要创建(以前创建的)自定义域的数组,因此 problem/solution discussed here

示例:

CREATE DOMAIN jbag AS JSONb
  CHECK(  VALUE IS NULL OR  jsonb_typeof(VALUE) IN ('object','null')  );  

但PostgreSQL不接受像CREATE FUNCTION intersection(jbag[]) RETURNS jbag这样的分词。

如何做一种CREATE DOMAIN jbag[] AS jbag[]?或者说对postgresql-parser“你好让我们接受原子自定义类型的数组!”?

有关详细信息,请参阅bag.sql

1 个答案:

答案 0 :(得分:1)

您可以根据预定义的数组类型创建域,在本例中为jsonb[]. 使用确保所有数组元素与jbag

兼容的函数定义检查约束
create or replace function jbags_check(jsonb[])
returns boolean language sql immutable as $$
    select bool_and(elem is null or jsonb_typeof(elem) in ('object','null'))
    from unnest($1) u(elem);
$$;

create domain jbags as jsonb[] 
    check(jbags_check(value));

现在您的功能可能如下所示:

CREATE FUNCTION intersection(jbags) RETURNS jbag AS $f$
    SELECT jsonb_object_agg(e,m::int)::jbag
    FROM (
      SELECT e, MIN(m) AS m
        FROM unnest($1), jsonb_each_text(unnest) as a(e, m)
        GROUP BY e
        HAVING COUNT(*)=array_length($1,1)
    ) t
$f$ language SQL IMMUTABLE;

行动中的功能:

select intersection(array['{"a": 2}', '{"a": 3, "b": 3}']::jbags);

 intersection 
--------------
 {"a": 2}
(1 row)

但:

select intersection(array['1', '{"a": 3, "b": 3}']::jbags);

ERROR:  value for domain jbags violates check constraint "jbags_check"