I've seen other libraries automatically protect against it, does pg-promise too? Or do I need to implement my own solution/use prepared statements?
Thanks.
You can either use prepared statements, or if you only send in dynamic column names, then you should use SQL Names to escape them properly.
If I created my query with something like this:
function insert(table, values) {
const keys = Object.keys(values),
columns = keys.join(', '),
placeholders = keys.map((k, i) => '$' + (i + 1)).join(', '),
query = `INSERT INTO ${(table)} (${columns}) VALUES (${placeholders})`;
return db.none(query, keys.map(k => values[k]));
}
...
const data = {
name: req.body.name,
email: req.body.email,
phone: req.body.phone
}
...
insert('table_name', data)
.then(function() {
console.log('Success');
})
.catch(function(err) {
console.log('Error: ' + err);
})
Would it be protected against SQL injection?
Not quite. As I said earlier, you should use SQL Names, do not the table name directly.
Better still, using helpers.insert is so much better ;)
Most helpful comment
You can either use prepared statements, or if you only send in dynamic column names, then you should use SQL Names to escape them properly.