[英]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.