SQL Injection Safe Query Builder
Build parameterized SQL queries with explicit placeholders to prevent injection while supporting dynamic WHERE and ORDER BY.
Code
export function queryBuilder(table){let whereClauses=[],params=[],orderBy=null;function where(col,op,val){whereClauses.push(col+' '+op+' ?');params.push(val);return api;}function whereIn(col,vals){whereClauses.push(col+' IN ('+vals.map(()=>'?').join(', ')+')');params.push(...vals);return api;}function order(col,dir='ASC'){if(!['ASC','DESC'].includes(dir.toUpperCase()))throw new Error('invalid direction');orderBy='ORDER BY '+col+' '+dir.toUpperCase();return api;}const api={where,whereIn,order,build(){const w=whereClauses.length?'WHERE '+whereClauses.join(' AND '):'';return{sql:('SELECT * FROM '+table+' '+w+' '+(orderBy??'')).trim(),params};}};return api;}What the code does
The working surface is the functions queryBuilder, where, whereIn and order — everything else is wiring.
A Error is thrown unconditionally at its throw site — no input check sits in front of it.
Applying it
The main signature reads export function queryBuilder(table)
queryBuilder is the public entry point; everything else in the file exists to support it.
Interactive Tools for This Topic
SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.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.
FAQ
- What triggers the exception?
- No. The `Error` is not behind any guard — it triggers purely on reaching that line of code.
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. The file defines `queryBuilder`, `where`, `whereIn` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.