Pg-promise: Question about SQL injection

Created on 16 Oct 2016  路  3Comments  路  Source: vitaly-t/pg-promise

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.

question

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.

All 3 comments

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 ;)

Was this page helpful?
0 / 5 - 0 ratings