1. The Anatomy of a SQL Injection (SQLi)
SQL Injection remains one of the critical security threats categorized under OWASP Top 10 vulnerabilities. It occurs when untrusted user input is directly concatenated or interpolated into a raw SQL query string instead of being treated as isolated literal data.
-- Vulnerable Raw Concatenation
SELECT * FROM users WHERE email = '' OR '1'='1' --' AND password = 'xxx';
In this classic attack vector, malicious SQL clauses modify the semantic logic of the query parser, causing the database to bypass authentication checks and expose unauthorized tables.
2. Defense in Depth: Prepared Statements & Parameterization
The only universally effective defense against SQL injection is the strict use of Parameterized Queries (Prepared Statements). Parameterization decouples the query compilation step from user data binding:
// Secure Node.js PostgreSQL Example
const text = 'SELECT id, email, role FROM users WHERE email = $1 AND active = $2';
const values = [userSuppliedEmail, true];
const res = await pool.query(text, values);
Because the database engine pre-compiles the query blueprint prior to binding parameters, malicious inputs are evaluated strictly as string literals, completely preventing semantic code execution.
3. Common Misconceptions with ORMs
While Object-Relational Mappers (Prisma, Drizzle, Hibernate) use prepared statements for standard helper methods (e.g., findUnique()), using raw bypass methods such as db.$queryRawUnsafe() or raw string template substitutions immediately reintroduces critical injection vulnerabilities if not parameterized manually.