如何设置包含具有文字值的JSONB元素的复合类型数组



我有这种类型:

CREATE TYPE public.user_type AS (
    text_1 VARCHAR(512),
    text_2 VARCHAR(1000),
    jsonb_1 JSONB,
    jsonb_2 JSONB
);

并且需要知道如何格式化字面价值以将这种类型的数组设置为单位测试。当我尝试设置它时,我一直会遇到畸形的阵列错误。

SQL Error [22P02]: ERROR: malformed array literal: "{{"(text 1,text 2,{"key_1":"value_1"},{"key_2":"value_2"})"}"
  Detail: Unexpected array element.
  Where: PL/pgSQL function inline_code_block line 4 during statement block local variable initialization

使用此片段:

DO $$
DECLARE
    user_type public.user_type[] = '{{"(text 1,text 2,{"key_1":"value_1"},{"key_2":"value_2"})"}';
BEGIN
END $$;

如何形成一个文字字符串来设置此复合类型?

对于其他单元测试,我可以在没有JSONB Elements 的情况下声明复合类型并将其设置为字面值。例如,这有效:

对于这种类型:

CREATE TYPE public.user_type_2 AS (
    text_1 VARCHAR(512),
    text_2 VARCHAR(1000)
);

此片段将返回多行:

DO $$
DECLARE
    user_type_2 public.user_type_2[] = '{{"(string_1a,string_1b)"},{"(string_2a,string_2b)"}}';
BEGIN
     DROP TABLE IF EXISTS _results;
     CREATE TEMPORARY TABLE _results AS  
     SELECT * FROM UNNEST(user_type_2) x (text_1, text_2);
END $$;
SELECT * FROM _results;

我期望的

+-----------+-----------+
|  text_1   |  text_2   |
+-----------+-----------+
| string_1a | string_1b |
| string_2a | string_2b |
+-----------+-----------+

您必须使用几个级别的逃脱:

  • 数组元素必须被"包围,因为它包含,{}

  • 数组元素内的每个"都必须逃脱到"

  • 复合类型中的JSON元素必须被"(现在")包围,因为它们包含,

  • json字符串的"必须加倍才能从上几个点逃脱",因此它们最终成为""

您的作业看起来像这样:

user_type public.user_type[] := '{"(text 1,text 2,"{""key_1"": ""value_1""}","{""key_2"": ""value_2""}")"}';

yuck。

最新更新