Skip to main content

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 version field from package.json into the bundled CLI via process.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 in src/cli/index.ts was 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 ROLLBACK itself failed, which it does on an aborted or already-dead connection, client.close() was never reached and the pool slot was lost. After pool.max such failures (5 by default) every subsequent query waited forever for a connection that would never come back.

    The client is now released from a finally block, so it is returned to the pool exactly once on every path, and a failing ROLLBACK is 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/logger now exports createLogger as its primary factory function (with createQueryLogger and createDurcnoLogger preserved as aliases), and LogMetadata groups query execution telemetry (sql, arguments, durationMs) into a strongly-typed query: QueryLogData object, 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 as text[], and a comparison has no target column to coerce it — unlike INSERT, 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/notIn with array values, and array operands of SQL functions such as coalesce/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 unknown and PostgreSQL resolves it from the other side of the comparison, so eq(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 numeric column 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"));
    -- before
    SELECT * FROM "public"."products" WHERE "products"."price" = abc
    -- ERROR: column "abc" does not exist

    Values are now checked against the PostgreSQL numeric literal grammar (optional sign, digits, optional fraction, optional exponent) before being serialized, and an invalid value throws immediately — matching how uuid already reports bad input:

    db.from(Products).select("*").where(() => eq(Products.price, "abc"));
    // Error: Invalid numeric value: abc

    The check rejects more than the previous Number()-based one could: "", "0x27", "1_000", "NaN", "Infinity", and anything containing SQL punctuation such as 0; 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 by createInsertSchema shares the same predicate, so validation no longer disagrees between the two paths: it previously accepted 0x27 while the SQL layer produced a syntax error.

    const schema = createInsertSchema(Products);

    schema.safeParse({ price: "123.50" }); // ok
    schema.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 Arg in several places of one prepared statement — isIn(col, [arg, arg]), a multi-row insert sharing one argument, or an UPDATE using one argument in both set() and where() — sent one argument per reference while the SQL kept one placeholder per reference:

    WHERE "users"."username" IN ($1, $1) -- 1 placeholder, 2 arguments sent

    PostgreSQL rejected the statement:

    ERROR: bind message supplies 2 parameters, but prepared statement "" requires 1

    Query.addArg now registers an argument in the placeholder slot it owns, so a repeated reference writes its $N again 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 swapped
    prepare({ 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 $N receives the value of its own argument. INSERT (both values() and ON CONFLICT ... DO UPDATE SET) and UPDATE argument emission go through the same Query.addArg path, 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.then chained 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 returns execute()'s promise untouched when there is neither handler — which is exactly what await query compiles to. Two async pass-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 handler​

    The old then(a).catch(b) shape fed an error thrown by a into b. That is not Promise.then semantics, and it silently swallowed errors from mapping callbacks:

    // before: the TypeError vanished, and onRejected saw it instead
    await db.from(Users).select("*").then((rows) => rows.map(r => r.id));

    // after: rejects with the TypeError

    Both handlers now go to one .then(), so onRejected only ever sees a rejection from execute(). .catch() and .finally() are unchanged.

    Cheaper SQL generation​

    Measured against a revert of this change on the same machine (best of 3, min):

    BenchmarkBeforeAfter
    select(12 explicit cols)3.5 µs1.5 µs
    select + 2 left joins7.8 µs4.3 µs
    insert 50 rows44.5 µs30.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.
    • camelToSnake memoizes its result. It runs once per column per clone() / cloneAsNullable(), and the table constructor no longer computes the same name twice.
    • escIdentifier / escLiteral skip 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 one Relations object and a value from another.

    Benchmarks​

    Two new no-database benchmarks make these paths measurable in future, alongside the existing handleRows benchmark:

    • perf/query-build.bench.ts — construction cost (builder chain + toQuery(), never executed)
    • perf/query-overhead.bench.ts — per-query promise overhead of await, 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.

  • 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.fromDriver re-checks null and the array dimensions on every value and then makes a second, polymorphic call to fromDriverScalar. With a dozen different Column subclasses 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 resolveFromDriver returns the cheapest correct converter for a column, so select("*"), explicit projections, and relational queries cannot drift apart:

    // one closure per column, built once per result set
    ((row, out) => {
    out[outKey] = fromDriver(row[key]);
    });

    resolveFromDriver keeps the full fromDriver for array-dimension columns (varchar({ dimension: array() }) and friends), whose values still need array parsing. No Column subclass overrides fromDriver, so the scalar branch is equivalent for every other column.

    The explicit-projection path is the one exception: it keeps calling fromDriver directly, 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.keys array 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 renamed​

    When 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 keys
    const rows = db.from(Tokens).select("*"); // -> the driver's own row objects

    This 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, from perf/handle-rows.ab.ts — which loads the old and new dist into 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 swapping dist between 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.

    BenchmarkBeforeAfter
    select("*") — 10000 rows x 126.96 ms4.71 ms−32%
    relational nested — 2000 x 5 x 26.33 ms4.24 ms−33%
    select({...}) mixed — 10000 x 80.69 ms0.66 msneutral

    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 time BigInt(1n) against BigInt("1"). Fed identical fresh driver rows, the in-place path wins 6 runs out of 6 on both min and p10, 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 of pnpm bench and are not picked up by vitest bench. perf/handle-rows.bench.ts also gains a case for the in-place path, which builds its rows per iteration because that path consumes them.

  • 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, delete and 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 JOIN hands its clause callbacks a copy of the joined table's columns with notNull / primaryKey stripped, 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 joins
    db.from(Articles)
    .leftJoin(ArticleRevisions, ...)
    .leftJoin(ArticleRatings, ...)
    .select("*")
    .where(...) // <- clones every joined column again
    .orderBy(...) // <- and again
    .groupBy(...) // <- and again

    The view is now built once and carried into the derived builder. It only describes a builder when its table and joins are unchanged, so every method that forwards both hands its view along, and innerJoin / leftJoin — which change joins — pass none. limit() and offset() 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 WeakMap keyed 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​

    • INSERT no 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 a WeakMap. 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 a unique column has to produce a different value for each row of a batch, so it is not memoised across rows.
    • UPDATE no longer scans every column per query. Reading the hasUpdateFn getter off each column is now done once per table and cached in a WeakMap: −7% on an update of a table carrying $updateFn columns.
    • A column's sqlType / sqlCast are built once rather than rebuilding the array-dimension suffix on every read. They are read on every cast and every toSQLExpression of an array column.
    • detectJsonKind no longer lowercases the class name per operand. The JSON kind of a SqlFn class is resolved once per class in a WeakMap: −13% on a projection of json_build_object, jsonb_build_object and json_build_array.
    • The auto-GROUP BY set is keyed on the column. Columns are per-table singletons, so the object is a free identity key and the cached fullName string 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 render
    this.exprs.forEach((expr, i) => {
    appendOperand(query, expr, ctx, { leadOperand: this.exprs[0] });
    if (i < this.exprs.length - 1) query.sql += ", ";
    });

    // after
    const exprs = this.exprs;
    const options = { leadOperand: exprs[0] }; // once, not per operand
    for (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's ORDER BY. The { leadOperand } object was additionally rebuilt for every operand of every coalesce / greatest / least call, although it is the same object each time.

    The same treatment covers the array literal in appendOperand, the ARRAY[...] branches of a dimension column, DISTINCT ON, an ON CONFLICT target list, a DO UPDATE SET list, and the json_build_object argument list of every relation in a relational query — all appended straight to query.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.

    RETURNING was the other one. Both resolveReturningColumns and buildReturningClause allocated 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 the RETURNING type inference depends on. A map that selects nothing still emits no clause.

    WITH went 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 RETURNING exclusion map −8%, ON CONFLICT … DO UPDATE SET plus RETURNING * −8%, a nested relational findMany with per-level columns −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 !== 0 guard, so no loop computes a last index any more:

    // before: a hoisted last index that every loop had to get right
    const lastIdx = items.length - 1;
    for (let i = 0; i < items.length; i++) {
    render(items[i]);
    if (i < lastIdx) query.sql += ", ";
    }

    // after
    for (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 four json_build_* functions, an aggregate's ORDER BY, ON CONFLICT targets, the rows of a bulk INSERT, and RETURNING. Loops over an array now use for...of wherever the index is not load-bearing — two arrays stepped in lockstep, a converts[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.
    • referencedColumns is read once. It is a rebuilding getter: it allocates a new array and recurses into nested expressions, and the auto-GROUP BY loop read it three times per projection entry.
    • hasAggregate breaks out of the loop instead of running entries.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 relational select / columns checks, and a record's first value is read without Object.values(...) in to_json / toJsonb and in the referencedColumns getters.
    • Sql.toSQL() and Sql.toQuery() index their template strings rather than forEach-ing a closure: −28% on an 11-parameter template.

    Combined on a 12-column projection with an aggregate, an auto-GROUP BY and an orderBy on a select alias: −27%.

    Measured​

    Median of five runs, from perf/query-build.ab.ts — which loads the old and new dist into 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 swapping dist between runs is too noisy on a shared machine to resolve differences of this size.

    min, median of five runs of 200 alternating samples each:

    CaseBeforeAfter
    left joins + 5 chained methods84.5 µs5.5 µs−94%
    2 left joins12.2 µs2.4 µs−80%
    12-col projection + auto GROUP BY10.1 µs7.3 µs−27%
    raw sql template, 11 params3.7 µs2.7 µs−28%
    nested relational findMany7.6 µs6.1 µs−21%
    array filters4.7 µs3.9 µs−17%
    json_build_object + jsonb_...4.1 µs3.6 µs−13%
    variadic functions × 86.5 µs5.8 µs−10%
    aggregate ORDER BY × 23.2 µs3.0 µs−8%
    ON CONFLICT … DO UPDATE SET10.6 µs9.2 µs−8%
    50-row INSERT, 5 columns omitted49.5 µs45.8 µs−7%
    UPDATE with $updateFn columns3.5 µs3.4 µs−7%
    DELETE … RETURNING (exclusion map)1.4 µs1.3 µs−8%
    IN (…) with 6 values2.2 µs2.2 µsneutral
    DISTINCT ON (3 columns)1.3 µs1.3 µsneutral
    WITH — 3 CTEs24.8 µs25.7 µsneutral
    select("*"), no join1.1 µs1.1 µsneutral

    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: WITH even flips sign when the two snapshots are loaded in the opposite order, and it is dominated by db.with() / .as() rather than by the clause that changed. DISTINCT ON and IN (…) changed a loop and a separator, not a list — there was no list to remove.

    No claim for row conversion. helpers.ts, rq.ts and select.ts also had their row-conversion loops swept, and perf/handle-rows.ab.ts over 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.