【问题标题】:Node pg-promise, bind multiple values with type casting节点 pg-promise,使用类型转换绑定多个值
【发布时间】:2020-12-22 20:43:11
【问题描述】:

我目前正在使用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 表示法?

【问题讨论】:

    标签: pg-promise


    【解决方案1】:

    将列定义改为这个:

    {
        name: 'timeslot',
        mod: ':raw',
        init: c => pgp.as.format('to_timestamp($1)', 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' 来更改值的来源。

    【讨论】:

      猜你喜欢
      • 2017-10-20
      • 2017-02-23
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2015-12-04
      • 1970-01-01
      • 2011-06-01
      相关资源
      最近更新 更多