【问题标题】:pg-promise ColumnSet use Postgres functions with def propertypg-promise ColumnSet 使用带有 def 属性的 Postgres 函数
【发布时间】:2017-11-03 22:14:21
【问题描述】:

我正在使用ColumnSethelper.insert 函数进行多行插入。

我有一个表格列,我想在其中使用 Postgres Date/Time now() 函数。

const cs = new helpers.ColumnSet([
    'lastname',
    {
        name: 'rental_date',
        def: 'now()'
    }
], { table: { table: 'book_rental', schema: 'public' } })

let rentals = [
    {
        lastname: 'Mueller'
    },
    {
        lastname: 'Johnson'
    }
]

let insert = helpers.insert(rentals, cs)

db.result(insert)
    .then(data => res.json({ message: 'Ok!' }))
    .catch(err => res.json({ message: 'Not ok!' }))

使用def: 'now()' 似乎可以正常工作,但我想确保以正确的方式使用它。

编辑:

关于评论中的答案。我尝试手动进行插入,看起来 Postgres 正在将 'now()' 字符串转换为 now() 函数。

INSERT INTO book_rental (lastname, rental_date) VALUES ('Mueller', 'now()');

涉及您的答案,我认为这应该是正确的代码吗?

const cs = new helpers.ColumnSet([
    'lastname',
    {
        name: 'rental_date',
        mod: ':raw',
        def: 'now()'
    }
], { table: { table: 'book_rental', schema: 'public' } })

【问题讨论】:

  • It seems to be working? 你能说得更具体点吗?看起来它不起作用,因为您需要使用原始文本字符串,而不是转义文本字符串。
  • 对不起,我是说使用上面的代码并在插入后检查数据库,rental_date 正确存储为timestamptz。这就是为什么我认为它有效。
  • def 仅在属性缺失时使用。如果没有丢失,则使用列值代替,因此它可能无法正常工作。如果你想确定,你应该改用init
  • 您的更新确实可以解决一个问题。对于另一个 - 见我的回答;)
  • 您知道,:raw 内联语法更短,并且适用于库的所有版本。作为作者,我自己有时甚至会忘记这些细节 :))) 毕竟,我确实将它设计为最终灵活。所以我更新了我的答案。我

标签: javascript pg-promise


【解决方案1】:

您的代码看起来不正确,原因如下:

  • 您想在没有任何条件的情况下使用now(),但def 值仅在源对象中不存在该属性时使用(请参阅Column)。应该使用 init 回调来保证正确的值覆盖。
  • 您将 now() 作为转义字符串返回,而查询需要它作为原始文本字符串。

首先,让我们声明一个可重用的Raw Text 字符串,就像Custom Type Formatting

const rawText = text => ({toPostgres: () => text, rawType: true});

然后你可以像这样定义列:

{
    name: 'rental_date',
    init: () => rawText('now()')
}

并确保您使用的是最新版本的 pg-promise(在撰写本文时为 v7.2.1)。

或者,您也可以这样声明:

{
    name: 'rental_date',
    mod: ':raw', // same as mode: '^'
    init: () => 'now()'
}

然而,这种语法适用于所有版本的库,而且使用起来可能更简单;)

【讨论】:

  • 我知道我不应该仅仅将评论用于“谢谢”。但我不得不说非常感谢! :)
猜你喜欢
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
  • 1970-01-01
  • 2021-06-16
  • 2016-06-18
  • 2017-11-18
相关资源
最近更新 更多