How to Refactor to Parameterized Queries
Replace string concatenation with driver placeholders, whitelist the identifiers placeholders cannot carry, and find legacy code by scanning.
On this page
Introduction
SQL injection is the vulnerability that refuses to die, not because it is subtle but because the vulnerable code shape, SQL text assembled from strings with user-controlled pieces, is also the natural shape of quick feature work. A query built as a string with an id interpolated works, passes tests, and celebrates launch, and the attack is one quote character away: the input rewrites the SQL, and the database cannot tell the intended statement from the delivered one. Parameterization eliminates the class rather than patching instances: values travel in a separate channel from SQL text, the driver encodes them as data, and no input can change the statement structure. The refactor from concatenation to parameters is mechanical for the common case and needs known patterns for the three genuine exceptions, identifiers, IN lists, and sort clauses. This tutorial finds the concatenation sites, converts them, handles the exceptions with whitelists and expansion, and locks the refactor with adversarial tests and CI scanning so the vulnerability cannot quietly re-enter through the next deadline.
Why concatenation fails
The failure is structural: concatenation puts data and code in one channel, and the boundary between them exists only in the programmer’s intent. The classic payload closing a string and appending a tautology, an OR chain that is always true, defeats the intended filter; the statement-append payload, closing the statement and opening a second one, reaches DROP and UPDATE; the second-order variant stores a payload today and detonates it when a later query concatenates the stored value. Escaping attempts to restore the boundary by neutralizing quote characters, and fails for the reasons escaping always fails: dialect-specific rules, quote and encoding edge cases, multi-byte character tricks, and the maintenance reality that the rules live in a helper someone will bypass under pressure. Parameterization moves the boundary into the driver protocol: the statement text is transmitted once, fully formed, and the values are transmitted as typed data afterward, so the parser has already committed to the statement shape before any value arrives. The database engine is structurally unable to reinterpret data as SQL, which is why every serious guidance ranks parameterized queries as the primary defense and everything else as secondary.
Convert the common case
The common case is a query with interpolated values, and the conversion moves each value into a placeholder, numbered in PostgreSQL, positional question marks in MySQL and SQLite, and positional in most drivers.
# before: the boundary lives in hope
query = "SELECT id, email FROM users WHERE tenant = '%s' AND email = '%s'" % (tenant, email)
cur.execute(query)
# after: the boundary lives in the protocol
cur.execute(
"SELECT id, email FROM users WHERE tenant = %s AND email = %s",
(tenant, email),
)
Two refactor details matter more than they look. The SQL text is now a constant, which means the database can cache the prepared plan, so the security refactor buys a performance win for free, plans prepared once and executed many times. And the values keep their types: a number parameter is transmitted as a number, not as its string rendering, so the query also stops misbehaving on locale-formatting and quoting edge cases. The TypeScript equivalent with a typical driver passes the values as an array beside the constant statement text, db.query('SELECT ... WHERE id = $1', [id]), and the same two details hold in every stack.
The three exceptions
Three query pieces cannot be parameters, because the protocol binds values, not parts of the statement, and each has a known safe pattern. Identifiers, table and column names chosen per request: whitelist against the known schema, a closed map from allowed request values to real column names, and reject anything else; quoting identifiers is a defense layer, not a substitute, because identifier quoting has its own dialect rules.
const SORTABLE: Record<string, string> = {
created: 'created_at',
name: 'display_name',
revenue: 'revenue_cents',
};
export function orderBy(userInput: string): string {
const column = SORTABLE[userInput];
if (!column) throw new InvalidSortError(userInput);
return column;
}
Dynamic IN lists: expand the list into placeholders computed from its length, WHERE id IN ($1, $2, $3) built from the count, values still bound as parameters, or use the driver’s array binding, PostgreSQL’s = ANY($1) with an array parameter, which is cleaner. Sort direction: ASC and DESC are statement text, so they come from a two-value whitelist, never from the request string even after validation. Each exception pattern shares one property: the set of possible statement texts is finite and known before any request arrives, which is exactly the property concatenation destroyed.
Find the legacy sites
The refactor needs an inventory, and the sites hide in patterns rather than in obvious places. The greppable shapes: string concatenation around SQL keywords, plus-appends near SELECT and WHERE; formatting calls, sprintf, String.format, f-strings, template literals, with SQL fragments; and query builders invoked with raw fragments, ORM escape hatches like raw query methods or unsafe escape calls. The greppable pass finds the majority, and the review pass finds the rest: dynamic ORDER BY construction, filter lists assembled per checkbox, migration scripts interpolating identifiers, and stored procedure calls built as strings. Prioritize by input reachability: a concatenated query fed only by constants is a latent bug rather than an active one, while anything touching request parameters, headers, or stored user data is the live surface. The inventory becomes the refactor backlog with the live-surface items first, and the CI scanner in the next section keeps the backlog from regrowing behind it.
Prove the refactor adversarially
Conversion is only trustworthy under attack, so each refactored query gets an adversarial test with canonical payloads: the quote-tautology closing a literal with an always-true OR chain, the statement-append with a comment terminator, the union probe appending a second SELECT, and the delayed-execution shape, a value stored now and concatenated later, which tests the second-order path end to end. The assertions are behavioral: the payload arrives as data, the query returns the empty or error result that literal data would produce, and the statement shape is unchanged, observable in query logs as one constant text with bound parameters.
it('treats injection payloads as literal data', async () => {
const evil = "' OR '1'='1";
const found = await users.findByEmail(evil);
expect(found).toBeNull(); // no tautology match
expect(queryLog.lastText()).toBe(USERS_BY_EMAIL_SQL); // constant shape
});
The whitelist exceptions get their own cases: an unlisted sort column is rejected with a validation error, not silently passed; an IN list of length zero and length one hundred both produce correct placeholder counts; and the sort direction accepts exactly the two whitelisted words. The suite runs in CI on every change to query code, and its presence is the difference between a refactor that held and one that decayed.
Lock it with CI scanning
The refactor decays unless returning to concatenation fails a build, so a scanner belongs in CI with a low tolerance. The mechanical options: a grep pass over the codebase for the concatenation shapes near SQL keywords, allowlisting the exceptions file by file with a documented reason; a lint rule where the ecosystem offers one, several SQL linting plugins flag string-built queries; or static analysis with taint tracking, which flags flows from request inputs into query construction and is the strongest signal with the most setup cost. The scanner’s policy is the important part: new concatenation fails the build, existing documented exceptions carry a reason and an owner, and the exception list is expected to shrink, not grow. Combine the scanner with the test suite’s behavioral assertions, and the two defenses cover each other’s blind spots: the scanner catches code the tests never exercised, and the tests catch semantic holes, a whitelisted column that should not have been whitelisted, that no text pattern can see.
Common pitfalls
- **Escaping instead of binding. ** Hand-rolled quoting fails on dialects, encodings, and the maintainer who forgets the rules; the driver’s parameter binding is the code whose only job is this.
- **Whitelisting by validation string. ** Matching the request against a regex still passes attacker-chosen identifiers; map through a closed dictionary to real names.
- **ORM escape hatches forgotten. ** Raw query methods re-open the hole the ORM closed, and refactors that skip them feel complete and are not.
- **Second-order injection missed. ** Stored payloads detonate in later concatenation; test the store-then-query path, not just the entry point.
- **One-off fixes without scanning. ** Patched instances regrow under deadline; CI scanning is what makes the refactor permanent.
- **Dynamic SQL in migrations. ** Scripts that interpolate identifiers inherit every problem at deploy time and deserve the same patterns.
Conclusion
SQL injection survives because its vulnerable shape is convenient, and the permanent answer is making the safe shape equally convenient. Convert value interpolation to driver placeholders, which keeps SQL text constant, data typed, plans cached, and injection structurally impossible. Handle the three genuine exceptions with their known patterns, identifier whitelists against the real schema, placeholder expansion or array binding for IN lists, two-value whitelists for sort direction, so every request still maps into a finite set of known statements. Find the legacy sites by grepping the concatenation shapes and reviewing the escape hatches, prove each conversion with adversarial payloads asserting literal treatment, and lock the result with CI scanning that fails new concatenation on sight. The refactor is mechanical, mostly an afternoon per module, and it deletes an entire vulnerability class rather than chasing its instances.
Sources: OWASP: SQL injection prevention cheat sheet, PostgreSQL: PREPARE, MDN: SQL injection glossary.
FAQ
- Can parameterization break some queries?
- Yes, three cases: identifiers, table and column names, which cannot be placeholders; dynamic IN lists, which need array expansion; and sort directions, which need whitelisting. Each has a known safe pattern, and none justify concatenation.
- Is escaping values by hand acceptable?
- No. Hand-rolled escaping fails on encoding mismatches, database-specific syntax, and the next maintainer who forgets the rules. Parameterization delegates the problem to code whose only job is solving it correctly.
- Does an ORM make this moot?
- ORMs parameterize their own generated queries, which covers the common path. Raw query escapes, string-built fragments, and dynamic ordering still inject, and the refactor targets exactly those seams.
Report a problem with this articleOpens a pre-filled issue on GitHub.