2

What's the syntax with Postgres COPY statement using CSV to insert an array containing a backslash and/or a double quote ?

Using:

  • Copy statement: COPY test (a, b) FROM 'file.csv' (FORMAT CSV, DELIMITER ',');
  • Table: CREATE TABLE test(a text, b text[]).

I have tried the following syntaxes:

  • "a""a\a.com","{""aaa\zzzeee""}" : black slash in the array is discarded;
  • "a""a\a.com","{""aaa\\zzzeee""}" : the array will contain two \.

1 Answer 1

3

It seems like the second option (doubling the backslash character) does work:

# cat /tmp/file.csv
"a""a\a.com","{""aaa\\zzzeee""}"
# echo "CREATE TABLE test(a text, b text[]);" | psql
CREATE TABLE
# echo "COPY test (a, b) FROM '/tmp/file.csv' (FORMAT CSV, DELIMITER ',');" | psql
COPY 1
# echo "SELECT b[1] FROM test LIMIT 1;" | psql
     b
------------
 aaa\zzzeee
(1 row)
# 

The double backslash (\\) you may be referring to is probably psql performing escaping when displaying the full array:

# echo "SELECT b FROM test LIMIT 1;" | psql
        b
-----------------
 {"aaa\\zzzeee"}
(1 row)

This behavior is described in the documentation (8.15.6. Array Input and Output Syntax):

The array output routine will put double quotes around element values if they are empty strings, contain curly braces, delimiter characters, double quotes, backslashes, or white space, or match the word NULL. Double quotes and backslashes embedded in element values will be backslash-escaped.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.