node-sql-template-strings icon indicating copy to clipboard operation
node-sql-template-strings copied to clipboard

Binding with IN operator

Open gavinbelson opened this issue 6 years ago • 5 comments

We are trying to use useBind() with a sequelize IN raw query going to MSSQL.

This works great if status has one element. However, when there are multiple elements in status:

status = ["Completed","In Progress"] query.append(SQL WHERE status IN ( ${status} )) statuses = await db.query(query.useBind(), {raw: true, nest: true});

The query doesn't return anything. The log from sequelize shows:

{"plain":false,"raw":true,"nest":true,"bind":[["Completed","In Progress"]],"type":"SELECT","level":"info","message":"Executing (default): SELECT * FROM some_table WHERE status IN ( @0 )"}

If I take out the .useBind() the query works as expected, uses replacements, and returns both statuses of "Completed" and "In Progress"

gavinbelson avatar Dec 11 '18 01:12 gavinbelson

I am not familiar with MSSQL, but usually you can’t use a single placeholder to replace all values passed to IN. You would need one placeholder per value, but you don’t know the number of values, so it’s not the same prepared query anymore for different values. In Postgres for example this doesn’t work with IN, but it does work with ANY, because ANY takes a single array value as operand that you can use a single placeholder for.

felixfbecker avatar Dec 11 '18 09:12 felixfbecker

It works without useBind() because then Sequeluze will just generate a different query. If you leave it in, Sequelize will pass the query with placeholders and values to the DB, and the DB won’t know what to do with a single placeholder in IN and an array of values.

felixfbecker avatar Dec 11 '18 09:12 felixfbecker

That makes sense, but a lot of the time, when you are doing bindings, it needs to be used with the IN operator.

So, right now there is no way of doing bindings with the IN operator right?

gavinbelson avatar Dec 11 '18 22:12 gavinbelson

No, it's impossible.

felixfbecker avatar Dec 11 '18 22:12 felixfbecker

Maybe you can use appendIn See #141

DblK avatar Feb 11 '21 17:02 DblK