1

我有一个带有以下命令的 postgres 文件的 SQL 脚本。

COPY product_master(productId, productName) FROM 'product.txt' DELIMITERS ',' CSV; 

我想处理这个命令的错误(记录错误)

例子

错误:重复键值违反。

COPY命令是否返回任何值?如果没有,那么如何记录 shell 脚本的输出?

4

1 回答 1

2

您可以在数据库日志文件中记录任何和所有带有大量附加信息的消息(错误、警告、..)。这是标准行为。当然,您的数据库集群必须配置为这样做。在这里阅读精美的手册

根据您的客户端,您还应该能够从数据库服务器获得错误消息作为直接答案。请注意,错误是在与数据输出不同的流上报告的。喜欢stoutstderr在壳里。

您可能会从shellpsql -f调用来执行脚本。看看这个演示会发生什么:

在 shell 中创建一个虚拟 SQL 脚本:

vim test.sql

把这样的东西放进去:

CREATE temp table x (a int primary key, b int);
insert into x values (1,2),(3,4);
COPY x TO '/var/lib/postgres/dev/test.out';
COPY x FROM '/var/lib/postgres/dev/test.out';

执行它:

psql mydb -f test.sql

输出取决于各种设置,例如client_min_messages

psql:test.sql:2: NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "x_pkey" for table "x"
CREATE TABLE
INSERT 0 2
psql:test.sql:4: ERROR:  duplicate key value violates unique constraint "x_pkey"
KONTEXT:  COPY x, line 1: "1    2"

由于我已配置log_statement = all(除其他外)我的服务器日志显示:

2011-11-15 22:36:23 CET postgres LOG:  statement: CREATE temp table x (a int primary key, b int);
2011-11-15 22:36:23 CET postgres LOG:  statement: insert into x values (1,2),(3,4);
2011-11-15 22:36:23 CET postgres LOG:  statement: COPY x FROM '/var/lib/postgres/dev/test.out';
2011-11-15 22:36:23 CET postgres ERROR:  duplicate key value violates unique constraint "x_pkey"
2011-11-15 22:36:23 CET postgres CONTEXT:  COPY x, line 1: "1  2"
2011-11-15 22:36:23 CET postgres STATEMENT:  COPY x FROM '/var/lib/postgres/dev/test.out';

我不会log_statement = all在生产服务器上使用。这会产生巨大的日志文件。

于 2011-11-15T21:50:16.863 回答