durcno@1.0.0-alpha.35
Minor Changes
-
daac782 - Thanks to @almahdi404 !
feat(select): add row locking (FOR UPDATE & co.)
SELECT queries now support PostgreSQL row-level locking clauses via four new chainable methods:
await db.from(Users).select("*").where(() => eq(Users.id, id)).forUpdate({ noWait: true });.forUpdate(),.forNoKeyUpdate(),.forShare(),.forKeyShare()map to the corresponding lock strengths.- Options accept
ofto lock only named tables of the FROM/JOIN, and eithernoWait: true(NOWAIT) orskipLocked: true(SKIP LOCKED) — the two are mutually exclusive at the type level.
Type safety enforces PostgreSQL's restrictions: a query holds at most one locking clause (methods are omitted from the returned builder), and the methods disappear after GROUP BY / HAVING, where locking clauses are invalid. The clause is emitted after LIMIT/OFFSET.
The
LockOptionstype is exported from the package root. Covered by runtime tests against a live Postgres container (lock conflicts underNOWAIT,SKIP LOCKEDbehavior,ofscoping, clause ordering) and type tests. -
969f918 - Thanks to @almahdi404 !
feat(select): add window function support (OVER, PARTITION BY, frame)
Every aggregate now accepts
.over(spec), turning it into a window function call, and a full set of pure window functions shipped:rowNumber,rank,denseRank,percentRank,cumeDist,ntile,lag,lead,firstValue,lastValue,nthValue.const orders = await db.from(Orders).select(() => ({id: Orders.id,grandTotal: sum(Orders.amount).over(),cartTotal: sum(Orders.amount).over({ partitionBy: [Orders.userId] }),position: rowNumber().over({partitionBy: [Orders.userId],orderBy: [asc(Orders.createdAt)],frame: rows(unboundedPreceding()),}),}));- The spec object carries
partitionBy(columns, non-aggregate functions or raw SQL),orderBy(asc()/desc()items) and aframebuilt byrows()/range()/groups(), withunboundedPreceding(),preceding(n),currentRow(),following(n),unboundedFollowing()endpoints and an optionalEXCLUDEkind. - The result is a
WindowedSqlFnthat rendersfn(...) [FILTER (WHERE ...)] OVER (spec)and delegates value conversion to the wrapped function, so defaults and deserialization keep their column types (coalesce(sum(x).over(), 0),lag(timestamptz)→Date | null). FILTERbeforeOVERis allowed, as in PostgreSQL; an aggregate with an inline.orderBy()combined with.over()throws at build time, mirroring PostgreSQL's "not implemented" error.SqlFnTypegained"window". Windowed expressions are refused exactly where aggregates are (WHERE,ON,GROUP BY, insert/set values); at runtime a window function never triggers grouping — the auto-GROUP BYscan now skips windowed items in mixed projections via a mirroredhasWindowflag threaded through all operand-walking functions.
- The spec object carries
-
f8a25de - Thanks to @almahdi404 !
feat(update): add FROM clause and values aliases for bulk updates
UPDATEgains aFROMclause.UpdateBuilder.from()accepts real tables, CTEs, and values aliases, so many rows can be updated to different values in one statement instead of one statement per row:const V = db.values("v", {cartItemId: CartItems.id,orderItemId: CartItems.orderItemId,}).as([{ cartItemId: 1n, orderItemId: 100n },{ cartItemId: 2n, orderItemId: 101n },]);await db.update(CartItems).from(V).set({ orderItemId: V.orderItemId }).where(eq(CartItems.id, V.cartItemId));// UPDATE "public"."cart_items" SET "order_item_id" = "v"."orderItemId"// FROM (VALUES (1, 100),// (2, 101)) AS "v"("cartItemId", "orderItemId")// WHERE "cart_items"."id" = "v"."cartItemId"db.values(name, columns)declares a typed values alias: each declared column wraps a source column (from any table, or a fresh column definition), so rows are type-checked per cell and each value keeps the source column's SQL encoding.undefinedcells renderNULLwith the column's cast, and an alias with no rows throws when the statement is built — an emptyVALUESlist is not valid SQL..from()must be chained before.set()(mirroring how joins precede.select()), because the set payload type-checks against the sources' columns. Repeated.from()calls append sources, and.where()accepts references to any FROM source on either side of a comparison.RETURNINGnow renders its columns — including*— qualified with the target table name, with or withoutFROM, so a same-named FROM column cannot make them ambiguous andRETURNING *keeps returning only the updated table's columns. -
98d46b5 - Thanks to @almahdi404 !
feat(functions/comparison): add numNonNulls and numNulls
PostgreSQL's null-counting functions are now available as typed scalar expressions. Both accept one or more operands of any type and return
number, so they compose with the rest of the expression API:import { numNonNulls, numNulls } from "durcno";const [row] = await db.from(Users).select(() => ({filled: numNonNulls(Users.email, Users.phone, Users.username),missing: numNulls(Users.email, Users.phone, Users.username),}));- Operands can be columns, SQL functions, raw
sqlexpressions, preparedArgs, primitive literals, dates, arrays, objects, ornull. - At least one operand is required, matching PostgreSQL; zero-argument calls are rejected at compile time.
- Untyped prepared
Argoperands are cast totext, since PostgreSQL cannot infer a parameter type inside a variadic"any"call. - Column scope, prepared-argument presence, and aggregate/window flags propagate like other scalar functions, so an expression containing an aggregate is refused where PostgreSQL rejects it.
- The functions live in
src/functions/comparison.tsand are exported from the package root.
Covered by type tests for inference and clause gating, plus runtime tests for mixed operands and prepared-argument casts.
- Operands can be columns, SQL functions, raw
-
05b7190 - Thanks to @almahdi404 !
feat: support scalar subqueries as values
Single-column
SelectQueryvalues can now be used directly wherever a scalar expression is accepted:const users = await db.from(Users).select(() => ({id: Users.id,postCount: db.from(Posts).select(() => ({ total: count("*") })).where(() => eq(Posts.userId, Users.id)),}));await db.update(Users).set({score: coalesce(db.from(Posts).select(() => ({ total: count("*") })).where(() => eq(Posts.userId, Users.id)),0,),});The scalar result is typed
T | null, because PostgreSQL returnsNULLwhen the subquery has no row. Usecoalesce(...)when assigning to a non-null column. A scalar query must select exactly one column; multi-column queries are rejected at compile time when the projection is statically known and throw when the query is built otherwise.Direct queries work in projections, updates, inserts and conflict updates, comparisons,
coalesce/greatest/least/nullif,caseWhen, arithmetic/math/string functions, JSON builders, andasc/desc. Prepared subqueries propagate their prepare flag, driver conversion follows the selected column, and subquery aggregates stay scoped to the subquery and out of the outerGROUP BY.For scalar positions not covered directly, use
sqlwith a parenthesized subquery and an explicit type parameter, e.g.Sql<number>.
Patch Changes
-
3cce63b - Thanks to @almahdi404 !
impr(cli): unquote migration options in generated files
Generated
up.tsanddown.tsfiles now use plain object keys for migration options:export const options: MigrationOptions = {transaction: true,};The serializer also no longer mutates the provided options and skips
undefinedvalues. -
6cb42c5 - Thanks to @almahdi404 !
impr(connectors/pglite): upgrade to PGlite v0.5
The connector is now built and tested against
@electric-sql/pglitev0.5.PGlite v0.4+ runs initdb in a separate WASM module and changes the default database from
template1topostgres; v0.5 moves to PostgreSQL 18 and ships extensions as separate packages. Data directories created by older PGlite versions cannot be opened by v0.5 and must be recreated or dumped and restored.connect()waits for PGlite to finish initializing, so startup failures surface at connection time instead of on the first query.PGlite migrations run sequentially inside a transaction, so a failing statement rolls the whole migration back:
export const options: MigrationOptions = {transaction: true,execution: "sequential",}; -
97baa25 - Thanks to @almahdi404 !
fix(prepare): renumber placeholders and evaluate generated values per run
Prepared
INSERTandUPDATEqueries called$insertFn/$updateFnwhile the statement was built, then reused the generated values for every.run(). A unique$insertFncolumn failed on the second run with a duplicate key.Generated values are now bound as dynamic arguments and produced on every execution: once per omitted insert cell and once per update. The SQL text stays stable across runs.
const createLog = prepare({ action: AuditLogs.action.arg() },(args) =>db.prepare().insertInto(AuditLogs).values({ action: args.action }),);// createdAt and publicId are generated separately for each run.await createLog.run(db, { action: "first" });await createLog.run(db, { action: "second" });Placeholders now take their numbers in write order instead of the sorted argument names, so previously built statements written out of name order produce different SQL. A reused
Argwrites its$Nat every occurrence while binding its value once, and declared arguments the statement never references send no parameter.Arg.indexnow reports the placeholder number of the argument's first use instead of its sorted declaration position.Rendering an
Argplaceholder outsideprepare()emits$1instead of the broken$0, and the ad-hocQuery.pushArghelper joins the same numbering: it never reuses a number anArgalready took, and pushed values now reach prepared statements, re-bound on everyrun().