3

My pg-promise query (2 ids in array passed in):

db.any(`SELECT * FROM users WHERE user_id IN ($1:csv)`, team.member_ids)

Console output of query and params passed to pg-promise:

SELECT * FROM users WHERE user_id IN ($1:csv) [ 1, 2 ]
//Fails one row returned, two expected

However I get only one result. If I run the following query in psql I get two results:

select * from users where user_id IN (1,2);
//Works successfully with two rows returned

Any help is appreciated!

vitaly-t
  • 24,279
  • 15
  • 116
  • 138
Ron I
  • 4,090
  • 8
  • 33
  • 64
  • when I run db.any(`SELECT user_id FROM users`) I get: [ { user_id: 2 }, { user_id: 1 } ] – Ron I Oct 21 '19 at 16:53

1 Answers1

1

This is explained in Query Formatting, how one value versus array changes the values interpretation:

This however works only for types number, bigint, string, boolean, Date and null, because types like Array and Object change the way parameters are interpreted.

db.any(`SELECT * FROM users WHERE user_id IN ($1:csv)`, team.member_ids)
//=> SELECT * FROM users WHERE user_id IN (1)

Because above you are passing in the value-array itself directly, $1 refers to the first element in that array. To make $1 refer to the entire value-array, that value itself needs to be inside an array:

db.any(`SELECT * FROM users WHERE user_id IN ($1:csv)`, [team.member_ids])
//=> SELECT * FROM users WHERE user_id IN (1,2)

Alternatively, the recommended use of Named Parameters makes the code more concise:

db.any(`SELECT * FROM users WHERE user_id IN ($<member_ids:csv>)`, team)
//=> SELECT * FROM users WHERE user_id IN (1,2)

In general, use pg-monitor to see what queries are being executed.

vitaly-t
  • 24,279
  • 15
  • 116
  • 138