【问题标题】:Multiple rows insert operation in Postgres should return failed rows informationPostgres 中的多行插入操作应返回失败的行信息
【发布时间】:2018-09-03 20:04:14
【问题描述】:

我想在 Postgres 中使用单个插入语句插入多行。

这里的问题是,如果单行插入失败,则所有其他成功的插入都将被回滚。有没有办法避免回滚并使查询返回失败行的列表。

否则,我最终会编写一个插入语句循环。我正在使用 Node pg 模块。如果 postgres 不支持,是否有推荐的方法来满足我的要求。

编辑 - 1

insert into test(name, email) values ('abcd', 'abcd@a'), ('efgh', 'blah'), (null, 'abcd') ON CONFLICT DO NOTHING;

ERROR:  null value in column "name" violates not-null constraint
DETAIL:  Failing row contains (9, null, abcd).

经过上述查询,select 语句返回 0 行。我正在寻找一种解决方案,其中前两行被插入。

【问题讨论】:

    标签: node.js postgresql


    【解决方案1】:

    听起来你所说的失败是遇到某种独特的约束?查看PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values 以了解与插入...有关的冲突使用问题。

    例如,如果您执行INSERT INTO X VALUES (...100 rows...) ON CONFLICT DO NOTHING;,则任何与主键冲突的重复项都将被忽略。 DO NOTHING 的替代方法是对冲突进行更新。

    编辑以匹配新提出的问题。 On 冲突无助于违反空约束。您可以执行 WITH 子句并仅选择没有空属性的值。这是我刚刚在 Postgres 中测试的示例:

    create extension if not exists pgcrypto;
    create table tmp (id uuid primary key default gen_random_uuid());
    
    with data_set_to_insert as (
        select x.id from (values (null), (gen_random_uuid())) x(id) -- alias x can be anything, does not matter what it is
    )
    insert into tmp(id) select id from data_set_to_insert where id is not null returning *;
    

    【讨论】:

    • 有什么方法可以检索所有行被忽略的信息?
    • 我已经用我正在寻找的内容更新了这个问题。
    • @krisnik 更新了我的答案以添加 WITH 子句示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 2015-03-24
    相关资源
    最近更新 更多