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.

JavascriptNodeSecurity Boundaries

Code

javascriptsnippet
29 lines
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:sqlite is a Node.js built-in module — it ships with the runtime, so there is nothing to install.
  • The guard ids.length === 0 short-circuits the flow with an early return when 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

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.