从 csv 自动生成 ids 的 psql 复制

psql copy from csv automatically generating ids

考虑一下这样创建的 table:

CREATE TABLE public.test
(
    id integer NOT NULL DEFAULT nextval('user_id_seq'::regclass),
    name text,
    PRIMARY KEY (id)
)

所以 table 有一个唯一的 'id' 列,它使用序列自动生成默认值。

现在我想从 csv 文件导入数据,扩展这个 table。但是 "obviously" id 需要是唯一的,因此我希望让数据库本身生成 id,csv 文件本身(来自完全不同的来源)因此具有 "empty column" 的 id:

,username
,username2

但是,如果我随后使用 psql 导入此 csv:

\copy public."user" FROM '/home/paul/Downloads/test.csv' WITH (FORMAT csv);

弹出如下错误:

ERROR:  null value in column "id" violates not-null constraint

那我该怎么做呢?

CSV 文件中的空列被解释为 SQL NULL,插入该值会覆盖 DEFAULT 并导致错误。

您应该省略文件中的空列并使用:

\copy public."user"(name) FROM '...' (FORMAT 'csv')

那么id将使用默认值。