SQLite Parameterized IN Clause Safety
Build dynamic IN clauses with generated placeholders instead of string interpolation, keeping every user value bound as a statement parameter.
Code
import { DatabaseSync } from 'node:sqlite';
const db = new DatabaseSync(':memory:');
db.exec('CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT)');
db.prepare('INSERT INTO users (email) VALUES (?)').run('ada@example.com');
function findEmails(ids) {
if (ids.length === 0) return [];
if (ids.some((id) => !Number.isInteger(id))) {
throw new TypeError('ids must be integers');
}
const placeholders = ids.map(() => '?').join(', ');
const stmt = db.prepare(
'SELECT id, email FROM users WHERE id IN (' + placeholders + ')',
);
return stmt.all(...ids);
}
try {
// 恶意输入只是参数值,永远不会被解析成 SQL 语法
db.prepare('SELECT * FROM users WHERE email = ?').all("x' OR '1'='1");
} catch (err) {
console.log('injection attempt contained:', err instanceof Error);
}
const rows = findEmails([1, 2, 3]);
console.log('matched rows:', rows.length);
db.close();How it works
SQLite Parameterized IN Clause Safety keeps everything in the function findEmails.
The import names the platform contact area: DatabaseSync, all from node:sqlite. When the guard condition holds, TypeError is thrown rather than a bogus value returned.
The result is a fresh construction, so callers can keep their originals.
What to watch for
node:sqliteis a Node.js built-in module — it ships with the runtime, so there is nothing to install.- The guard
ids.length === 0short-circuits the flow with an earlyreturnwhen its condition holds.
Using it
The main signature reads function findEmails(ids)
Running the file prints labeled results such as injection attempt contained:, matched rows: — each operation’s effect is visible in the output.
Key statements
const placeholders = ids.map(() => '?').join(', ');
if (ids.some((id) => !Number.isInteger(id))) {
throw new TypeError('ids must be integers');
}
if (ids.length === 0) return [];
Interactive Tools for This Topic
URL Safety CheckerEvaluate a URL against common phishing red flags such as plain HTTP, embedded credentials, IP hosts, Punycode, and risky top-level domains.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- Does `findEmails` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- How does the snippet fail?
- It throws `TypeError` before any real work runs, via the guard `ids.length === 0` — handle it at the call site or let it propagate deliberately.
- Do I need to install anything before running this?
- Nothing needs installing: `node:sqlite` ships with Node.js itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.