Skip to content
Advertisement

Express-Postgres fails to apply array filter: error: operator does not exist: integer[] && text[]

The same query works on the terminal. But for some reason I’m getting an error:

pg.query is unable to process the expression path && Array[$1] using this: https://www.postgresql.org/docs/9.2/functions-array.html

Advertisement

Answer

This should work:

Why?

Short answer: type resolution.

Long answer:

Concluding from the error message that comments.comment_id is of type integer. Forming an array from it with ARRAY[comment_id] produces an integer array: integer[], or int[] for short.

You want int[] or compatible on the other side, not text[]. Untyped string literals are passed (I assume, but the solution also works for parameters typed text or varchar). When fed to the ARRAY constructor in ARRAY[$1], type resolution is forced before a matching type can be deferred from the assignment in the expression. The default type is text, so you get text[]. Hence the error message:

Explanation by example:

db<>fiddle here

You can fix this with an explicit cast, either before or after the ARRAY constructor is applied. But it’s slightly cheaper to do it first.

Then again, my alternative, equivalent syntax is cheaper, yet:

Also, if comments.comment_id can be NULL (which you also did not specify) or the recursive CTE adds a NULL to the array (the one at hand does not), your original expression with the ARRAY “overlap” operator && would fail as it cannot cope with NULL elements. So twice better.

The array operator would make sense to employ a GIN index on an array column. But a derived array column is never indexed, so there is no point in using the more expensive operator. See:

I added explicit casts to integer for both parameters. Does not hurt, but it’s not necessary in my version of the query – if parameters are passed as untyped string literals (which I assume).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement