I observed this code example from the 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)
I'm trying to do something similar, here's a 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)
I use pgp.as.format
to view the SQL being passed onto postgres. The output from the above is this:
{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}')
I formatted the SQL for readability sake.
This SQL obviously doesn't work as the whole object is provided as a single string and returns the error:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): error: INSERT has more target columns than expressions
I expected VALUES()
to be formatted as in the documentation.
How come the documentation example doesn't work in my MWE? Is it because of the db.query
-> db.none
function swap?
Looks like the issue is with the library version.
Current version is 8.2.2
. And automatic property enumeration was added in version 7.5.0.
I'm certain that you are using a version older than that, and hence the problem.
In general, assume that the current documentation always covers the very latest version of the library ;)
When in doubt what version is being loaded, you can do the following:
console.log(db.$config.version);