porsager / postgres

Postgres.js - The Fastest full featured PostgreSQL client for Node.js, Deno, Bun and CloudFlare
The Unlicense
7.09k stars 259 forks source link

Dynamic column selection with nested tagged string error #777

Open lolgesten opened 6 months ago

lolgesten commented 6 months ago

In issue https://github.com/porsager/postgres/issues/588 it says mixing string and tagged string as dynamic columns should work:

const columns = ['name', sql`ST_AsText(location) as loc_txt`];
const cities = await sql`SELECT ${sql(columns)} FROM city`;

However trying this locally, I get an error. As far as I can tell the function escape, str.replace expects only strings, where the tagged string is a Promise.

Is this a regression or intentional?

$ node
Welcome to Node.js v21.2.0.
Type ".help" for more information.
> const sql = require('postgres')();
undefined
> const columns = ['name', sql`ST_AsText(location) as loc_txt`];
undefined
> const cities = await sql`SELECT ${sql(columns)} FROM city`;
Uncaught TypeError: str.replace is not a function
    at escape (/home/node_modules/postgres/cjs/src/types.js:217:20)
    at /home/node_modules/postgres/cjs/src/types.js:213:22
    at Array.map (<anonymous>)
    at escapeIdentifiers (/home/node_modules/postgres/cjs/src/types.js:213:13)
    at Object.select [as fn] (/home/node_modules/postgres/cjs/src/types.js:139:12)
    at Builder.build (/home/node_modules/postgres/cjs/src/types.js:71:17)
    at stringifyValue (/home/node_modules/postgres/cjs/src/types.js:109:38)
    at stringify (/home/node_modules/postgres/cjs/src/types.js:100:16)
    at build (/home/node_modules/postgres/cjs/src/connection.js:223:20)
    at execute (/home/node_modules/postgres/cjs/src/connection.js:167:7)
    at cachedError (/home/node_modules/postgres/cjs/src/query.js:170:23)
    at new Query (/home/node_modules/postgres/cjs/src/query.js:36:24)
    at sql (/home/node_modules/postgres/cjs/src/index.js:112:11)
    at REPL3:1:52
    at cachedError (/home/node_modules/postgres/cjs/src/query.js:170:23)
    at new Query (/home/node_modules/postgres/cjs/src/query.js:36:24)
    at sql (/home/node_modules/postgres/cjs/src/index.js:112:11)
    at REPL3:1:52
alonrbar commented 3 months ago

Seems like the same issue as #701. There's a workaround there you might find useful.