`WHERE col IN` with named parameters

2019-08-03 00:04发布

问题:

In the example on how to use parameterized queries with an IN clause, the syntax is as follows:

const data = [1, 'two', 3, 'four'];

db.any('SELECT * FROM table WHERE id IN ($1:csv)', [data])
    .then(data => {
...

I can't seem to get this to work for named parameters:

db.manyOrNone('SELECT widget FROM widgets WHERE id IN ($(ids:list))', 
              { ids: [1, 2, 3] })

(I'm using :list since it appears to be interchangeable with :csv). I've tried various combinations like:

  • ($(ids):list) (syntax error at or near ":")
  • (${ids:list}) (syntax error at or near "$")

I keep getting invalid syntax errors from Postgres. Is this supported? Or do I have to pass the parameters as an array and reference them like in the example?

Versions:

  • Postgres: 9.5.7
  • pg-promise: 5.7.1

UPDATE I changed my param to be ... WHERE widget IN ($(ids:csv))... and it works now, So it seems that :list and :csv are not interchangeable.

回答1:

The problem is that you are using an ancient version of pg-promise. The current version is 8.4.4, and you are using 5.7.1

Alias :list is fully interchangeable with :csv, but it was added much later than v5.7.1

Upgrade to the latest version, and it will work with :list as well.

Also assume that everything that's in the current documentation refers accordingly, to the current version of the library.