私は、テキスト配列(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'を使用しています:
copy_expert
は、ファイルをエクスポートしますか? –いいえ、私はPythonの 'csv'ライターにデータを渡しています。ルールが異なるクエリ(例:文字列の一重引用符)のフォーマットを「曖昧にする」。私は配列の値に対して 'mogrify'を使ってみましたが、私が言ったように、' ARRAY'構文を私に与えます。 – sudo