durcno@1.0.0-alpha.31
Patch Changes
-
054b9a4 - Thanks to @almahdi404 !
perf(rq): narrow relation subquery projections and fix nested limit/offset
Two changes to the SQL generated by
db.query(Table).findMany/findFirst: a projection fix that avoids reading unused columns, and corrections to nestedlimit/offsethandling.Narrowed relation subquery projections
Each related row set is built with a
LEFT JOIN LATERALover a derived table. That derived table used to select"alias".*, so PostgreSQL read every column of every matched related row off the heap even when the parent projection only referenced a few of them.The projection is now built from the same
columnsfilter that drivesjson_build_object, so only the columns the result actually needs are read:-- beforeFROM (SELECT "posts".* FROM "public"."posts" "posts" WHERE ...) "posts"-- afterFROM (SELECT "posts"."id", "posts"."title" FROM "public"."posts" "posts" WHERE ...) "posts"The saving scales with
(parent rows x related rows)and is largest for tables with widetext/jsonbcolumns, since the unrequested ones no longer have to be fetched and detoasted.Alias-based
selectmode keeps the*projection, because the columns referenced by aSqlFnexpression are not introspectable. Results are unchanged.Nested
limitandoffsetcorrectionsThree fixes to the
limit/offsetoptions accepted inside awithblock formanyrelations.offsetwas never emitted. It was accepted by the type definitions and documented, butbuildRelationSubqueryonly handledorderByandlimit, sooffsetwas silently dropped. It now renders afterLIMIT, as PostgreSQL requires when both are present.limit: 0was dropped. The guard was a truthiness check rather than anundefinedcheck, so a zero limit never reached the generated SQL. It now correctly producesLIMIT 0and returns an empty array.limit/offsetno longer inline preparedArgplaceholders. Nested values were interpolated directly, which rendered anArgobject asLIMIT [object Object]and failed with a syntax error. They now bind as proper$Nparameters, matching the top-level options:const statement = prepare({ lim: Arg.number(), off: Arg.number() },(args) =>db.prepare().query(schema.Posts).findMany({columns: { id: true },with: {comments: {columns: { body: true },orderBy: asc(schema.Comments.body),limit: args.lim,offset: args.off,},},}),);The shared top-level and nested limit/offset rendering is now a single
appendLimitOffsethelper, so both paths stay in sync. -
c4a5ae4 - Thanks to @almahdi404 !
perf(rows): precompute the row-conversion plan of select and relational queries
Every result row was re-deriving what each of its values should be converted with, even though the answer only depends on the query, not on the row. The conversion is now resolved once per query and replayed for each row.
What changed
handleRowsis the last step of a query: it maps driver rows to the JS shapes you get back. It used to do that work per value:- an explicit
.select({...})looked up the projection item again for every cell and re-ran the samenull/ column /SqlFn/ literal type dispatch on it, walking the prototype chain each time the item was not a column; select("*")resolvedcolumnsBySql[key] ?? columns[key]— plus a scan of the joined tables — for every cell of every row, from inside nested callbacks;- relational queries allocated an
Object.keysarray per row (per nested child object too) and re-resolved the alias map, the table columns, and the relation map on every key.
All three now build a plan from the keys of the first row and loop over it:
// before — per cellconst item = this.#$select[key];if (item === null) { /* ... */ }else if (isTCol(item)) row[key] = item.fromDriver(row[key]);else if (item instanceof SqlFn) { /* ... */ }else if (typeof item === "bigint") { /* ... */ }// after — per key, onceconst convert = buildSelectItemConverter(this.#$select[key]);// then, per cellrow[key] = convert(row[key]);Relational queries do the same per level of the relation tree, so the plan for
users -> posts -> commentsis built once and reused by every parent row and every nested child.Two smaller wins on the same path:
Columncaches its array dimensions instead of reading them back through the config on every conversion, and the converter of a CTE/virtual column is resolved from its source expression once, at construction, rather than re-dispatching on the source kind per value.The five copies of the
SELECT *row mapper (select,insert,update,delete,first) are now onemapStarRowshelper insrc/query-builders/helpers.ts, withselectcaching its plan across rows.Results
Measured with the new
pnpm benchsuite (perf/), which feeds synthetic driver rows tohandleRowsso the numbers isolate conversion cost from SQL generation and network time. Both variants ran interleaved in one process, medians over 15 rounds:Benchmark Before After Speedup select("*")— 10k rows × 12 col13.1 ms 7.8 ms 1.7× select({...})— 10k rows × 8 col2.2 ms 0.77 ms 2.9× relational nested — 2k × 5 × 2 11.9 ms 7.0 ms 1.7× Results are unchanged.
tests/qb/rows.unit.test.tscovers the conversion of star, aliased, joined, and relational results, including NULL handling, theColumn ... not found in any tableerror, and reusing a query's plan across executions. - an explicit