【问题标题】:pg-promise insert formatting via :name and :csvpg-promise 通过 :name 和 :csv 插入格式
【发布时间】:2018-03-16 14:12:06
【问题描述】:

我从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 显然不起作用,因为整个对象作为单个字符串提供并返回错误:

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

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

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

【问题讨论】:

    标签: javascript node.js pg-promise


    【解决方案1】:

    看来问题出在库版本上。

    当前版本是8.2.2。并在7.5.0版本中增加了自动属性枚举。

    我确定您使用的是旧版本,因此存在问题。


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

    当您对正在加载的版本有疑问时,您可以执行以下操作:

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

    【讨论】:

    • 看来你是对的我在 7.3.3 上!谢谢。另一方面,正如您要问的那样,为默认的 postgres timestamp 列插入 javascript Date() 的正确方法是什么?
    • @BML91 你不应该使用timestamp,而是使用timestamptzDate 的默认格式就足够了 ;)
    • 奇怪,我从 timestamp 更改为 timestamptz 但是当尝试插入 Date() 时,我仍然收到错误 invalid input syntax for type timestamp with time zone: "Mon Mar 12 2018 22:47:16 GMT+0000 (GMT)"。 -- 编辑:我的错误 - 我只需要 new Date() 而不是 Date() :)
    猜你喜欢
    • 2010-12-19
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 2017-06-07
    • 2016-07-14
    • 2016-09-15
    • 2021-08-14
    相关资源
    最近更新 更多