pg-promise 通过 :name 和 :csv 插入格式

pg-promise insert formatting via :name and :csv

我从 pg-promise documentation:

观察到这个代码示例
   const obj = {
        one: 1,
        two: 2
    };
    db.query('INSERT INTO table(${this:name}) VALUES(${this:csv})', obj);
    //=> INSERT INTO table("one","two") VALUES(1, 2)

我正在尝试做类似的事情,这是一个 MWE:

var insertObj = {rating_text: 'Example goes here!',
                 pros: 'Example pro',
                 cons: 'Example con',
                 stars: '5',
                 product_id: '20',
                 account_id: '1'}
var insertObj['rating_date'] = Date.now()
console.log(insertObj)
console.log(pgp.as.format('INSERT INTO product_rating(${this:name}) VALUES(${this:csv})', insertObj))
db.none('INSERT INTO product_rating(${this:name}) VALUES(${this:csv})', insertObj)

我使用 pgp.as.format 查看传递到 postgres 的 SQL。上面的输出是这样的:

{rating_text: 'Example goes here!',
 pros: 'Example pro',
 cons: 'Example con',
 stars: '5',
 product_id: '20',
 account_id: '1',
 rating_date: 1520886741488}

INSERT INTO product_rating("rating_text",
                           "pros",
                           "cons",
                           "stars",
                           "product_id",
                           "account_id",
                           "rating_date") VALUES('{"rating_text":"Example goes here!",
                                                   "pros"       :"Example pro",
                                                   "cons"       :"Example con",
                                                   "stars"      :"5",
                                                   "product_id" :"20",
                                                   "account_id" :"1",
                                                   "rating_date":1520886741488}')

为了便于阅读,我对 SQL 进行了格式化。

这 SQL 显然不起作用,因为整个对象作为单个字符串提供并且 returns 错误:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): error: INSERT has more target columns than expressions

我希望 VALUES() 的格式与文档中的一样。

为什么文档示例在我的 MWE 中不起作用?是不是因为 db.query -> db.none 函数 swap?

看起来问题出在库版本上。

当前版本是8.2.2。并在版本 7.5.0.

中添加了自动 属性 枚举

我确定您使用的是比该版本更旧的版本,因此出现了问题。


一般来说,假设当前文档总是涵盖最新版本的库;)

如果不确定正在加载哪个版本,您可以执行以下操作:

console.log(db.$config.version);