Skip to main content

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​

Value handling​

  • sql.value(val) - Embed user values using placeholders (avoid SQLi)
  • sql.literal(val) - Embed simple values directly if safe; fall back to sql.value(val) otherwise

Common expressions​

  • sql.true - equivalent to sql`true`
  • sql.false - equivalent to sql`false`
  • sql.null - equivalent to sql`null`
  • sql.blank - equivalent to sql``

Query building​

Advanced features​

Most users won't need these, but they are available for advanced use cases:

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