[英]How to set composite type array containing JSONB elements with a literal value?
我有这种类型:
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元素的复合类型,并使用文字值设置它们。 例如,这有效:
对于这种类型:
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\"\"}\")"}';
呸。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.