Node-postgres: Syntax error binding IS NULL query

Created on 18 Oct 2018  路  1Comment  路  Source: brianc/node-postgres

I'm trying to use a bind parameter in an IS query and it generates a PG syntax error I can't replicate in psql.
console.log(sql, values) gives:

DELETE FROM property WHERE code is $1 RETURNING * [ null ]

which logs an error starting:

{ error: syntax error at or near "$1"
...

but the query

DELETE FROM property WHERE code is null RETURNING * 

is valid in psql.

I've traced deep into node-postgres to make sure it's handling the null correctly, so I think this may be a pg issue, but i can't find anything on that.

Most helpful comment

The ... IS NULL predicate is not parameterizable. That syntax is only valid with the word "NULL". You can't put a parameter placeholder. This isn't a node-postgres restriction, it's part of PostgreSQL's SQL syntax.

You can have the SQL handle both situations via something like this:

DELETE FROM property
WHERE ($1 IS NULL AND code IS NULL)
   OR ($1 IS NOT NULL AND code = $1)
RETURNING *

Or even more clearly using the PostgreSQL's IS NOT DISTINCT FROM operator (not as portable to other databases but IMHO much easier on the eyes):

DELETE FROM property
WHERE code IS NOT DISTINCT FROM $1
RETURNING *

See here for more info: https://www.postgresql.org/docs/current/static/functions-comparison.html

>All comments

The ... IS NULL predicate is not parameterizable. That syntax is only valid with the word "NULL". You can't put a parameter placeholder. This isn't a node-postgres restriction, it's part of PostgreSQL's SQL syntax.

You can have the SQL handle both situations via something like this:

DELETE FROM property
WHERE ($1 IS NULL AND code IS NULL)
   OR ($1 IS NOT NULL AND code = $1)
RETURNING *

Or even more clearly using the PostgreSQL's IS NOT DISTINCT FROM operator (not as portable to other databases but IMHO much easier on the eyes):

DELETE FROM property
WHERE code IS NOT DISTINCT FROM $1
RETURNING *

See here for more info: https://www.postgresql.org/docs/current/static/functions-comparison.html

Was this page helpful?
0 / 5 - 0 ratings