如何在pg-promise的多行插入中使用nextval函数插入整数

问题描述 投票:0回答:1

是否可以在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列的默认值。

node.js postgresql pg-promise
1个回答
1
投票

正如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 });
© www.soinside.com 2019 - 2024. All rights reserved.