API
pg-sql2 provides a comprehensive API for building SQL queries safely and
dynamically without risking SQL injection. All functions are available as
methods on the main sql
export. It's designed for use with PostgreSQL, but
many features are applicable to other SQL databases as well.
Core functions
Template literal function
sql`...`
- The main template literal function for building SQL queries, supports embedding other SQL fragments (only! no raw values)
Compilation
sql.compile(query, options?)
- Compile SQL totext
andvalues
ready for execution
Value handling
sql.value(val)
- Embed user values using placeholders (avoid SQLi)sql.literal(val)
- Embed simple values directly if safe; fall back tosql.value(val)
otherwise
Common expressions
sql.true
- equivalent tosql`true`
sql.false
- equivalent tosql`false`
sql.null
- equivalent tosql`null`
sql.blank
- equivalent tosql``
Query building
sql.join(fragments, delimiter)
- Join multiple SQL fragments togethersql.identifier(...names)
- Create safely escaped SQL identifierssql.parens(fragment, force?)
- Add parentheses when neededsql.indent(fragment)
- Indent SQL for readabilitysql.indentIf(condition, fragment)
- Conditionally indent SQL
Advanced features
Most users won't need these, but they are available for advanced use cases:
sql.comment(text)
- Add SQL commentssql.placeholder(symbol, fallback?)
- Create replaceable placeholderssql.withTransformer(transformer, callback)
- Allow non-SQL values to be interpolatedsql.isSQL(value)
- Check if a value is a SQL fragmentsql.isEquivalent(sql1, sql2, options?)
- Compare SQL fragments for equivalencesql.symbolAlias(symbol1, symbol2)
- Create symbol aliases (e.g. when merging fragments)sql.replaceSymbol(fragment, needle, replacement)
- Replace symbols in SQL fragments
Escape hatch
HIGHLY DISCOURAGED
This method bypasses all SQL injection protections. There are almost always
better solutions. If you use sql.raw
you're defeating the purpose of the
library and opening yourself up to SQL injection vulnerabilities.
EXTREME CAUTION ADVISED.
sql.raw(text)
- ⚠️ DANGER ⚠️ Embed raw, dynamic, SQL text