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)
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:
Important:
@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.identifierconcept 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 forqueryRawerror logging so I’ll hunt around for that before creating a new one.@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, andvalueinterleaved 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 usingPrisma.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
stringparameters. then try this. it worked for meCan reproduce in
3.13.0but not in4.0.0or current internal dev version. This seems to be already fixed. Please upgrade your version.Note: a workaround would be to use
$executeRawUnsafe()likeNot 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:
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 yourdaysparameter 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 beenUPDATE public.user SET chat_banned_time = NOW() + INTERVAL concat(${time}, ' MINUTES') WHERE id = ${userId}since theintervalfunction expects a single interval string spec.All of that being said, @janpio - maybe it’d be worth just creating a
Prisma.identifiertype which behaves similarly toPrisma.rawjust 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.$rawQueryand 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.0and in4.3.1. My query is way more complex and it was working with 3.xi have a similar issues.
const result = await this.prismaService.$queryRaw(Prisma.sql${raw})above line return the same error as yours. i also triedconst result = await this.prismaService.$queryRaw${raw}but return the same error.this is my raw content
but if i copy the content of raw it’s working fine.
Same trouble