In Prisma Client, why is $queryRaw written as a tagged template, and when do $queryRawUnsafe or Prisma.raw reopen SQL injection?
answer
- fragments and values arrive separately
- values only, never identifiers
- join, sql, empty helpers
- verbatim text is the danger
- 64-bit counts come back unusual
basics
~20 s$queryRaw is a tag function, so each ${value} becomes a bind parameter rather than SQL text. $queryRawUnsafe takes a plain string and Prisma.raw splices text verbatim; both are safe only with trusted text, so dynamic identifiers must come from an allowlist.
solid answer
~50 sBecause `$queryRaw` is a tag function, JavaScript hands it the literal SQL fragments and the interpolated values separately; Prisma Client sends the fragments as statement text and every `${value}` as a bind parameter (`$1`, `$2` on PostgreSQL), so a hostile search term stays data. It refuses a plain string argument with a `PrismaClientValidationError`. Parameters bind values only: a column, a table or `ASC`/`DESC` cannot be a placeholder, so a user-chosen sort must come from an allowlist and be inserted with `Prisma.raw`, which splices text verbatim. `$queryRawUnsafe(sql, ...values)` accepts any string: safe with `$1` placeholders and separate values, injectable once input is concatenated or interpolated into the string. `Prisma.join` builds an `IN` list, `Prisma.sql` composes fragments and `Prisma.empty` stands for an absent clause. Results are mapped to JavaScript types, so a PostgreSQL `count(*)` arrives as a `BigInt`.
code
typescript · 23 linesimport { Prisma } from "./generated/prisma/client";
const SORT_SQL = {
rating: Prisma.raw("avg_rating"),
reviews: Prisma.raw("review_count"),
} as const;
async function topRated(categoryIds: number[], minReviews: number, sort: keyof typeof SORT_SQL, search?: string) {
if (categoryIds.length === 0) return [];
const rows = await prisma.$queryRaw<
{ id: number; name: string; avg_rating: number; review_count: bigint }[]
>`
SELECT p.id, p.name, avg(r.rating)::float8 AS avg_rating, count(r.id) AS review_count
FROM "Product" p
JOIN "Review" r ON r."productId" = p.id
WHERE p."categoryId" IN (${Prisma.join(categoryIds)})
${search ? Prisma.sql`AND p.name ILIKE ${`%${search}%`}` : Prisma.empty}
GROUP BY p.id, p.name
HAVING count(r.id) >= ${minReviews}
ORDER BY ${SORT_SQL[sort]} DESC
LIMIT 20`;
return rows.map((row) => ({ ...row, review_count: Number(row.review_count) }));
}go deeper
Recall that $queryRaw takes a template literal, that ${} values become parameters, and that the Unsafe methods take plain strings.
Explain how the tag function separates fragments from values, why identifiers cannot be bound, and how Prisma.join, Prisma.sql, Prisma.empty and Prisma.raw fit together.
Spot the unsafe shapes in review, Unsafe with interpolation and Prisma.raw around input, and handle result types such as BigInt counts before they reach an API.
Set the team's raw-SQL rules: when raw SQL is allowed, an allowlist for dynamic identifiers, and whether new typed queries go through TypedSQL.
## The four raw methods Prisma Client has four methods for SQL it cannot generate, such as a report with grouping, window functions or database-specific syntax. | Method | Accepts | Resolves to | Interpolated values become | |---|---|---|---| | `$queryRaw` | tagged template or a `Prisma.sql` object | an array of rows | bind parameters | | `$executeRaw` | tagged template or a `Prisma.sql` object | the affected-row count | bind parameters | | `$queryRawUnsafe` | any string, plus optional values | an array of rows | SQL text, unless passed as separate values | | `$executeRawUnsafe` | any string, plus optional values | the affected-row count | SQL text, unless passed as separate values | Each call runs exactly one statement, so `SELECT 1; SELECT 2` does not work. The docs recommend **TypedSQL**, a preview feature that generates typed functions from `.sql` files, for new typed raw queries; the four methods remain the general escape hatch. ## How the tagged template keeps values out of the SQL 1. JavaScript calls a tag function with two separate things: the array of literal string fragments written in source, and the evaluated `${}` values. 2. `$queryRaw` joins the fragments with placeholders in the database's dialect, `$1`, `$2` on PostgreSQL or `?` on MySQL, and sends the values as parameters of a prepared statement. 3. A search term such as `lamp'; DROP TABLE x; --` therefore travels as data and is compared as a string. Because the protection depends on the fragments coming from source code, `$queryRaw` refuses a plain string: `prisma.$queryRaw("SELECT 1")` throws a `PrismaClientValidationError` explaining that it is a tag function. A hand-built array with a `raw` property can still impersonate a template; the docs list that as an unsafe pattern. ## What a placeholder cannot do - **Identifiers and keywords.** A column, table or schema name, and `ASC` or `DESC`, cannot be parameters. `ORDER BY ${column}` binds the column name as a string value; it does not choose a column. - **Text inside SQL quotes.** A `${}` written inside a quoted SQL literal is not a placeholder. Build the whole pattern in JavaScript, for example the `%lamp%` string, and pass it as one value. - **Implicit casts.** Prisma sends JavaScript integers to PostgreSQL as `INT8` and does not add casts, so a function that expects `text` may need `${42}::text`. - **`ALTER` on PostgreSQL**, which cannot run as a prepared statement. ## The helpers on the `Prisma` namespace - `Prisma.join(ids)` expands an array into `$1,$2,$3` for an `IN (...)` list. It throws on an empty array, so handle that case before the query. - ``Prisma.sql`...` `` builds a reusable fragment whose values stay parameters; fragments nest inside a `$queryRaw` template. - `Prisma.empty` stands in for a fragment that is absent, such as an optional `AND` clause. - `Prisma.raw(text)` inserts text **verbatim**. It is the only way to place an identifier, and it is safe only when the text comes from your own allowlist. ## Where injection comes back - **`$queryRawUnsafe` with concatenation.** Building `"... WHERE name = '" + term + "'"` sends the term as SQL. The same method is safe when you write `$1` in the string and pass the value as an extra argument. - **A template literal handed to the Unsafe method.** `` $queryRawUnsafe(`... ${term}`) `` looks like `$queryRaw` but is ordinary string interpolation. - **`Prisma.raw` around input.** `${Prisma.raw(term)}` inside a template is as injectable as concatenation. Why binding beats escaping, and allowlisting as a general rule, belong to the application-security lesson on SQL injection. ## What comes back `$queryRaw` resolves to `unknown` unless you pass a type argument, and that type is a promise you make, not a check Prisma performs. Values are mapped from database types: - 64-bit integers, including PostgreSQL's `count(*)`, arrive as `BigInt`, which `JSON.stringify` cannot serialise, so convert them or cast in SQL with `::int`; - `numeric` values, such as `avg()` over integers, arrive as `Decimal`; - timestamps and dates arrive as `Date`. Unlike model queries, raw results are not normalised across databases: a boolean column reads `true`/`false` on PostgreSQL but `1`/`0` on MySQL.
- Why does JSON.stringify fail on a report row that contains a count from $queryRaw?On PostgreSQL `count(*)` is a 64-bit `bigint`, and Prisma maps 64-bit integers to JavaScript `BigInt` so no precision is lost. `JSON.stringify` throws on a `BigInt`. Convert with `Number(...)` when the value is known to be small, or cast in SQL with `count(*)::int`.
- How do you add an optional search clause without building SQL strings by hand?Interpolate a fragment chosen at runtime: a `Prisma.sql` template holding `AND p.name ILIKE` and the pattern value when a search term exists, and `Prisma.empty` otherwise. The nested `Prisma.sql` keeps the pattern a bind parameter, and `Prisma.empty` contributes nothing. An empty string or `null` would not work there, because they would be bound as values.
- Prisma escapes ${} values and splices them into the SQL text.
- You can bind a column name with ${column} in ORDER BY.
- $queryRawUnsafe is always injectable, even with $1 placeholders and separate values.
- Prisma.raw is safe because it is part of Prisma's own API.
- The type argument to $queryRaw validates the rows at runtime.