queryRaw doesn't support dynamic tables names
See original GitHub issueBug description
const values = await prisma.$queryRaw`SELECT type FROM ${collection};`; fails with the error
 Message: `db error: ERROR: syntax error at or near "$1"
However,
const values = await prisma.$queryRawUnsafe(`SELECT type FROM ${collection};`); works fine.
Does anyone know why this occurs? I need to be able to be use the safe version to prevent SQL injection in my app 😕
How to reproduce
Raw query a postgres database with a dynamic table name.
Expected behavior
No response
Prisma information
generator client {
  provider = "prisma-client-js"
}
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}
model spacebudz {
  type              String?
}
Environment & setup
- OS: Mac OS
 - Database: PostgreSQL
 - Node v16.10.10
 
Prisma Version
3.2.1
Issue Analytics
- State:
 - Created 2 years ago
 - Reactions:4
 - Comments:9 (2 by maintainers)
 
Top Results From Across the Web
Raw database access (Reference)
Prisma Client supports the option of sending raw queries to your database. ... $queryRaw does not support dynamic table names in PostgreSQL databases....
Read more >Prisma queryRaw throws error when using template string ...
I'm trying to write a service that takes the table name as a parameter, and the service itself calls queryRaw to run a...
Read more >Prisma $queryRaw with variable length parameter list
I need to use $queryRaw for a particular query due to use of unsupported tsvector type in the underlying table. In this query,...
Read more >Performing raw SQL queries
By default, Django figures out a database table name by joining the model's “app label” ... Dictionary params are not supported with the...
Read more >8 Coding Dynamic SQL Statements
You should use dynamic SQL in cases where static SQL does not support the operation ... You might let a user specify the...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

I actually found a solution to this that’s slightly safer imo than
$queryRawUnsafewhich is you can wrap the table name withconst tableArg = Prisma.raw(tableName)and then usetableArg. This makes things slightly safer as its easier to validate thetableNamethan the entire string.@MilesConn
This is a great and quick fix that actually worked for me:
Just wrap your inserted variable with
Prisma.raw()and it should work.In this context:
const values = await prisma.$queryRaw SELECT type FROM ${Prisma.raw(collection)};should do the job!