durcno@1.0.0-alpha.33
Patch Changes
-
338b904 - Thanks to @almahdi404 !
fix(cli): fix cli version lagging one release behind
Fix an issue where the CLI version reported by the published package was always one version behind the release.
Previously, the CI workflow built the package before running the versioning step. Because the build script inlines the
versionfield frompackage.jsoninto the bundled CLI viaprocess.env.VERSION, the distributed CLI binary retained the pre-bump version rather than the newly published release version.The build step is now configured via
cngpac.config.ts(build.script: "build"), ensuring the package is built after the version bump and before publishing. In addition, the unbundled fallback version insrc/cli/index.tswas updated from"1.0.0"to"0.0.0". -
87d7e98 - Thanks to @almahdi404 !
fix(db): release the pooled connection when a transaction ROLLBACK fails
Fix a resource leak in
db.transaction()that permanently exhausted the connection pool after repeated failures.Every transaction acquires a dedicated client from the pool. When the transaction body threw, the error path rolled back and released that client — but if the
ROLLBACKitself failed, which it does on an aborted or already-dead connection,client.close()was never reached and the pool slot was lost. Afterpool.maxsuch failures (5 by default) every subsequent query waited forever for a connection that would never come back.The client is now released from a
finallyblock, so it is returned to the pool exactly once on every path, and a failingROLLBACKis reported through the configured logger instead of replacing the error that caused the transaction to fail:try {await db.transaction(async (tx) => {await tx.insertInto(Users).values({ name: "John Doe" });throw new Error("Intentional failure");});} catch (error) {// Still the "Intentional failure" error, and the connection is back in the pool.console.error(error);}In addition,
durcno/loggernow exportscreateLoggeras its primary factory function (withcreateQueryLoggerandcreateDurcnoLoggerpreserved as aliases), andLogMetadatagroups query execution telemetry (sql,arguments,durationMs) into a strongly-typedquery: QueryLogDataobject, cleanly separating query events from database lifecycle errors. -
c0f7c1e - Thanks to @almahdi404 !
fix(filters): cast array values in comparisons to the column type
Comparing an array column with an array value failed with a PostgreSQL error:
ERROR: operator does not exist: character varying[] = text[]PostgreSQL types every
ARRAY[...]literal it parses astext[], and a comparison has no target column to coerce it — unlikeINSERT, where the target column supplies the type. The write path already emitted the cast, but the read paths did not.Array values rendered on the value side of a comparison are now cast to the column's array type, via the new
Column.toSQLExpression:SELECT * FROM "items" WHERE "items"."tags" = ARRAY['a', 'b']::varchar(100)[]This covers
eq/ne/gt/lt/gte/lte,isIn/notInwith array values, and array operands of SQL functions such ascoalesce/greatest/caseWhen. The existing array filters (arrayContains,arrayContainedBy,arrayOverlaps) now go through the same helper and emit identical SQL.Scalar filter values are untouched — a string literal is
unknownand PostgreSQL resolves it from the other side of the comparison, soeq(Users.name, "a")still emits"users"."name" = 'a'. Index usage is unaffected: the cast is on the value side of the operator and is folded into a constant at plan time, so a btree/GIN index on the array column is still selected. -
ee21108 - Thanks to @almahdi404 !
fix(columns): validate numeric values before serializing them to SQL
A
numericcolumn was interpolated into SQL without validation, so a non-numeric value produced broken statements instead of an error:db.from(Products).select("*").where(() => eq(Products.price, "abc"));-- beforeSELECT * FROM "public"."products" WHERE "products"."price" = abc-- ERROR: column "abc" does not existValues are now checked against the PostgreSQL
numericliteral grammar (optional sign, digits, optional fraction, optional exponent) before being serialized, and an invalid value throws immediately — matching howuuidalready reports bad input:db.from(Products).select("*").where(() => eq(Products.price, "abc"));// Error: Invalid numeric value: abcThe check rejects more than the previous
Number()-based one could:"","0x27","1_000","NaN","Infinity", and anything containing SQL punctuation such as0; DROP TABLE users; --were all accepted before and emitted verbatim.The literal itself is unchanged — valid values are still emitted bare (
WHERE "products"."price" = 10.50), so existing queries, prepared statements ($1::numeric), and generated migrations keep byte-identical SQL. The Zod schema used bycreateInsertSchemashares the same predicate, so validation no longer disagrees between the two paths: it previously accepted0x27while the SQL layer produced a syntax error.const schema = createInsertSchema(Products);schema.safeParse({ price: "123.50" }); // okschema.safeParse({ price: "0x27" }); // fails: "Invalid numeric value" -
7566d59 - Thanks to @almahdi404 !
fix(prepare): bind a reused Arg once and bind values to their own placeholder
Referencing the same
Argin several places of one prepared statement —isIn(col, [arg, arg]), a multi-row insert sharing one argument, or anUPDATEusing one argument in bothset()andwhere()— sent one argument per reference while the SQL kept one placeholder per reference:WHERE "users"."username" IN ($1, $1) -- 1 placeholder, 2 arguments sentPostgreSQL rejected the statement:
ERROR: bind message supplies 2 parameters, but prepared statement "" requires 1Query.addArgnow registers an argument in the placeholder slot it owns, so a repeated reference writes its$Nagain without registering the value twice.The same change fixes a silent wrong-results bug that did not need a repeated argument. Placeholder numbers come from the argument names (sorted), while values used to be bound in the order the statement happened to write them, so any statement whose arguments were not written in name order bound each value to the wrong placeholder:
// "age" is $1 (sorts before "username"), so this used to run as// "users"."username" = $2 AND "users"."age" = $1 with the values swappedprepare({ age: Users.age.arg(), username: Users.username.arg() }, (args) =>db.prepare().from(Users).select("*").where(() =>and(eq(Users.username, args.username), eq(Users.age, args.age))));Values are now bound in placeholder order, so every
$Nreceives the value of its own argument.INSERT(bothvalues()andON CONFLICT ... DO UPDATE SET) andUPDATEargument emission go through the sameQuery.addArgpath, replacing their direct argument pushes. -
5bf6261 - Thanks to @almahdi404 !
perf(query): cut per-query promise allocations and redundant string work
Query building and per-query overhead are noticeably cheaper. Generated SQL is byte-identical in every case, and no public type changed.
Fewer promises per awaited query
Awaiting a query allocated a second promise and added a microtask hop, because
QueryPromise.thenchained a trailing.catch()that ran even with no rejection handler:return this.execute().then(onFulfilled).catch(onRejected);It now passes both handlers to a single
.then(onFulfilled, onRejected), and returnsexecute()'s promise untouched when there is neither handler — which is exactly whatawait querycompiles to. Twoasyncpass-through layers in the connector base class (execQuery,execStrArgs) were also dropped; they only forwarded a promise..then()no longer swallows errors from your own handlerThe old
then(a).catch(b)shape fed an error thrown byaintob. That is notPromise.thensemantics, and it silently swallowed errors from mapping callbacks:// before: the TypeError vanished, and onRejected saw it insteadawait db.from(Users).select("*").then((rows) => rows.map(r => r.id));// after: rejects with the TypeErrorBoth handlers now go to one
.then(), soonRejectedonly ever sees a rejection fromexecute()..catch()and.finally()are unchanged.Cheaper SQL generation
Measured against a revert of this change on the same machine (best of 3,
min):Benchmark Before After select(12 explicit cols)3.5 µs 1.5 µs select + 2 left joins7.8 µs 4.3 µs insert 50 rows44.5 µs 30.0 µs Gains scale with the number of columns rendered per query, which is where the wins came from:
- A column's
"table"."column"identifier is cached instead of rebuilt on every reference. The cache is invalidated when a column is named or attached to a table, so cloned and left-join columns still resolve correctly. camelToSnakememoizes its result. It runs once per column perclone()/cloneAsNullable(), and the table constructor no longer computes the same name twice.escIdentifier/escLiteralskip the regex scan when the string contains no quote to escape.database()calls each relations factory once instead of three times. Besides the wasted rebuilds, three calls could disagree with each other — a factory with side effects could produce a map key from oneRelationsobject and a value from another.
Benchmarks
Two new no-database benchmarks make these paths measurable in future, alongside the existing
handleRowsbenchmark:perf/query-build.bench.ts— construction cost (builder chain +toQuery(), never executed)perf/query-overhead.bench.ts— per-query promise overhead ofawait, against a stub pool
Note that per-query overhead is on the order of 1 µs, so it is invisible next to any real database round-trip. It is a fixed cost removed, not a throughput change.
- A column's
-
e9d13c6 - Thanks to @almahdi404 !
perf(select): resolve row converters once per result set
Converting driver rows to JS objects is the single hottest path in Durcno, and it now does a fraction of the per-cell work. Values are unchanged, and no public type or generated SQL changed.
One converter per column, not a lookup per cell
Column.fromDriverre-checksnulland the array dimensions on every value and then makes a second, polymorphic call tofromDriverScalar. With a dozen differentColumnsubclasses in one result set, both call sites are megamorphic — and that dispatch was repeated for every single cell.The conversion plan now resolves the converter once, when the plan is built from the first row, and stores one closure per column. A new shared
resolveFromDriverreturns the cheapest correct converter for a column, soselect("*"), explicit projections, and relational queries cannot drift apart:// one closure per column, built once per result set((row, out) => {out[outKey] = fromDriver(row[key]);});resolveFromDriverkeeps the fullfromDriverfor array-dimension columns (varchar({ dimension: array() })and friends), whose values still need array parsing. NoColumnsubclass overridesfromDriver, so the scalar branch is equivalent for every other column.The explicit-projection path is the one exception: it keeps calling
fromDriverdirectly, because its converter array interleaves per-column closures with shared module-level converters, and drawing them all from one shared literal pushed that call site further into polymorphism — measurably ~20% slower than the status quo.On the relational path the redundant
plan.keysarray is gone as well: each closure already closed over its own key, so the loop was loading the same key twice per cell.SELECT *converts in place when no key has to be renamedWhen every driver key already equals its camelCase output key — true for any all-lowercase, single-word column — the driver row already has the right keys. Those rows are now converted in place and handed straight back, instead of allocating a copy of every row:
// id, name, kind, price, enabled — all already their output keysconst rows = db.from(Tokens).select("*"); // -> the driver's own row objectsThis is the one intentional behaviour change here. When at least one key needs renaming (
user_name→userName), a fresh array of fresh objects is returned exactly as before and the input rows are left untouched.Two consequences for custom connectors:
- Returned rows may be the driver's own row objects. The built-in connectors construct rows fresh per query and never retain them, so this is contained there; a connector that reuses row objects — a row cache, a streaming cursor — must return fresh ones from
getRows(). - The conversion plan is built from the first row's keys. On the in-place path a later row carrying a key the first row did not have keeps that value unconverted, where the allocating path dropped it. No built-in connector produces heterogeneous row keys.
Measured
Median of three runs,
min, fromperf/handle-rows.ab.ts— which loads the old and newdistinto one process and alternates them inside the sample loop, so machine load and thermal drift cannot favour either side. Cross-process A/B (rebuilding and swappingdistbetween runs) proved too noisy on a shared machine to resolve differences of this size; it initially hid a real 20% regression in the opposite direction, and initially reported the in-place path as noise when it is a consistent win.Benchmark Before After select("*")— 10000 rows x 126.96 ms 4.71 ms −32% relational nested — 2000 x 5 x 2 6.33 ms 4.24 ms −33% select({...})mixed — 10000 x 80.69 ms 0.66 ms neutral The
select("*")benchmark uses a snake_case fixture, so it only exercises the allocating path.The in-place path is measured separately by
perf/handle-rows.paths.ts, which cannot be compared across builds — the allocating path never mutates its input while the in-place path does, so a shared fixture would timeBigInt(1n)againstBigInt("1"). Fed identical fresh driver rows, the in-place path wins 6 runs out of 6 on bothminandp10, by ~20% and ~12% respectively. That is a real but modest win, and it is the only part of this change with an observable behavior difference.Both harnesses ship alongside the benchmarks in
perf/as development tools — they are not part ofpnpm benchand are not picked up byvitest bench.perf/handle-rows.bench.tsalso gains a case for the in-place path, which builds its rows per iteration because that path consumes them. - Returned rows may be the driver's own row objects. The built-in connectors construct rows fresh per query and never retain them, so this is contained there; a connector that reuses row objects — a row cache, a streaming cursor — must return fresh ones from
-
2983012 - Thanks to @almahdi404 !
perf(query): cut repeated per-render work across the query builders
Building a query asks the same question in several places, and the answer was being worked out again every time. Across
select,insert,update,deleteand relational queries the same SQL now costs 7–21% less to produce, and a query on left-joined tables costs up to 94% less. Generated SQL is byte-identical in every case, and no public type changed.Three kinds of change, in descending order of what they were worth.
Cached per table, per class
One columns view per query, not one per chained method
A
LEFT JOINhands its clause callbacks a copy of the joined table's columns withnotNull/primaryKeystripped, so.where(),.orderBy(),.groupBy()and.having()each needed that copy. The view was memoised per builder instance — but every chained method returns a new instance, so the copy was rebuilt from scratch on each one:// 20 columns x 2 left-joined tables, for every method after the joinsdb.from(Articles).leftJoin(ArticleRevisions, ...).leftJoin(ArticleRatings, ...).select("*").where(...) // <- clones every joined column again.orderBy(...) // <- and again.groupBy(...) // <- and againThe view is now built once and carried into the derived builder. It only describes a builder when its
tableandjoinsare unchanged, so every method that forwards both hands its view along, andinnerJoin/leftJoin— which changejoins— pass none.limit()andoffset()do not read the view at all, so they forward whatever their builder already had without building one.The nullable copies are memoised per joined table in a
WeakMapkeyed on the table object, which covers the join methods too. Tables are per-schema singletons, so the cache is bounded and does not leak.Cost per query is now flat in the number of methods chained after the joins: −80% for two left joins with nothing after them, −94% with five methods after them.
One behavioural note: a nullable column in the view is now the same object in every query that joins that table, rather than a fresh copy each time. The view is read-only by convention — it exists to be handed to
eq(...),asc(...)and friends — and durcno already passes the table's own live column records to callbacks, so this makes the existing contract uniform. A callback that mutated a view column would now be visible to later queries.The rest of the caches
INSERTno longer rebuilds its column list. The("id", "title", ...)list and the field names are fixed by the table, yet both were rebuilt per query — one string and one array allocation per column, per insert. They are now resolved once per table in aWeakMap. Together with the streamed row loop: −7% on a 50-row insert that leaves five of nine columns out. A value function is still resolved per row, as before:.$insertFn(() => crypto.randomUUID())on auniquecolumn has to produce a different value for each row of a batch, so it is not memoised across rows.UPDATEno longer scans every column per query. Reading thehasUpdateFngetter off each column is now done once per table and cached in aWeakMap: −7% on an update of a table carrying$updateFncolumns.- A column's
sqlType/sqlCastare built once rather than rebuilding the array-dimension suffix on every read. They are read on every cast and everytoSQLExpressionof an array column. detectJsonKindno longer lowercases the class name per operand. The JSON kind of aSqlFnclass is resolved once per class in aWeakMap: −13% on a projection ofjson_build_object,jsonb_build_objectandjson_build_array.- The auto-
GROUP BYset is keyed on the column. Columns are per-table singletons, so the object is a free identity key and the cachedfullNamestring no longer has to be hashed per projection entry.
Streamed, not assembled
Every variadic function used to build an array of fragments and join it, or allocate a closure per element to thread a comma through:
// before, per renderthis.exprs.forEach((expr, i) => {appendOperand(query, expr, ctx, { leadOperand: this.exprs[0] });if (i < this.exprs.length - 1) query.sql += ", ";});// afterconst exprs = this.exprs;const options = { leadOperand: exprs[0] }; // once, not per operandfor (let i = 0; i < exprs.length; i++) {if (i !== 0) query.sql += ", ";appendOperand(query, exprs[i], ctx, options);}That ran in
concat,concat_ws,coalesce,greatest,least,json_build_object,jsonb_build_object,json_build_array,jsonb_build_array, and an aggregate'sORDER BY. The{ leadOperand }object was additionally rebuilt for every operand of everycoalesce/greatest/leastcall, although it is the same object each time.The same treatment covers the array literal in
appendOperand, theARRAY[...]branches of a dimension column,DISTINCT ON, anON CONFLICTtarget list, aDO UPDATE SETlist, and thejson_build_objectargument list of every relation in a relational query — all appended straight toquery.sql. The relational path was the worst offender: each level assembled an array of fragments, joined it, then embedded the result in a template literal.RETURNINGwas the other one. BothresolveReturningColumnsandbuildReturningClauseallocated three throwaway arrays (Object.values,Object.keys,filter,map,join) over a column list that is fixed per table. The clause is now streamed into the SQL, and the resolved column map is built in table-column order as before — which theRETURNINGtype inference depends on. A map that selects nothing still emits no clause.WITHwent further: it used to pick between"), "and") "by index, and now closes the previous CTE before opening the next and closes the last one after the loop.Measured on their own paths: variadic functions −10%, array filters −17%, a
RETURNINGexclusion map −8%,ON CONFLICT … DO UPDATE SETplusRETURNING *−8%, a nested relationalfindManywith per-levelcolumns−21%.Loop form, separators and hoisted invariants
Where items are comma-separated, the separator moved to the top of the loop body under an
i !== 0guard, so no loop computes a last index any more:// before: a hoisted last index that every loop had to get rightconst lastIdx = items.length - 1;for (let i = 0; i < items.length; i++) {render(items[i]);if (i < lastIdx) query.sql += ", ";}// afterfor (let i = 0; i < items.length; i++) {if (i !== 0) query.sql += ", ";render(items[i]);}That is the projection list,
ORDER BY,GROUP BY(explicit and auto-generated),DISTINCT ON,IN (...),ARRAY[...]for both operands and dimension columns,concat/concat_ws,coalesce/greatest/least, the fourjson_build_*functions, an aggregate'sORDER BY,ON CONFLICTtargets, the rows of a bulkINSERT, andRETURNING. Loops over an array now usefor...ofwherever the index is not load-bearing — two arrays stepped in lockstep, aconverts[i](...)call, reverse iteration, and a bound that is not the array's own length keep it.The reads that used to happen per iteration now happen once:
- A projection iterates keys, not
Object.entries(select)— which built a[key, value]pair per projection entry per query. referencedColumnsis read once. It is a rebuilding getter: it allocates a new array and recurses into nested expressions, and the auto-GROUP BYloop read it three times per projection entry.hasAggregatebreaks out of the loop instead of runningentries.some(...)over every entry.- The select-alias view is built with a loop rather than
Object.fromEntries(Object.keys(...).map(...)). - Emptiness is tested without
Object.keys(...)in the relationalselect/columnschecks, and a record's first value is read withoutObject.values(...)into_json/toJsonband in thereferencedColumnsgetters. Sql.toSQL()andSql.toQuery()index their template strings rather thanforEach-ing a closure: −28% on an 11-parameter template.
Combined on a 12-column projection with an aggregate, an auto-
GROUP BYand anorderByon a select alias: −27%.Measured
Median of five runs, from
perf/query-build.ab.ts— which loads the old and newdistinto one process and alternates them inside the sample loop, with the order inside each round flipped, so machine load, thermal drift and cache warmth cannot favour either side. Rebuilding and swappingdistbetween runs is too noisy on a shared machine to resolve differences of this size.min, median of five runs of 200 alternating samples each:Case Before After left joins + 5 chained methods 84.5 µs 5.5 µs −94% 2 left joins 12.2 µs 2.4 µs −80% 12-col projection + auto GROUP BY10.1 µs 7.3 µs −27% raw sqltemplate, 11 params3.7 µs 2.7 µs −28% nested relational findMany7.6 µs 6.1 µs −21% array filters 4.7 µs 3.9 µs −17% json_build_object+jsonb_...4.1 µs 3.6 µs −13% variadic functions × 8 6.5 µs 5.8 µs −10% aggregate ORDER BY× 23.2 µs 3.0 µs −8% ON CONFLICT … DO UPDATE SET10.6 µs 9.2 µs −8% 50-row INSERT, 5 columns omitted49.5 µs 45.8 µs −7% UPDATEwith$updateFncolumns3.5 µs 3.4 µs −7% DELETE … RETURNING(exclusion map)1.4 µs 1.3 µs −8% IN (…)with 6 values2.2 µs 2.2 µs neutral DISTINCT ON(3 columns)1.3 µs 1.3 µs neutral WITH— 3 CTEs24.8 µs 25.7 µs neutral select("*"), no join1.1 µs 1.1 µs neutral Three honest notes. The three flat cases each render a handful of items, and a case under about 2 µs has a ±5% noise floor on this machine:
WITHeven flips sign when the two snapshots are loaded in the opposite order, and it is dominated bydb.with()/.as()rather than by the clause that changed.DISTINCT ONandIN (…)changed a loop and a separator, not a list — there was no list to remove.No claim for row conversion.
helpers.ts,rq.tsandselect.tsalso had their row-conversion loops swept, andperf/handle-rows.ab.tsover three runs puts all three paths inside ±3% of where they were. The loop form was applied as a rule, and nothing is claimed for it.