@triptease/sql-template
v0.37.8
Published
This is yet another SQL tagged template for Typescript/Javascript
Readme
Sql Template
This is yet another SQL tagged template for Typescript/Javascript
Why another library?
- Typescript first
- Functional/Immutable
- Super simple implementation (see SQL.ts)
- Full escaping of identifiers and values
- Plugable to any DB (currently Postgres via
@triptease/sql-template-postgreswithpg) - Automatic support for prepareStatement naming (Postgres)
Installation
npm install @triptease/sql-template @triptease/sql-template-postgres
# or
bun add @triptease/sql-template @triptease/sql-template-postgresBoth packages are plain ESM JavaScript with type declarations, so they work in Node and Bun.
@triptease/sql-template has no dependencies and @triptease/sql-template-postgres depends only on it
(it does not depend on pg; bring your own driver). In Node they can also be loaded with require()
(Node 20.19+/22.12+, which can require() ES modules).
Usage
Node with pg
import pg from "pg";
import {SQL, id, values} from "@triptease/sql-template";
import {statement, prepareStatement} from "@triptease/sql-template-postgres";
const pool = new pg.Pool();
const table = 'users', name = "O'Brien";
await pool.query(statement(SQL`select * from ${id(table)} where name = ${name}`));
// { text: 'select * from "users" where name = $1', values: ["O'Brien"] }
// named prepared statement (the name defaults to a hash of the SQL)
await pool.query(prepareStatement(SQL`select * from users where id in (${values([1, 2, 3])})`));
// { name: 'feb13b21…', text: 'select * from users where id in ($1, $2, $3)', values: [1, 2, 3] }Bun
If you only target Bun, its built-in sql tagged template already binds values
and escapes identifiers, so you probably don't need this library. Use it in Bun when your query code also has to
run on Node with pg, or when you want queries as plain immutable values you can build, test and log
(debugQuery) without a connection.
Composing
import {SQL, id, ids, text, values} from "@triptease/sql-template";
// templates nest, and values() can join them with an explicit (raw) separator
const filters = [SQL`${id('name')} = ${name}`, SQL`${id('age')} > ${30}`];
const query = SQL`select ${ids(['id', 'name'])} from users where ${values(filters, text(' and '))}`;
// select "id", "name" from users where "name" = $1 and "age" > $2Templates are immutable (frozen) and flat. Expressions are identified by a Symbol.for brand rather than
instanceof, so templates built by a different copy of @triptease/sql-template (e.g. two installed
versions) still work, while plain data (such as parsed JSON) can never be mistaken for SQL.
Cheatsheet
Core (@triptease/sql-template)
| function | Description |
|------------------------------------------------|---------------------------------------------------------------------------------------------|
| SQL | The main function to create tagged templates for SQL (DB agnostic) |
| text (alias raw) | Input raw SQL without any escaping (use with care) |
| id / ids(names, separator?) | Input dynamic identifiers into SQL (escaped as needed) |
| value (optional) / values(list, separator?) (alias spread) | Input one or more values into SQL (bound as parameters) |
| template | Combine expressions into a (flattened, frozen) template |
| isExpression / isText / isIdentifier / isValue / isTemplate / kindOf | Type guards based on the expression brand (for adapters) |
separator is an Expression and defaults to text(', ').
Postgres (@triptease/sql-template-postgres)
| function | Description |
|------------------------------------------------|----------------------------------------------------------------------|
| statement | Converts DB agnostic SQL template into a postgres statement (pg) |
| prepareStatement | Converts DB agnostic SQL template into a named prepared statement (pg) |
| escapeIdentifier / escapeLiteral | Postgres identifier and string literal escaping (ported from pg) |
| debugQuery | Renders a template with values inlined, for debugging (see below) |
use with care -> Used incorrectly you can open yourself up to SQL injection
debugQuery escapes every value (strings, numbers, booleans, null, Dates, Buffers, arrays and objects), but
it is meant for logging: execute queries with statement/prepareStatement so values are bound as
parameters. Inlined literals are not always typed the way parameters are (e.g. arrays become array literal
strings and objects JSON strings, which need a cast in some contexts). Dates are inlined as UTC ISO strings, so for
timestamp (without time zone) or text targets the output only matches what pg executes when the process runs
with TZ=UTC.
Breaking changes (since the pg-only releases)
- The
separatorofvalues/spread/idsis now an Expression: replacevalues(xs, ' or ')withvalues(xs, text(' or ')). Passing a string throws aTypeError(it used to be inserted as raw SQL). @triptease/sql-template-postgresno longer depends onpg; itsQueryConfigis a local type that is structurally compatible with pg's.- Adapters throw on expressions they do not understand instead of silently dropping them, and SQL with an
invalid escape sequence (e.g.
SQL`\u`) throws instead of producing the textundefined. - Public types use
unknowninstead ofany;idstakesstring[]. - The packages are ESM only (they used to be CommonJS):
require()needs Node 20.19+/22.12+ (older Node versions can onlyimportthem).- TypeScript consumers need
"module"/"moduleResolution"set tonodenext(ornode20) orbundler. A CommonJS project usingnode16(ornodenextbefore TypeScript 5.8) gets error TS1479; switch to one of those settings or load the packages withimport(). - Only the package roots are exported: deep imports such as
@triptease/sql-template/Textfail withERR_PACKAGE_PATH_NOT_EXPORTED. Import everything from@triptease/sql-template/@triptease/sql-template-postgres.
Expressionis abstract and subclassing it is not supported: an instance of your own subclass is rejected with aTypeError(composeSQL/text/id/value/templateinstead).debugQueryoutput changed:null/undefinedrender asNULL, booleans asTRUE/FALSE, negative numbers are parenthesised,NaN/Infinityare quoted, and Dates, Buffers, arrays and objects are rendered as escaped literals. Do not parse or compare its output.- A
Templatebuilt directly withnew Template([...])now keeps the values of nested templates (they used to be dropped).
Extending
It is simple to extend to other DBs: switch on kindOf(expression) ('text', 'identifier', 'value',
'template') and throw on anything else. Have a look at the
postgres implementation.
Development
Tool versions (node, bun) are pinned in mise.toml. Install mise, then:
mise install # installs the pinned node and bun
./run # install deps, clean, build (tsc --build), typecheck and test (bun test)The repo is a bun workspace: each package has a published src/package.json (runtime dependencies only)
and a private test/package.json (test dependencies). Tests import the packages by name.
The postgres integration tests (sql-template-postgres/test/integration.test.ts) run real queries through
pg. They need a database:
DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres ./runWithout DATABASE_URL they are skipped locally (with a warning) but fail when CI=true; the GitHub Actions
test job provides a postgres:18 service.
Releasing
Every push to triptease/sql-template that passes the test job runs the publish job in
.github/workflows/build.yml, which runs scripts/release.ts:
- Version:
0.<git rev-list --count HEAD>.<GITHUB_RUN_NUMBER>; dist-taglatestonmaster,devon other branches. - It does a clean
tsc --build(without declaration maps, as the.tssources are not published), then writes<pkg>/dist/package.jsonfrom<pkg>/src/package.json(version stamped,workspace:*replaced by that version,main/types/exportspointing at the.js/.d.tsfiles, explicitfiles) and copies this README next to it. Thedistdirectory is what gets published, so import paths never containsrc/ordist/. It fails if anyworkspace:range is left. - It publishes core first, then postgres, with
npm publish <pkg>/dist:- to GitHub Packages (
npm.pkg.github.com) on every run, using the workflow'sGITHUB_TOKEN; - to npmjs only when the repo variable
NPM_PUBLISHistrue, with--access public --provenance, authenticated by npm Trusted Publishing (OIDC).
- to GitHub Packages (
- Versions that are already on a registry are skipped, so a failed run can simply be re-run.
- The staged
distdirectories are kept as thedistartifact of the workflow run.
Check what would be published without uploading anything (npm publish --dry-run; add NPM_PUBLISH=true
to include npmjs):
./run release --dry-run./run ci runs the full build and tests, then the release script.
One-off setup (needs an npm org admin and a GitHub repo admin)
- On npmjs.com, for each of
@triptease/sql-templateand@triptease/sql-template-postgres: Settings → Trusted Publisher → GitHub Actions, organizationtriptease, repositorysql-template, workflow filenamebuild.yml, environment empty, allowed actions:npm publishonly. The workflow filename is part of the trust relationship, so do not renamebuild.yml. Publishing access is set to "require two-factor authentication and disallow tokens", so only this workflow can publish. - In the GitHub repo, set the Actions variable
NPM_PUBLISHtotrue(Settings → Secrets and variables → Actions → Variables). Until then npmjs publishing is skipped and only GitHub Packages is published. - GitHub Packages: after the first publish, check both packages under the org's Packages page, make sure they are linked to this repository and set their visibility to public if they should be visible outside the org.
Installing from GitHub Packages
npmjs is the main channel. Installing from GitHub Packages needs authentication even for public packages:
a token with read:packages and an .npmrc like
@triptease:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}