Psql COPY with constraint fails

萝らか妹 提交于 2019-12-13 16:01:38

问题


I have a table like this in the server:

CREATE TABLE example_table (
id                          BIGSERIAL PRIMARY KEY,
name                        VARCHAR(70) NOT NULL,
status                      VARCHAR(70) NOT NULL CONSTRAINT status_enum CHECK (status IN ('old', 'new')),
UNIQUE (id, name)
);

And I have an SQL file, example.sql. The first line contain a header:

name_of_class,status
'CLASSNAME','old';

And I try to run a psql \copy to google server:

PGPASSWORD=password psql -d database --username username --port 5432 --host 11.111.111 << EOF
    BEGIN;
    \copy example_table(name,status) FROM example.sql DELIMITER ',' CSV Header
    COMMIT;
EOF

I then get this error:

ERROR:  new row for relation "example_table" violates check constraint "status_enum"
DETAIL:  Failing row contains (1, 'CLASSNAME', 'old';).
CONTEXT:  COPY example_table, line 2: "'CLASSNAME','old';"
ROLLBACK

Any idea how to solve this? 🙂


回答1:


It appears that your source csv is using the ' (single-quote) to quote all the columns. You could specify that as the quote character using the option QUOTE

The \copy command is trying to load 'old' into the status column that checks that values are either new or old. The extra quotes violate the constraint.

\copy example_table(name,status) FROM example.sql DELIMITER ',' CSV Header QUOTE ''''

4 single quotes are required because 1 specifies the actual quote char, 1 to escapes the quote-character, and 2 encloses the escaped quote-character.



来源:https://stackoverflow.com/questions/46977345/psql-copy-with-constraint-fails

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!