我转储了我的表数据:
COPY( SELECT * FROM tariff_details ) TO STDOUT WITH( FORMAT CSV, HEADER )
数据:
id,tariff_id,name,price,option,periodic,value,sorder
17,1,Setup fee,5.000000000000000000,,f,,0
当我恢复数据时:
COPY tariff_details FROM STDIN WITH( FORMAT CSV, HEADER )
我收到错误:
ERROR: null value in column "periodic" violates not-null constraint
DETAIL: Failing row contains (17, 1, Setup fee, 5.000000000000000000, null, f, null, 0).
CONTEXT: COPY tariff_details, line 2: "17,1,Setup fee,5.000000000000000000,,f,,0"
数据库中的表定义为下一个:
Column | Type | Modifiers
-----------+-----------------------+-------------------------------------------------------------
id | integer | not null default nextval('tariff_details_id_seq'::regclass)
tariff_id | integer | not null
name | character varying(64) | not null
price | tmoney | not null
periodic | boolean | not null default false
option | character varying(16) |
value | text |
sorder | integer | not null default 0
您可以看到字段option
和periodic
被翻转。
HEADER
指定文件包含标题行,其中包含文件中每列的名称。在输出时,第一行包含表中的列名,在输入时,忽略第一行。仅在使用CSV格式时才允许使用此选项。
如何告诉postgres使用CSV文件中的列顺序? 有可能吗?
UPD
作为解决方法,我使用:line=$$(head -n 1 ${APP_ROOT}/db/${TABLE}.dump.csv)
dbrestoretable: export PGPASSWORD = ${DB_PASS}
dbrestoretable:
line=$$(head -n 1 ${APP_ROOT}/db/${TABLE}.dump.csv)
@cat ${APP_ROOT}/db/${TABLE}.dump.csv | \
psql -h ${DB_HOST} -p ${DB_PORT} -U ${DB_USER} ${DB_NAME} -c \
"BEGIN;COPY ${TABLE}($$line) FROM STDIN WITH( FORMAT CSV, HEADER );COMMIT;" ||:
答案 0 :(得分:1)
您只需在COPY FROM
中指定 目标 列名:
COPY tariff_details(id,tariff_id,name,option,price,periodic,value,sorder)
FROM STDIN WITH (FORMAT CSV, HEADER);
(我翻了option
和periodic
。)
除此之外:SELECT * FROM tbl
以确定性顺序返回列 - 如pg_attribute.attnum
中所定义。因此,在转储和恢复之间,数据库中的某些内容已经发生了变化。
答案 1 :(得分:0)
在解决时,我使用:columns=$$(head -n 1 ${APP_ROOT}/db/${TABLE}.dump.csv)
dbrestoretable: export PGPASSWORD = ${DB_PASS}
dbrestoretable:
columns=$$(head -n 1 ${APP_ROOT}/db/${TABLE}.dump.csv)
@cat ${APP_ROOT}/db/${TABLE}.dump.csv | \
psql -h ${DB_HOST} -p ${DB_PORT} -U ${DB_USER} ${DB_NAME} -c \
"BEGIN;COPY ${TABLE}($$columns) FROM STDIN WITH( FORMAT CSV, HEADER );COMMIT;" ||: