2011-11-15 56 views
1

我有一个SQL脚本用于postgres文件与以下命令。记录SQL脚本错误

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

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

例如

ERROR: duplicate key value violates.

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

回答

2

您可以使用数据库日志文件中的大量附加信息记录任何和所有消息(错误,警告,..)。这是标准行为。当然,您的数据库集群必须配置为这样做。 Read the fine manual here

根据您的客户,您还应该能够获得错误消息作为数据库服务器的直接答案。请注意,错误是在不同于数据输出的流上报告的。像在shell中的stoutstderr一样。

shell您可能会调用psql -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 

输出取决于各种settings like 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。这产生了巨大的日志文件。