[英]How to set composite type array containing JSONB elements with a literal value?
I have this type: 我有这种类型:
CREATE TYPE public.user_type AS (
text_1 VARCHAR(512),
text_2 VARCHAR(1000),
jsonb_1 JSONB,
jsonb_2 JSONB
);
And need to know how to format a literal value to set an array of this type for a unit test. 并且需要知道如何格式化文本值以设置用于单元测试的这种类型的数组。 I keep getting malformed array literal errors when I try to set it.
当我尝试设置它时,总是收到格式错误的数组文字错误。
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
with this snippet: 这个片段:
DO $$
DECLARE
user_type public.user_type[] = '{{"(text 1,text 2,{"key_1":"value_1"},{"key_2":"value_2"})"}';
BEGIN
END $$;
How do I form a literal string to set this composite type? 如何形成文字字符串来设置此复合类型?
For other unit tests I can declare composite types without JSONB elements and set them with literal values. 对于其他单元测试,我可以声明不带有JSONB元素的复合类型,并使用文字值设置它们。 For example this works:
例如,这有效:
For this type: 对于这种类型:
CREATE TYPE public.user_type_2 AS (
text_1 VARCHAR(512),
text_2 VARCHAR(1000)
);
This snippet will return multiple rows: 此代码段将返回多行:
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;
as I would expect 如我所料
+-----------+-----------+
| text_1 | text_2 |
+-----------+-----------+
| string_1a | string_1b |
| string_2a | string_2b |
+-----------+-----------+
You have to use several levels of escaping for that: 为此,您必须使用多个转义:
The array element has to be surrounded by "
, because it contains ,
, {
and }
. 该阵列元件具有由包围
"
,因为它包含,
, {
和}
。
Each of the "
inside the array element has to be escaped to \\"
. 每个
"
数组元素内部的元素都必须转义为\\"
。
The JSON elements in the composite type have to be surrounded by "
(now \\"
) because they contain ,
. 复合类型中的JSON元素必须包含
"
(现在\\"
),因为它们包含,
。
The "
for JSON strings have to be doubled to escape the "
from the previous point, so they eventually become \\"\\"
. JSON字符串的
"
必须加倍,以避开上一点的"
,因此它们最终变为\\"\\"
。
Your assignment could look like this: 您的作业可能如下所示:
user_type public.user_type[] := '{"(text 1,text 2,\"{\"\"key_1\"\": \"\"value_1\"\"}\",\"{\"\"key_2\"\": \"\"value_2\"\"}\")"}';
Yuck. 呸。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.