2011-11-15 57 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。這產生了巨大的日誌文件。