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

Syntax error at or near "$1" at "Query parameters" #772

Open VshivcevA opened 6 months ago

VshivcevA commented 6 months ago

Hello. I'm trying to make a dynamic request. I try to do it as closely as possible to the documentation, but I still get syntax error at or near "$1" Can you tell me what I'm doing wrong?

const days = 1
const result = await sql`
        select *
        from ${sql(table)}
        where
            timestamp >= current_timestamp - interval ${days} day
    `

When i use timestamp >= current_timestamp - interval '1' day all works correctly

Louis-Tian commented 6 months ago

The days variable is a number and it translates to interval 1 day instead of interval '1' day. The former is not valid SQL in Postgres.

VshivcevA commented 6 months ago

Thank you, then how do I use this value as a variable?

ogelami commented 6 months ago

I ran into the same issue, would love to get a suggestion on how to use variable intervals.

maxlang commented 5 months ago

What about using one of the solutions from here: https://stackoverflow.com/questions/7796657/using-a-variable-period-in-an-interval-in-postgres

const describe = await sql`
  select *
  from ${sql(table)}
  where
      timestamp >= current_timestamp - (${days} || ' day')::INTERVAL`.describe()

and

const describe = await sql`
  select *
  from ${sql(table)}
  where
      timestamp >= current_timestamp - ${days} * INTERVAL '1 day'`.describe();

both seem to work for me (but I haven't actually run the queries.)

josh-i386g commented 2 months ago

Encountered this before, what worked for me is ${sql(variable)}.

Encountered similar issue today but it's different, it's on SET not working, following solved it for me: https://github.com/porsager/postgres/issues/640#issuecomment-1636850807