prisma: Raw query failed. Code: `42601`. Message: `db error: ERROR: syntax error at or near "$1"` Postgresql INTERVAL

Bug description

const time = 5

await this.prisma.$executeRaw`
UPDATE public.user SET chat_banned_time = NOW() + INTERVAL '${time} MINUTES' WHERE id = ${userId}
`;
PrismaClientKnownRequestError:
Invalid `prisma.executeRaw()` invocation:


  Raw query failed. Code: `42601`. Message: `db error: ERROR: syntax error at or near "$1"`
    at Object.request (C:\disapp\api\node_modules\@prisma\client\runtime\index.js:45629:15)
    at async Proxy._request (C:\disapp\api\node_modules\@prisma\client\runtime\index.js:46456:18)
    at async Service.handler (C:\disapp\api\services\player\chat\chat.service.js:581:22)
    at async Service.callAction (C:\disapp\api\node_modules\moleculer-web\src\index.js:636:16)
    at async C:\disapp\api\node_modules\moleculer-web\src\index.js:461:22 {
  code: 'P2010',
  clientVersion: '3.13.0',
  meta: {
    code: '42601',
    message: 'db error: ERROR: syntax error at or near "$1"'
  }
}

How to reproduce

const time = 5

await this.prisma.$executeRaw`
UPDATE public.user SET chat_banned_time = NOW() + INTERVAL '${time} MINUTES' WHERE id = ${userId}
`;

Expected behavior

No response

Prisma information

model User {
  id               Int              @id @default(autoincrement())
  chatBannedTime   DateTime?        @map("chat_banned_time")
}

Environment & setup

  • OS:
  • Database:
  • Node.js version:

Prisma Version

"prisma": "^3.13.0"

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 9
  • Comments: 21 (6 by maintainers)

Most upvoted comments

For some reason, Prisma does not accept the use of variables for table names and field names. One way I found to solve this problem was to use an auxiliary variable to assemble the query and then use this variable with queryRaw.

See an example below:

const query = `
  SELECT * FROM "${options.table}"
  WHERE "${options.column}" = '${value}'
`;

const row: any[] = await prisma.$queryRaw`${Prisma.raw(query)}`;

Important:

  • If the name of the table or field contains double quotes, they must be placed in the query.
  • It is necessary to use Prisma.raw() for the query to work.

@janpio I’ll try to put together something soon to cover the suggestions.

On further thought I’m not sure whether it’d be wise to try and do a Prisma.identifier concept since it’ll be so frequently inapplicable - it’d be trying to solve for a user education issue but would probably just open its own can of worms. I think there might already be an existing issue for queryRaw error logging so I’ll hunt around for that before creating a new one.

For some reason, Prisma does not accept the use of variables for table names and field names. One way I found to solve this problem was to use an auxiliary variable to assemble the query and then use this variable with queryRaw.

See an example below:

const query = `
  SELECT * FROM "${options.table}"
  WHERE "${options.column}" = '${value}'
`;

const row: any[] = await prisma.$queryRaw`${Prisma.raw(query)}`;

Important:

  • If the name of the table or field contains double quotes, they must be placed in the query.
  • It is necessary to use Prisma.raw() for the query to work.

@lucasjribeiro I just wanted to call out an additional major issue with this approach since it looks like several users have upvoted your comment. Your query is entirely subject to SQL injection attacks; it looks like you are parameterizing the query, but in reality you’ve just created a normal template string with options.table, options.column, and value interleaved and then told Prisma to run it. This might occasionally be fine if each of those variables are entirely trustworthy, but I’d be surprised.

For instance, if you’re using this options table to decide which are available to a user, we could just inject with something like this to get every option from that table: const value = '\' OR 1=1 OR \'\' = \''. You want to be extremely careful when using Prisma.raw - whenever you apply that, you’re just issuing a string and need to sanitize carefully for SQL injection yourself.

+1 facing the same issue

Suppose your code has string parameters. then try this. it worked for me

//example 1
let userTable = 'User'
let result = await prisma.$queryRawUnsafe(`SELECT * FROM ${userTable}`)

//my code
const lastMonday = `'${lastMonday}'`;
const thisMonday = `'${thisMonday}'`;

const userInterest =
    await prisma.$queryRawUnsafe<InterestUser>(`Select user_id, SUM(interest_amount) as weekly_amount  from "Interest"
        where
        created_date between ${lastMonday} AND ${thisMonday}
         GROUP BY user_id
         HAVING SUM(interest_amount) > 1`);

Can reproduce in 3.13.0 but not in 4.0.0 or current internal dev version. This seems to be already fixed. Please upgrade your version.

Note: a workaround would be to use $executeRawUnsafe() like

 const test1 = await prisma.$executeRawUnsafe(`
  UPDATE "User" SET chat_banned_time = NOW() + INTERVAL '${time} MINUTES' WHERE id = ${userId}`);

Not any of the OPs, but I think almost every one of the issues described here are byproducts of not understanding how Prisma injects query parameters.

For instance, @lucasjribeiro - if you want to have a dynamic table value, most database engines can’t parameterize it (which is what you’re doing). As an alternative, try something like this:

    const query = Prisma.sql`
      SELECT * FROM "${Prisma.raw(options.table)}"
      WHERE "${Prisma.raw(options.column)}" = ${value}
    `;
    
    const row: any[] = await prisma.$queryRaw(query);

You need to provide the actual, raw values (without parameterization) for anything which isn’t a value. If you had a dynamic function, that also needs to be injected raw without parameterization. If you just template the values into the query they’ll all be treated as parameters which is invalid syntax.

Same for @kpturner - your date-field = NOW() + INTERVAL '${days} days' sample would need to make your days parameter raw since you’re already quoting it (e.g. date-field = NOW() + INTERVAL '${Prisma.raw(days)} days'). If you wanted it to be parameterized, you could’ve just concatenated the interval string like this: date-field = NOW() + INTERVAL concat(${days}, 'days').

And same for @patrickJramos where both the schema and the table references need to be raw.

Even the OP had this problem in their query: UPDATE public.user SET chat_banned_time = NOW() + INTERVAL '${time} MINUTES' WHERE id = ${userId} should have been UPDATE public.user SET chat_banned_time = NOW() + INTERVAL concat(${time}, ' MINUTES') WHERE id = ${userId} since the interval function expects a single interval string spec.

All of that being said, @janpio - maybe it’d be worth just creating a Prisma.identifier type which behaves similarly to Prisma.raw just to make it clearer that there are scenarios where a template variable isn’t going to play well with parameterization. Worth noting, parameters can actually be applied to identifiers in certain scenarios (e.g. here’s the Postgres doc on that).

It’d also be amazing if any more information can be logged when a raw query fails. At the moment the error doesn’t even provide the failing query content so it can be incredibly frustrating to triage. I actually ended up on this ticket for entirely unrelated reasons but the error logging is so generic that any syntax error ends up looking the same. Maybe there’s already a ticket for this? I’d be happy to create coverage if not.

I am unfortunately not able to do that in next few days. Anyhow it would not be the query I would have to share, but the generation using template strings. Queries are generated, by a function. Table names are dynamically added and some conditions based on functions params will be added.

Though, it is now working with prisma.$rawQuery and actually that is totally fine. My queries are for calculating statistics and filling other tables. None of the params are changeable by any user.

I can reproduce in 4.0.0 and in 4.3.1. My query is way more complex and it was working with 3.x

i have a similar issues. const result = await this.prismaService.$queryRaw(Prisma.sql${raw}) above line return the same error as yours. i also tried const result = await this.prismaService.$queryRaw${raw} but return the same error.

this is my raw content

        let rawSU: string = "SELECT type, null as hotel_id, action, old_value, new_value, change, creator_type, created_by, created_at FROM system_user_activity_log"
        let rawSC: string = "SELECT type, null as hotel_id, action, old_value, new_value, change, creator_type, created_by, created_at FROM system_configuration_log"
        let rawHS: string = "SELECT type, hotel_id, action, old_value, new_value, change, creator_type, created_by, created_at FROM hotel_subscription_log"

        let from: string
        let to: string
        if (query.change) {
            rawSU = rawSU + ` where change like '%${query.change}%'`
            rawSC = rawSC + ` where change like '%${query.change}%'`
            rawHS = rawHS + ` where change like '%${query.change}%'`
        }
        if (query.user) {
            rawSU = rawSU + ` and where change = ${query.user}`
            rawSC = rawSC + ` and where change = ${query.user}`
            rawHS = rawHS + ` and where change = ${query.user}`
        }
let raw = `${rawSU} UNION ALL ${rawSC} UNION ALL ${rawHS}`
        raw = raw + ` offset 0 limit 10`
        // const result = await this.prismaService.$queryRaw(Prisma.sql`${raw}`)
        const result = await this.prismaService.$queryRaw`${raw}`

but if i copy the content of raw it’s working fine.

const result = await this.prismaService.$queryRaw(Prisma.sql`SELECT type, null as hotel_id, action, old_value, new_value, change, creator_type, created_by, created_at FROM system_user_activity_log UNION ALL SELECT type, null as hotel_id, action, old_value, new_value, change, creator_type, created_by, created_at FROM system_configuration_log UNION ALL SELECT type, hotel_id, action, old_value, new_value, change, creator_type, created_by, created_at FROM hotel_subscription_log offset 0 limit 10`)

Same trouble