Skip to main content

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 of to lock only named tables of the FROM/JOIN, and either noWait: true (NOWAIT) or skipLocked: 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 LockOptions type is exported from the package root. Covered by runtime tests against a live Postgres container (lock conflicts under NOWAIT, SKIP LOCKED behavior, of scoping, 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 a frame built by rows()/range()/groups(), with unboundedPreceding(), preceding(n), currentRow(), following(n), unboundedFollowing() endpoints and an optional EXCLUDE kind.
    • The result is a WindowedSqlFn that renders fn(...) [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).
    • FILTER before OVER is allowed, as in PostgreSQL; an aggregate with an inline .orderBy() combined with .over() throws at build time, mirroring PostgreSQL's "not implemented" error.
    • SqlFnType gained "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 BY scan now skips windowed items in mixed projections via a mirrored hasWindow flag threaded through all operand-walking functions.
  • f8a25de - Thanks to @almahdi404 !

    feat(update): add FROM clause and values aliases for bulk updates

    UPDATE gains a FROM clause. 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. undefined cells render NULL with the column's cast, and an alias with no rows throws when the statement is built — an empty VALUES list 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.

    RETURNING now renders its columns — including * — qualified with the target table name, with or without FROM, so a same-named FROM column cannot make them ambiguous and RETURNING * 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 sql expressions, prepared Args, primitive literals, dates, arrays, objects, or null.
    • At least one operand is required, matching PostgreSQL; zero-argument calls are rejected at compile time.
    • Untyped prepared Arg operands are cast to text, 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.ts and 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.

  • 05b7190 - Thanks to @almahdi404 !

    feat: support scalar subqueries as values

    Single-column SelectQuery values 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 returns NULL when the subquery has no row. Use coalesce(...) 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, and asc/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 outer GROUP BY.

    For scalar positions not covered directly, use sql with 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.ts and down.ts files 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 undefined values.

  • 6cb42c5 - Thanks to @almahdi404 !

    impr(connectors/pglite): upgrade to PGlite v0.5

    The connector is now built and tested against @electric-sql/pglite v0.5.

    PGlite v0.4+ runs initdb in a separate WASM module and changes the default database from template1 to postgres; 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 INSERT and UPDATE queries called $insertFn / $updateFn while the statement was built, then reused the generated values for every .run(). A unique $insertFn column 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 Arg writes its $N at every occurrence while binding its value once, and declared arguments the statement never references send no parameter. Arg.index now reports the placeholder number of the argument's first use instead of its sorted declaration position.

    Rendering an Arg placeholder outside prepare() emits $1 instead of the broken $0, and the ad-hoc Query.pushArg helper joins the same numbering: it never reuses a number an Arg already took, and pushed values now reach prepared statements, re-bound on every run().