Saturday, 24 April 2021

How to parameterize column names in a pg query

I am trying to dynamically change the column queried in a WHERE statement.

My code looks like this

const pg = require('pg');
const pool = new pg.Pool();
await pool.connect();

let selector = {
  key: 'foo',
  value: 'bar',
};

const result = await pool.query(`SELECT * FROM foobar WHERE ${selector.key}=$1::text`, [selector.value]);

There is only a few key values I switch between. While the key is pre-defined and not from user input I would prefer not to use a template string.

Is there a way to parameterize the column name?

I have tried a few ways.

  1. Just using a default parameter
await pool.query('SELECT * FROM foobar WHERE $1=$2::text', [selector.key, selector.value]);

This doesn't work as it parameterizes the key as a string so is just doing a string comparison.

  1. Casting as oid (this was mentioned somewhere but I can't remember where)
await pool.query('SELECT * FROM foobar WHERE $1::oid=$2::text', [selector.key, selector.value]);

This throws an error as pg doesn't have a way to cast text to oid.



from How to parameterize column names in a pg query

No comments:

Post a Comment