postgres.js has a nice API for queries:
const users = await sql`SELECT * FROM users WHERE id = ${id}`
Values become parameters, never string concatenation, and the driver prepares and reuses the statement automatically.
I think pg can offer the same with the machinery it already has. A tagged template receives the same frozen strings array on every call from the same call site, so a WeakMap on it gives a stable statement name with no hashing. The tag only has to build { name, text, values } and pass it to query(): named statements already skip re-parsing per connection, and with #3739 the queries also pipeline through pool.query(), postgres.js style.
Open points:
- an option to skip the statement name, for pgbouncer in transaction mode?
- recovery when a schema change invalidates a prepared statement (postgres.js retries once)?
- composition (nested fragments, identifiers) can come later, values only is already useful?
I would like to work on this. Is a PR welcome, and would you prefer it in core or as a separate package?
POC
const { sql } = new Pool({ max: 2, pipeline: true });
const id = 7;
const users = await sql`SELECT * FROM users WHERE id = ${id}`;
WIP master...nigrosimone:node-postgres:sql-template-tag
postgres.js has a nice API for queries:
Values become parameters, never string concatenation, and the driver prepares and reuses the statement automatically.
I think pg can offer the same with the machinery it already has. A tagged template receives the same frozen strings array on every call from the same call site, so a
WeakMapon it gives a stable statement name with no hashing. The tag only has to build{ name, text, values }and pass it toquery(): named statements already skip re-parsing per connection, and with #3739 the queries also pipeline throughpool.query(), postgres.js style.Open points:
I would like to work on this. Is a PR welcome, and would you prefer it in core or as a separate package?
POC
WIP master...nigrosimone:node-postgres:sql-template-tag