SQL Injection Safe Query Builder

Build parameterized SQL queries with explicit placeholders to prevent injection while supporting dynamic WHERE and ORDER BY.

JavascriptSecurity Boundaries

Code

javascriptsnippet
1 line
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

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.