Short answer: ORMs and the Supabase client protect you from SQL injection only when you use their normal query builders. You are still exposed when user input is concatenated into a string that becomes SQL or a filter: prisma.$queryRawUnsafe() with template strings, Drizzle sql.raw(), pg client.query() with string interpolation, Postgres functions that run execute 'select ... ' || input, and Supabase .or() or .filter() strings built from user input. Fix it by passing values as parameters (tagged templates or $1 placeholders), using format() with %L and %I or execute ... using inside Postgres, and allowlisting anything that cannot be a parameter, like column names and sort direction.
AI coding tools usually write safe code on the happy path. The risky code appears when you ask for "search across these fields", "sort by any column" or "a flexible filter endpoint". That is when the model reaches for raw SQL and string building. Here is where to look.
1. Prisma: $queryRaw is safe, $queryRawUnsafe is not
Prisma's tagged template turns each ${} into a bound parameter:
// Safe: email is sent as a parameter, not as SQL text
const users = await prisma.$queryRaw`
select id, email from "User" where email = ${email}
`;
The dangerous version looks almost identical:
// Vulnerable: email becomes part of the SQL string
const users = await prisma.$queryRawUnsafe(
`select id, email from "User" where email = '${email}'`
);
An attacker sends ' or '1'='1 and gets every user. The same applies to $executeRawUnsafe and to Prisma.raw(userInput) inside a tagged template, which inserts text without escaping.
If you really need $queryRawUnsafe (for example the query shape is dynamic), keep values as positional parameters:
await prisma.$queryRawUnsafe(
'select id, email from "User" where email = $1',
email
);
2. Drizzle: sql`` is safe, sql.raw() is not
import { sql } from "drizzle-orm";
// Safe: parameterized
await db.execute(sql`select * from orders where user_id = ${userId}`);
// Vulnerable: raw text
await db.execute(sql.raw(`select * from orders where user_id = '${userId}'`));
Search your codebase for sql.raw( and check that nothing user controlled reaches it.
3. node-postgres and other raw drivers
// Vulnerable
await client.query(`select * from notes where title ilike '%${q}%'`);
// Safe
await client.query("select * from notes where title ilike $1", [`%${q}%`]);
With the postgres (postgres.js) library, the tagged template sql`...${q}` is parameterized, but sql.unsafe(string) is not.
4. Things that cannot be parameters: column names and sort order
Placeholders work for values only. You cannot write order by $1. This is where generated code most often falls back to interpolation:
// Vulnerable: sort comes straight from the query string
const { sort = "created_at", dir = "desc" } = searchParams;
await prisma.$queryRawUnsafe(`select * from "Post" order by ${sort} ${dir}`);
Fix it with an allowlist so only known identifiers can ever reach the SQL:
const SORTABLE = { created: "created_at", title: "title", votes: "vote_count" } as const;
const column = SORTABLE[sort as keyof typeof SORTABLE] ?? "created_at";
const direction = dir === "asc" ? "asc" : "desc";
await prisma.$queryRawUnsafe(
`select * from "Post" where author_id = $1 order by ${column} ${direction}`,
userId
);
The interpolated parts can now only be strings you wrote. Better still, use the ORM's own orderBy option, which handles this for you.
5. Supabase: dynamic SQL inside Postgres functions
The Supabase JS client sends requests to PostgREST, which builds parameterized SQL, so normal .eq(), .ilike() and .insert() calls are not SQL injectable. The risk moves into Postgres functions you call with .rpc(). A pattern AI tools produce for "flexible search":
-- Vulnerable
create or replace function search_products(p_column text, p_term text)
returns setof products
language plpgsql
as $$
begin
return query execute
'select * from products where ' || p_column || ' ilike ''%' || p_term || '%''';
end;
$$;
Both arguments are concatenated into SQL. Fix it with format() and using, plus an allowlist for the column:
create or replace function search_products(p_column text, p_term text)
returns setof products
language plpgsql
set search_path = ''
as $$
begin
if p_column not in ('name', 'description', 'sku') then
raise exception 'invalid column';
end if;
return query execute
format('select * from public.products where %I ilike $1', p_column)
using '%' || p_term || '%';
end;
$$;
%I quotes an identifier, %L quotes a literal, and using passes values as real parameters. Never use %s with user input. In most cases you do not need dynamic SQL at all: a plain language sql function with where name ilike '%' || p_term || '%' is already safe because p_term is a bound value.
This matters even more if the function is security definer, because injected SQL then runs with the owner's privileges and bypasses RLS. See Supabase RPC and security definer functions for how to lock those down.
6. Supabase .or() and .filter() strings: filter injection
.or() takes a raw PostgREST filter string. When you build it from user input, the user can add their own conditions:
// Risky: q is inserted into the filter grammar
const { data } = await supabase
.from("posts")
.select("*")
.or(`title.ilike.%${q}%,body.ilike.%${q}%`);
A value containing commas, dots or parentheses can change the meaning of the filter, for example adding ,status.eq.draft to pull rows your UI meant to hide. This is not classic SQL injection, and RLS still applies, so it cannot read rows the user's policies forbid. But if you rely on the filter for anything security related (hiding drafts, soft deleted rows or other tenants' data when RLS is loose), it is a real hole.
Safer options:
// Strip characters that have meaning in the filter syntax
const safe = q.replace(/[,()."\\:]/g, " ").trim();
const { data } = await supabase
.from("posts")
.select("*")
.eq("status", "published") // enforced separately, not inside .or()
.or(`title.ilike.%${safe}%,body.ilike.%${safe}%`);
Or move search into a parameterized rpc() function or full text search with .textSearch(). The real fix for "users must not see this row" is always an RLS policy, as covered in the Supabase RLS checklist.
7. Search terms and LIKE wildcards
Even with parameters, a user can send % or _ to match everything. That is usually harmless for search, but if you use ilike for something like "find user by email", escape wildcards or use = on a lowercased column instead.
How to find these in your repo
Run these searches. Every hit needs a human look:
rg -n "queryRawUnsafe|executeRawUnsafe|Prisma\.raw\(" .
rg -n "sql\.raw\(|\.unsafe\(" .
rg -n "query\(\`" .
rg -n "\.or\(\`|\.filter\(\`" .
rg -n "execute '|execute format\(.*%s" supabase/
For each hit, ask: can any part of this string come from a request, a URL, a form, a webhook body or an LLM response? If yes, parameterize it or allowlist it. LLM output counts as user input; if your AI feature writes SQL or filters, treat that text as hostile (see prompt injection in AI apps).
Defense in depth
- Run app queries as a database role that cannot drop tables or read other schemas.
- On Supabase, keep RLS on for every table so a single injectable query cannot dump everything. Server code using the service role key bypasses RLS, so it needs the most careful review.
- Authenticate and authorize every API route and Server Action before it touches the database. See securing Next.js API routes and Next.js Server Actions security.
- Return generic error messages. Raw Postgres errors in responses help attackers map your schema.
Quick test
- Find every endpoint that takes a search, filter or sort parameter.
- Send a single quote (
'), then' or '1'='1, then a sort value likecreated_at; select 1. A 500 error with a Postgres syntax message means the input reached SQL text. - For Supabase
.or()searches, send a term containing a comma or parentheses, likea,b(c). A 400 "failed to parse" error from PostgREST means the input is reaching the filter syntax.
Get an automated check
PreflightPR reviews AI-built apps for raw SQL built from user input, unsafe Postgres functions, missing Supabase RLS, leaked keys and other launch blockers. Run a free scan on a public repo for a launch score and a prioritized fix list, or install the PreflightPR GitHub App to check every pull request before it merges.