Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Compose nested sql`` fragments in the Neon db wrapper

nirholasf26612d9e88b
diff --git a/api/_lib/db.js b/api/_lib/db.js
index e92be2597..9365e1818 100644
--- a/api/_lib/db.js
+++ b/api/_lib/db.js
@@ -1,5 +1,20 @@
// Neon serverless Postgres. HTTP-based, works in edge + node runtimes.
// Use `sql` as a tagged template for queries: sql`SELECT … WHERE id = ${id}`.
+//
+// Fragment composition
+// --------------------
+// The raw `@neondatabase/serverless` tagged template does NOT compose: if you
+// interpolate the result of another `sql`…`` call into a query it binds that
+// object as a positional parameter, emitting invalid SQL like `… 2) $3 $4 …`
+// (Postgres: `syntax error at or near "$3"`). Several endpoints rely on the
+// natural pattern of building conditional `sql`…`` fragments and splicing them
+// into a parent query (dynamic WHERE clauses, `reduce`-built UPDATE SET lists),
+// so this wrapper makes that pattern correct: an interpolated fragment is
+// flattened inline and its placeholders are renumbered against the parent. A
+// fragment stays fully compatible with `sql.transaction([...])` (it carries the
+// `NeonQueryPromise` tag plus a prepared `parameterizedQuery`/`opts`) and is a
+// thenable, so `await`, `.catch`, `.finally`, and `Promise.all` all behave
+// exactly as before for non-fragment queries.
import { neon } from '@neondatabase/serverless';
import { env } from './env.js';
@@ -20,25 +35,83 @@ function getSql() {
// from corrupt/garbage input, never legitimately, so we strip them from every
// string-typed query parameter at this single boundary rather than dotting
// per-endpoint sanitizers around the codebase. Non-string params (numbers,
-// booleans, Buffers/bytea, null, jsonb objects) pass through untouched; the
-// template-strings array (args[0]) is never modified.
-function stripNulParams(args) {
- if (args.length < 2) return args;
- let mutated = false;
- const out = args.map((v, i) => {
- if (i === 0) return v; // template strings array — leave intact
- if (typeof v === 'string' && v.includes('\u0000')) {
- mutated = true;
- return v.replace(/\u0000/g, '');
+// booleans, Buffers/bytea, null, jsonb objects) pass through untouched.
+function stripNul(v) {
+ return typeof v === 'string' && v.includes('\u0000') ? v.replace(/\u0000/g, '') : v;
+}
+
+// Brand identifying a composable fragment produced by this wrapper.
+const FRAGMENT = Symbol('neonSqlFragment');
+
+function isFragment(v) {
+ return v != null && typeof v === 'object' && v[FRAGMENT] === true;
+}
+
+// Flatten a tagged-template (strings + interpolated values) into a single
+// parameterized query. Nested fragments are spliced inline — their own values
+// are recursively appended and every placeholder is renumbered against the
+// flattened param list. Non-fragment values become `$N` placeholders. NULs are
+// stripped from string params here, before Neon's `prepareValue` runs.
+function composeFragment(strings, values) {
+ let query = '';
+ const params = [];
+ const walk = (strs, vals) => {
+ for (let i = 0; i < strs.length; i++) {
+ query += strs[i];
+ if (i < vals.length) {
+ const v = vals[i];
+ if (isFragment(v)) {
+ walk(v.strings, v.values);
+ } else {
+ params.push(stripNul(v));
+ query += '$' + params.length;
+ }
+ }
}
- return v;
- });
- return mutated ? out : args;
+ };
+ walk(strings, values);
+ return { query, params };
+}
+
+// A fragment is a lazy, composable stand-in for a NeonQueryPromise. It holds the
+// raw template pieces so a parent query can splice it, and only builds the
+// underlying Neon query (via the function form, which prepares params and stays
+// lazy until awaited) the first time it is executed, inspected for its
+// `parameterizedQuery`, or read for `opts` — i.e. when used standalone or inside
+// `sql.transaction([...])`.
+function makeFragment(strings, values) {
+ let native;
+ const toNative = () => {
+ if (!native) {
+ const { query, params } = composeFragment(strings, values);
+ native = getSql()(query, params);
+ }
+ return native;
+ };
+ return {
+ [FRAGMENT]: true,
+ [Symbol.toStringTag]: 'NeonQueryPromise',
+ strings,
+ values,
+ get parameterizedQuery() { return toNative().parameterizedQuery; },
+ get opts() { return toNative().opts; },
+ then(onFulfilled, onRejected) { return toNative().then(onFulfilled, onRejected); },
+ catch(onRejected) { return toNative().catch(onRejected); },
+ finally(onFinally) { return toNative().finally(onFinally); },
+ };
}
export const sql = new Proxy(function () {}, {
apply(_t, _this, args) {
- return getSql()(...stripNulParams(args));
+ // Neon dispatches on the first argument: a string is the ordinary
+ // function form `sql(queryText, params, opts)`; anything else is a
+ // tagged-template call where the first arg is the strings array.
+ if (typeof args[0] === 'string') {
+ const [queryText, params, opts] = args;
+ const safeParams = Array.isArray(params) ? params.map(stripNul) : params;
+ return getSql()(queryText, safeParams, opts);
+ }
+ return makeFragment(args[0], args.slice(1));
},
get(_t, prop) {
return getSql()[prop];
diff --git a/tests/db-sql-compose.test.js b/tests/db-sql-compose.test.js
new file mode 100644
index 000000000..e1aee31d4
--- /dev/null
+++ b/tests/db-sql-compose.test.js
@@ -0,0 +1,108 @@
+// Unit tests for the composable `sql` wrapper in api/_lib/db.js.
+//
+// The raw @neondatabase/serverless tagged template does NOT compose nested
+// fragments — interpolating one `sql`…`` result into another binds it as a
+// positional parameter and emits invalid SQL (`… 2) $3 $4 …` → Postgres
+// `syntax error at or near "$3"`). Our wrapper flattens fragments inline and
+// renumbers placeholders. These tests assert the generated `parameterizedQuery`
+// without touching a database — DATABASE_URL only needs to be a syntactically
+// valid connection string so neon() can instantiate lazily.
+
+import { describe, it, expect, beforeAll } from 'vitest';
+
+let sql;
+beforeAll(async () => {
+ process.env.DATABASE_URL = process.env.DATABASE_URL || 'postgresql://u:p@localhost/db';
+ ({ sql } = await import('../api/_lib/db.js'));
+});
+
+describe('sql fragment composition', () => {
+ it('builds a plain parameterized query with no fragments', () => {
+ expect(sql`select * from t where id = ${5}`.parameterizedQuery).toEqual({
+ query: 'select * from t where id = $1',
+ params: ['5'],
+ });
+ });
+
+ it('splices conditional WHERE fragments and renumbers placeholders (oracle/wins pattern)', () => {
+ const tier = 'prime';
+ const days = 30;
+ const before = null;
+ const tierFilter = tier !== 'all' ? sql`and c.tier = ${tier}` : sql``;
+ const periodFilter =
+ days != null ? sql`and c.scored_at >= now() - (${days} || ' days')::interval` : sql``;
+ const beforeFilter = before ? sql`and c.scored_at < ${before}::timestamptz` : sql``;
+
+ const { query, params } = sql`
+ select * from oracle_conviction c
+ where c.network = ${'mainnet'}
+ and o.ath_multiple >= ${2}
+ ${tierFilter}
+ ${periodFilter}
+ ${beforeFilter}
+ limit ${50}
+ `.parameterizedQuery;
+
+ // Every placeholder is sequential and contiguous — no bare `$N` gaps.
+ expect(params).toEqual(['mainnet', '2', 'prime', '30', '50']);
+ expect(query).toContain('c.network = $1');
+ expect(query).toContain('o.ath_multiple >= $2');
+ expect(query).toContain('c.tier = $3');
+ expect(query).toContain("($4 || ' days')::interval");
+ expect(query).toContain('limit $5');
+ // The empty `beforeFilter` contributes nothing.
+ expect(query).not.toContain('$6');
+ });
+
+ it('drops empty fragments entirely', () => {
+ expect(sql`select 1 ${sql``} ${sql``}`.parameterizedQuery).toEqual({
+ query: 'select 1 ',
+ params: [],
+ });
+ });
+
+ it('composes a reduce-built SET clause with deep nesting (mocap/animations PATCH pattern)', () => {
+ const sets = [
+ sql`avatar_id = ${'av1'}`,
+ sql`price_amount = ${100}`,
+ sql`price_currency = ${'USDC'}`,
+ ];
+ const setClause = sets.reduce(
+ (acc, s, i) => (i === 0 ? sql`set ${s}` : sql`${acc}, ${s}`),
+ sql``
+ );
+ expect(sql`update t ${setClause} where id = ${'x'} returning *`.parameterizedQuery).toEqual({
+ query: 'update t set avatar_id = $1, price_amount = $2, price_currency = $3 where id = $4 returning *',
+ params: ['av1', '100', 'USDC', 'x'],
+ });
+ });
+
+ it('keeps fragments compatible with sql.transaction([...])', () => {
+ const f = sql`insert into t(a) values (${1})`;
+ // Neon's transaction() rejects anything whose toStringTag !== 'NeonQueryPromise'.
+ expect(Object.prototype.toString.call(f)).toBe('[object NeonQueryPromise]');
+ expect(f.parameterizedQuery).toEqual({ query: 'insert into t(a) values ($1)', params: ['1'] });
+ expect(f.opts).toBeUndefined();
+ });
+
+ it('exposes thenable methods so await/.catch/.finally still work', () => {
+ const f = sql`select 1`;
+ expect(typeof f.then).toBe('function');
+ expect(typeof f.catch).toBe('function');
+ expect(typeof f.finally).toBe('function');
+ });
+
+ it('strips NUL bytes from string params at the boundary', () => {
+ expect(sql`select ${'a\u0000b'}`.parameterizedQuery).toEqual({
+ query: 'select $1',
+ params: ['ab'],
+ });
+ });
+
+ it('passes ordinary function-form calls straight through', () => {
+ expect(sql('select $1::int', [7]).parameterizedQuery).toEqual({
+ query: 'select $1::int',
+ params: ['7'],
+ });
+ });
+});