1

I am querying an array column (style text[]) using the contains operator @>. My raw query is:

SELECT * FROM songs WHERE style @> '{Acoustic}'

When I drop this into node (using pg-pool) and attempt to parameterize it, the braces surrounding the value reference seem to prevent it from working properly. Note these examples:

const style = 'Acoustic';

// this works, but I don't want to in-line like this:
const { rows } = await pool.query(`SELECT * FROM songs WHERE style @> '{` + style + `}'`);

// this fails with 'error: bind message supplies 1 parameters, but prepared statement "" requires 0'
const { rows } = await pool.query(`SELECT * FROM songs WHERE style @> '{$1}'`, [style]);

What's the proper way to parameterize this?

1
  • Note that I got this working with a different kind of query: pool.query('SELECT * FROM songs WHERE $1 = ANY (style)', [style]);, but I'd like to know if there's a way to work with the form above. Commented Jul 30, 2020 at 6:12

1 Answer 1

2
const { rows } = await pool.query(`SELECT * FROM songs WHERE style @> '{$1}'`, [style]);

The $1 here, being in quotes, is just regarded as part of the string, not as a substitutable variable. If you wish to pass in a scalar and have it treated as an array, you should be able to do it this way:

const { rows } = await pool.query(`SELECT * FROM songs WHERE style @> ARRAY[$1]`, [style]);

An alternative might be to have node.js bind an array directly (not tested):

const { rows } = await pool.query(`SELECT * FROM songs WHERE style @> $1`, [[style]]);
Sign up to request clarification or add additional context in comments.

1 Comment

Both options you gave work, and make it clearer to me how to work with array columns. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.