节点 pg-promise,通过类型转换绑定多个值

Node pg-promise, bind multiple values with type casting

我目前正在使用 pg-promise 库以以下格式将多个值插入数据库:

const cs = new pgp.helpers.ColumnSet(['booking_id', {name:'timeslot', cast:'timestamp'}], {table: 'booking'});

// data input values:
const values = [];
bookings.forEach(slot => {
   values.push({booking_id: booking_id, timeslot: slot});
});

我需要时隙作为时间戳的地方。然而它进入 API 作为价值

1515586500.0

使用上面的 cast 属性 我的查询得到了这样的解决

insert into "booking"("booking_id","timeslot") values(1,'1515586500.0'::timestamp)

但是这会引发 cannot cast type numeric to timestamp without time zone

的错误

如果我使用 to_timestamp 函数,但是这会按我需要的方式工作,例如

insert into "booking"("booking_id","timeslot") values(1,to_timestamp('1515586500.0'));

有什么方法可以让 pg-promise 使用 to_timestamp 而不是 ::timestamp 符号?

将列定义更改为此:

{
    name: 'timeslot',
    mod: ':raw',
    init: c => pgp.as.format('to_timestamp()', c.value)
}

{
    name: 'timeslot',
    mod: ':raw',
    init: c => pgp.as.format('to_timestamp(${value})', c)
}

...根据 Column 类型文档。

或者您可以在类型上使用 Custom Type Formatting,自动自行格式化。


此外,您不需要重新映射值以适应 ColumnSet 对象,而是使用 ColumnSet 对象来适应数据。因此,如果列 timeslot 的值在 属性 slot 中,您只需在列定义中使用 prop: 'slot' 来更改值的来源。