【问题标题】:How to insert an integer with nextval function in an multirow insert in pg-promise如何在 pg-promise 的多行插入中插入带有 nextval 函数的整数
【发布时间】:2020-05-15 19:41:04
【问题描述】:

是否可以在 pg-promise 多行插入中使用 nextval 函数? 我有一个数据库(很遗憾我无法更改),其中 id 必须通过客户端插入,如下所示:

INSERT INTO some_object (object_id, object_name)
VALUES (nextval('some_object_seq'), ${object_name})
RETURNING object_id;

这适用于一个插入。但现在我必须一次插入多行并尝试 pgp.helpers.insert:

const cs = pgp.helpers.ColumnSet(['object_id', 'object_name'], { table });
const query = pgp.helpers.insert(values, cs)  + 'RETURNING object_id';
database.many(query).then(data => {
  return data
}).catch(error => {
  logger.error(error, query);
});

在这种情况下有什么方法可以使用 nextval('some_object_seq') 吗?遗憾的是,我无法更改表定义中 id 列的默认值。

【问题讨论】:

  • 您确定object_id 列还没有DEFAULT 的序列吗?
  • 你可以给你的ColumnSet一个default expression for the object_id column
  • 是的,我确定没有设置 DEFAULT,我无法更改。我试过 { name: "object_id", def: "nextval('some_object_seq')" } 但 nextval 然后作为字符串发送而不被识别为函数。
  • 啊,我忘了添加这个:mod:'^',谢谢你指出我正确的方向!

标签: node.js postgresql pg-promise


【解决方案1】:

你的栏目应该这样定义:

{
    name: `object_id`,
    init: () => `nextval('some_object_seq')`,
    mod: `:raw`
}

与@baal 的回答相反,您不需要使用def,因为您没有提供默认值,而是完全覆盖该值,这就是init 的用途。

它也可以在 upsert 查询中使用。

【讨论】:

  • 感谢您的评论。会尝试并接受这个作为答案!
【解决方案2】:

正如 Bergi 所写,可以像这样向列集添加默认表达式:

const cs = pgp.helpers.ColumnSet(
        [{
            name: "object_id",
            // setting the DEFAULT value for this column
            def: "nextval('some_object_seq')", 
            // use raw-text modifier to inject string directly
            mod: "^",
        }, 'object_name'], { table });

【讨论】:

  • 此解决方案唯一不能忘记的缺点:此列集不能用于update
  • @Bergi 是的,但它可以与 upsert 查询一起使用。
猜你喜欢
  • 2017-06-07
  • 2016-09-15
  • 2015-11-23
  • 1970-01-01
  • 2019-09-27
  • 2020-03-04
  • 2019-11-12
  • 1970-01-01
  • 2016-07-14
相关资源
最近更新 更多