So I'm a little stuck here.
I have an object such as:
var lineItems = [
{
id: 1,
quantity: 10
},
{
id: 2,
quantity: 15
},
{
id: 4,
quantity: 22
}
]
now what I need to do is loop through this in a pg-promise SQL transaction to ensure that the row item in the database quantity for the associated id is >= the object items, so:
SELECT * FROM inventory WHERE id = $1 AND quantity >= $2, [1,10],
SELECT * FROM inventory WHERE id = $1 AND quantity >= $2, [2,15],
SELECT * FROM inventory WHERE id = $1 AND quantity >= $2, [4,22]
if I receive 3 results then the object is true and i'm able to insert the request with
INSERT INTO orders SET a = 1, b = 2, c = 3, items = lineItems::json etc RETURNING id;
and of course if i have less results than in the lineItems object then I don't bother with the INSERT
statement, and simply return a 'item id: 4, quantity:22 doesn't have enough inventory to perform your request...
I was initially using:
db.tx(function(t)){
return this.batch([
checkInventory
])
.then(function(inv){
console.log( inv );
});
})
.then(function(results){
console.log( results );
})
.catch(function(error){
console.log( error );
});
where checkInventory
is the function I'm calling as
var checkInventory = function(){
console.log( '|-------------------------------------|' );
console.log( 'LINE ITEMS >> ', lineItems );
var query = [], sql = '';
for( var i = 0; i < lineItems.length; i++ ){
sql += 'SELECT quantity FROM pim_inventory WHERE';
sql += ' product_id = $1 AND quantity >= $2;';
var pquery = [
lineItems[i].id,
lineItems[i].quantity
];
query.push(this.one(sql, pquery));
}
console.log( 'invQUERY >> ', query );
return query;
};
which is generating the following errors:
(node:44810) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): QueryResultError: Multiple rows were not expected.
(node:44810) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 4): error: syntax error at or near "product_id"
|-------------------------------------|
EVENTS >> [ [ Promise {
<rejected> QueryResultError: Multiple rows were not expected.
at QueryResultError.Error (native)
at new QueryResultError (/Users/directtap-dev/www/GitHub/v1.02/node_modules/pg-promise/lib/errors.js:13:22)
at Query.callback (/Users/directtap-dev/www/GitHub/v1.02/node_modules/pg-promise/lib/index.js:629:38)
at Query.handleReadyForQuery (/Users/directtap-dev/www/GitHub/v1.02/node_modules/pg/lib/query.js:89:10)
at Connection.<anonymous> (/Users/directtap-dev/www/GitHub/v1.02/node_modules/pg/lib/client.js:163:19)
at emitOne (events.js:101:20)
at Connection.emit (events.js:188:7)
at Socket.<anonymous> (/Users/directtap-dev/www/GitHub/v1.02/node_modules/pg/lib/connection.js:109:12)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7) },
Promise { <rejected> [Object] } ] ]
any ideas?