Javascript pg promise ColumnSet使用带有def属性的Postgres函数
我正在使用和函数进行多行插入 我有一个表列,我想在其中使用Postgres函数Javascript pg promise ColumnSet使用带有def属性的Postgres函数,javascript,pg-promise,Javascript,Pg Promise,我正在使用和函数进行多行插入 我有一个表列,我想在其中使用Postgres函数 const cs = new helpers.ColumnSet([ 'lastname', { name: 'rental_date', def: 'now()' } ], { table: { table: 'book_rental', schema: 'public' } }) let rentals = [ { lastname
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!' }))
INSERT INTO book_rental (lastname, rental_date) VALUES ('Mueller', 'now()');
它似乎是通过使用def:'now()'
工作的,但我想确保我使用它的方式是正确的
编辑:
关于评论中的答案。我尝试手动执行插入,看起来Postgres正在将'now()
字符串转换为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!' }))
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' } })
您的代码看起来不正确,原因如下:
- 您希望不带任何条件地使用
,但now()
值仅在源对象中不存在该属性时使用(请参阅)。应该使用def
回调来保证正确的值重写init
- 您将
作为转义字符串返回,而查询需要它作为原始文本字符串now()
{
name: 'rental_date',
init: () => rawText('now()')
}
{
name: 'rental_date',
mod: ':raw', // same as mode: '^'
init: () => 'now()'
}
并确保您使用的是的最新版本(撰写本文时为v7.2.1)
或者,您也可以这样声明:
{
name: 'rental_date',
init: () => rawText('now()')
}
{
name: 'rental_date',
mod: ':raw', // same as mode: '^'
init: () => 'now()'
}
但是,此语法适用于库的所有版本,并且可能更易于使用;)
它似乎起作用了?
你能说得更具体一点吗?它看起来不起作用,因为您需要使用原始文本字符串,而不是转义文本字符串。对不起,我是说使用上面的代码并在插入后检查数据库,rental\u date
正确存储为timestamtz
。这就是我认为它可以工作的原因。def
仅在缺少属性时使用。如果没有丢失,则使用列值,因此可能无法工作。如果你想确定,你应该改用init
。你的更新确实可以解决一个问题。关于另一个,请参见我的答案;)您知道,:raw
内联语法甚至更短,适用于库的所有版本。我自己,作为作者,甚至有时我也会忘记这些细节:)毕竟,我的设计最终是灵活的。所以我更新了我的答案。我知道我不应该用这个评论来表达“谢谢”。但我不得不说,非常感谢你!:)