I'm trying to execute this query with pg-promise, version 9.2.1, communicating with Postgres 9.5
All of the following queries work when I run it through the psql
CLI or Postico, just not when I run it from pg-promise.
I started off with this query (I know, using pg keywords for fields is bad, but it's for legacy):
await db.many(
`SELECT * FROM "${schemaName}".versions
UNION
SELECT * FROM "${schemaName}".z_transfer_metadata
UNION
SELECT 'version' AS key, "version"::varchar AS value FROM "${schemaName}".modules WHERE parent_id IS NULL`)
I would get this error from node:
error: syntax error at or near " SELECT"
at Connection.parseE (/app/node_modules/pg/lib/connection.js:604:11)
at Connection.parseMessage (/app/node_modules/pg/lib/connection.js:401:19)
and this from PG:
ERROR: UNION types character varying and bigint cannot be matched at character 133
STATEMENT: SELECT * FROM "the_schema".versions
UNION
SELECT * FROM "the_schema".z_transfer_metadata
UNION
SELECT "version" as key, version::varchar as value FROM "the_schema".modules WHERE parent_id IS NULL
The query was working before I added that third union select, so I pared it down to just that query:
`SELECT 'version' AS key, "version"::varchar AS value FROM "${schemaName}".modules WHERE parent_id IS NULL`
but then PG gives me this error:
ERROR: syntax error at or near "::" at character 35
STATEMENT: SELECT 'version' AS key, "version"::varchar AS value FROM "the_schema".modules WHERE parent_id IS NULL
I've tried multiple variations, including using CAST
and escaping the quotes around 'version'
, and most of the escaping variations work natively, just not through pg-promise.
ERROR: syntax error at or near "AS" at character 41
STATEMENT: SELECT 'version' AS key, CAST("version" AS TEXT) AS value FROM "the_schema".modules WHERE parent_id IS NULL
How can I run this query from pg-promise?
It turns out I had invalid characters in the query, which was causing very strange output like:
23:17:31 error: relation "schema-d123.modules where parent_id is null" does not exist
query: SELECT version FROM "schema-d123".modules WHERE parent_id IS NULL
(note how the where clause was being included in the relation name for some reason, despite the query being displayed correctly)
It turns out I had non-breaking spaces in the query somehow, which I discovered moving my cursor through the query by word (option + left / right in VSCode). I installed the Gremlins extension and found that there were in fact invalid characters in the query:
Once I re-typed the query, everything worked as expected.