0

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

4

2 回答 2

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 });
于 2020-01-30T09:35:42.690 回答
1

您的列应定义为:

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

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

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

于 2020-01-30T09:50:51.947 回答