pg-promise ColumnSet 使用带有 def 属性 的 Postgres 函数
pg-promise ColumnSet use Postgres functions with def property
我正在使用 ColumnSet and the helper.insert 函数进行多行插入。
我有一个 table 列,我想在其中使用 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' } })
您的代码看起来不正确,原因如下:
- 您想无条件地使用
now()
,但 def
值仅在源对象中不存在 属性 时使用(请参阅 Column). init
回调应该用来保证正确的值覆盖。
- 您 return
now()
作为转义字符串,而查询需要它作为原始文本字符串。
首先,让我们声明一个可重复使用的 Raw Text string, as per 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()'
}
然而,这种语法适用于库的所有版本,而且使用起来可能更简单;)
我正在使用 ColumnSet and the helper.insert 函数进行多行插入。
我有一个 table 列,我想在其中使用 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' } })
您的代码看起来不正确,原因如下:
- 您想无条件地使用
now()
,但def
值仅在源对象中不存在 属性 时使用(请参阅 Column).init
回调应该用来保证正确的值覆盖。 - 您 return
now()
作为转义字符串,而查询需要它作为原始文本字符串。
首先,让我们声明一个可重复使用的 Raw Text string, as per 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()'
}
然而,这种语法适用于库的所有版本,而且使用起来可能更简单;)