AleannLab

SQL Injection in AI-Generated Code: It Is Still Here

AleannLab team2 min read

SQL injection happens when user input becomes part of the query text instead of a value passed alongside it. ORMs and query builders prevent it in normal use, so the bug survives in the exceptions: raw queries built with template strings, dynamic ORDER BY and column names, search filters, and database functions that assemble SQL with string concatenation. Pass values as parameters, and choose identifiers from an allowlist.

On this page
  1. Where it hides in modern stacks
  2. Find it
  3. Fix it
  4. Reduce the blast radius

The classic example still gets generated when a prompt says "add search":

TypeScript
const rows = await db.query(
  `SELECT * FROM products WHERE name LIKE '%${req.query.q}%'`
);

Search for ' UNION SELECT email, password_hash, null FROM users -- and the product list returns your users table.

Where it hides in modern stacks

Raw query escape hatches. Prisma's tagged template is safe; the "unsafe" variant with interpolation is not:

TypeScript
// safe: values are sent as parameters
await prisma.$queryRaw`SELECT * FROM products WHERE name ILIKE ${'%' + q + '%'}`;

// injectable: the string is built first
await prisma.$queryRawUnsafe(`SELECT * FROM products WHERE name ILIKE '%${q}%'`);

The same split exists in Drizzle (sql template versus sql.raw), Knex (whereRaw with bindings versus without) and every driver.

Sorting and column names. Parameters work for values, not for identifiers. So code like this appears:

TypeScript
const rows = await db.query(`SELECT * FROM orders ORDER BY ${req.query.sort} ${req.query.dir}`);

Database functions. In Postgres and Supabase, dynamic SQL inside a function is injectable too:

SQL
-- injectable
execute 'select * from ' || table_name || ' where owner = ''' || owner || '''';

If that function is security definer and callable over RPC, the injection runs with the owner's rights. See can anyone call your Supabase functions?.

Filters passed through. PostgREST-style filter strings assembled from user input (for example a .or() string built with interpolation) can be manipulated to add conditions you did not intend.

Find it

bash
grep -rnE "queryRawUnsafe|executeRawUnsafe|sql\.raw|whereRaw|\.query\(\s*\`|execute\s+'|format\(" \
  app src lib supabase --include=*.ts --include=*.js --include=*.sql

Then look for template strings that contain both SQL keywords and ${:

bash
grep -rnE "\`[^\`]*(SELECT|INSERT|UPDATE|DELETE)[^\`]*\\$\{" app src lib --include=*.ts --include=*.js

To test from outside, put a single quote ' into search boxes, filters, sort parameters and IDs. A 500 error or a database error message where a normal value works is the signal to look at that query. On a test environment, sqlmap automates the rest.

Fix it

Values: always parameters.

TypeScript
await db.query('SELECT * FROM products WHERE name ILIKE $1', [`%${q}%`]);

Identifiers: allowlist.

TypeScript
const SORTABLE = { created: 'created_at', total: 'total_cents', status: 'status' } as const;
const column = SORTABLE[req.query.sort as keyof typeof SORTABLE] ?? 'created_at';
const dir = req.query.dir === 'asc' ? 'ASC' : 'DESC';

await db.query(`SELECT * FROM orders WHERE user_id = $1 ORDER BY ${column} ${dir}`, [userId]);

The user picks a key. Your code picks the SQL.

Dynamic SQL in Postgres: format with %I and %L, or using.

SQL
execute format('select * from %I where owner = $1', table_name) using owner;

%I quotes an identifier, %L quotes a literal, and using passes real parameters.

Validate types early. An ID that must be a UUID or an integer should be parsed as one before it gets near a query.

Reduce the blast radius

  • The application's database user should not own the schema or be a superuser. Injection with a read-only role on three tables is a smaller incident.
  • Do not return database error text to clients. It tells an attacker exactly what to try next. See exposed .env files and debug endpoints.
  • Row Level Security helps when queries run as the end user, as with Supabase. It does nothing for a server connection that bypasses it.

String-built SQL is check 9 in our security checklist for vibe-coded apps. If you want your queries and database functions reviewed and fixed, that is part of our app rescue and security audit.

All articles →

Ready to discuss your project with us?

idea
*
*
*
I'm interested in...
Web Development
App Development
UX/UI Design
DevOps
Artificial Intelligence And Machine Learning
QA Testing
Mobile Development
Consultation
OutSource
Project budget (USD)
≤ $5K
$10K-$20K
$30K-$40K
$50K-$60K
>$100K
Upload file