我有一個包含文本數組(text[]
)類型列的表。我想使用COPY
命令來複制CSV。我使用Psycopg2的複製功能,但問題與Postgres相關。Postgres將不允許COPY中的ARRAY語法
看來Postgres只接受像{"string1","string2","string3"}
格式的數組,而不是ARRAY['string1', 'string2', 'string3']
(見下文)。這是一個問題,因爲以前格式的字符串轉義是一個巨大的麻煩,而Psycopg2的mogrify
函數以後一種格式輸出數組。第一種格式的手動轉義是我的最後手段,但我真的不想去那裏...
有沒有什麼辦法讓Postgres採取後者的格式進行復制或其他解決方法?
這裏是我的測試:
-- proof that both syntaxes are valid and compare equal
db=# SELECT ARRAY['string1', 'string2', 'string3']::text[] = '{"string1","string2","string3"}'::text[];
?column?
----------
t
(1 row)
-- COPY works with {} syntax
db=# CREATE TEMP TABLE test(words text[]);
CREATE TABLE
db=# COPY test FROM stdin;
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> {"string1","string2","string3"}
>> \.
COPY 1
-- COPY fails with ARRAY syntax
db=# COPY test FROM stdin;
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> ARRAY['string1', 'string2', 'string3']
>> \.
ERROR: malformed array literal: "ARRAY['string1', 'string2', 'string3']"
DETAIL: Array value must start with "{" or dimension information.
CONTEXT: COPY test, line 1, column words: "ARRAY['string1', 'string2', 'string3']"
是否使用'mogrify'生成文件? –
不,我將數據傳遞給Python的'csv'作家。用於查詢的'mogrify'格式,它具有不同的規則(例如,圍繞字符串的單引號)。我曾嘗試使用'mogrify'作爲數組值,但正如我所說的,它給了我'ARRAY'語法。 – sudo