porsager / postgres

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

How to make LIKE statement with dynamic subsctring? #897

Closed lkoida closed 2 weeks ago

lkoida commented 2 weeks ago

I have to return an order by segment of order id and pin, so, I've tried to do the folowing but all the time have the error.

query example:

 sql`
    SELECT *
      FROM orders
    WHERE id LIKE '${order_id}%' AND pin=${pin};
    `

Error:

PostgresError: could not determine data type of parameter $1
    at ErrorResponse (file:///D:/javascript-course-2023-2024/app/node_modules/postgres/src/connection.js:788:26)
    at handle (file:///D:/javascript-course-2023-2024/app/node_modules/postgres/src/connection.js:474:6)        
    at Socket.data (file:///D:/javascript-course-2023-2024/app/node_modules/postgres/src/connection.js:315:9)   
    at Socket.emit (node:events:518:28)
    at addChunk (node:internal/streams/readable:559:12)
    at readableAddChunkPushByteMode (node:internal/streams/readable:510:3)
    at Readable.push (node:internal/streams/readable:390:5)
    at TCP.onStreamRead (node:internal/stream_base_commons:190:23)
    at cachedError (file:///D:/javascript-course-2023-2024/app/node_modules/postgres/src/query.js:170:23)
    at new Query (file:///D:/javascript-course-2023-2024/app/node_modules/postgres/src/query.js:36:24)
    at sql (file:///D:/javascript-course-2023-2024/app/node_modules/postgres/src/index.js:112:11)
    at Server.<anonymous> (file:///D:/javascript-course-2023-2024/app/server.mjs:92:8) {
  severity_local: 'ERROR',
  severity: 'ERROR',
  code: '42P18',
  file: 'postgres.c',
  line: '741',
  routine: 'pg_analyze_and_rewrite_varparams'

Any suggestion how I should construct such queries? thanks in advance.

porsager commented 2 weeks ago

Remove the quotes and add the '%' to the var like this:

sql`
  SELECT *
  FROM orders
  WHERE id LIKE ${ order_id + '%' } AND pin= ${ pin }
`