Skip to main content

durcno@1.0.0-alpha.27

Major Changes​

  • c323dbd - Thanks to @almahdi404 !

    change(qb)!: adopt callback-based column views in select queries

    Refactors SelectBuilder and SelectQuery to adopt a unified, callback-based columns-view pattern across query clauses: .where(), .select(), .orderBy(), .groupBy(), .having(), .distinctOn(), .innerJoin(), and .leftJoin().

    Instead of passing top-level column references from table objects (e.g. Users.id), clauses now receive a scoped columns view keyed by table name (e.g. ({ users, posts }) => ...). This eliminates ambiguous column references in multi-table queries and aligns syntax across all clauses.

    Columns from left-joined tables are now automatically projected as nullable types in the callback view, with runtime support via cloneAsNullable() on column instances.

    Output column aliases in .groupBy() and .orderBy() are now accessed via a second callback parameter (selects), replacing the previous GroupByAlias wrapper class with direct alias references.

    // Querying with scoped column views
    const result = await db
    .from(Users)
    .leftJoin(Posts, ({ users, posts }) => eq(users.id, posts.userId))
    .select(({ users, posts }) => ({
    userId: users.id,
    postTitle: posts.title, // typed as string | null
    }))
    .where(({ users }) => eq(users.isActive, true))
    .groupBy(({ users }, { userId }) => [userId])
    .orderBy(({ users }) => asc(users.createdAt));
  • c496682 - Thanks to @almahdi404 !

    change(qb)!: align insert, delete, and select methods with sql syntax

    Renames core query builder entry methods across Database and WithStatement to more closely mirror SQL statement syntax:

    • Renames db.insert() to db.insertInto() (and with(...).insert() to with(...).insertInto()).
    • Renames db.delete() to db.deleteFrom() (and with(...).delete() to with(...).deleteFrom()).

    Calling .select() with no arguments is no longer allowed. Selecting all table columns now requires explicitly passing "*" (select("*")), aligning with standard SQL SELECT * semantics while preserving callback-based selection for projecting specific columns.

    // Insert into table
    await db.insertInto(Users).values({
    name: "Alice",
    email: "alice@example.com",
    });

    // Delete from table
    await db.deleteFrom(Users).where(eq(Users.id, 1));

    // Select all columns explicitly
    const allUsers = await db.from(Users).select("*");

    // Select specific columns
    const userProfiles = await db.from(Users).select(({ users }) => ({
    id: users.id,
    name: users.name,
    }));
  • a877fe1 - Thanks to @almahdi404 !

    change(cte)!: use CTE instances directly in .from()

    Removes the db.with(...).from((ctes) => ctes.name) callback form. CTEs are now passed to .from() directly, exactly like normal tables, and their columns are referenced directly from the CTE variable.

    // Before
    const rows = await db
    .with(activeUsers)
    .from((ctes) => ctes.activeUsers)
    .select("*")
    .orderBy(({ activeUsers }) => asc(activeUsers.username));

    // After
    const rows = await db
    .with(activeUsers)
    .from(activeUsers)
    .select("*")
    .orderBy(() => asc(activeUsers.username));

    CTEs used in .leftJoin() are unaffected — left joined tables are still accessed through the callback view parameter, just like normal tables.

Minor Changes​

  • b45eabe - Thanks to @almahdi404 !

    feat: support expression projections and null-safe sql functions

    Expands .select() projections and CTEs to support arbitrary expressions beyond table columns and SQL functions. Projections can now include raw sql template expressions, literal primitives (string, number, bigint, boolean), and null or sql.null, with runtime driver deserialization and full compile-time type inference:

    • In CTE queries defined via db.with(...).as(...), virtual tables automatically infer column types and non-nullability constraints from projected literals, Sql expressions, and SqlFn instances.
    • Exports SelectableItem, InferSelectRow, and InferSelectValue utility types for working with selectable projections.
    • Built-in SQL utilities now(), uuidv4(), and uuidv7() now return typed Sql<Date> and Sql<string> instances.

    Introduces strict null-sensitive return type inference (StrictFnReturn) across mathematical, string, arithmetic, pgvector, and postgis functions. Function return types dynamically narrow based on operand nullability: returning null when an argument is strictly null, T | null when an argument is nullable, and non-nullable T when all arguments are guaranteed non-null.

    Adds conditional SQL functions coalesce (which drops null from the return type when a non-null fallback is provided), nullif, greatest, and least, alongside string concatenation functions concat and concatWs.

    // Selecting literals, raw SQL, and conditional expressions
    const users = await db.from(Users).select(({ users }) => ({
    username: users.username,
    displayName: coalesce(users.email, "Anonymous"),
    initial: left(users.username, 1), // typed as string
    statusLabel: "active", // literal string
    customCalc: sql<number>`${users.id} * 10`,
    score: greatest(users.id, 0n),
    }));

    // Using literals and raw SQL inside CTEs
    const userStats = db.with("stats").as(
    db.from(Users).select(({ users }) => ({
    userId: users.id,
    activeFlag: true,
    created: now(), // typed as Date in CTE output
    })),
    );

    const rows = await db
    .with(userStats)
    .from((ctes) => ctes.stats)
    .select("*"); // full types preserved
  • 6efc8b7 - Thanks to @almahdi404 !

    feat: add json functions, case expressions, and aggregate filters

    Introduces PostgreSQL JSON and JSONB function builders for constructing nested JSON structures directly in SQL queries:

    • jsonBuildObject and jsonbBuildObject build key-value objects from columns, scalar expressions, or literals with compile-time object typing and runtime JSON deserialization.
    • jsonBuildArray and jsonbBuildArray assemble structured JSON arrays from heterogeneous or homogeneous elements.
    • jsonAgg and jsonbAgg aggregate rows into JSON arrays, supporting .orderBy(...), .filter(...), and .distinct().
    • toJson and toJsonb convert scalar values or entire table row views (e.g. toJson(users)) into JSON representations.
    • jsonStripNulls and jsonbStripNulls strip null object fields from JSON structures.

    Refactors aggregate functions (count, countDistinct, countStar, sum, avg, min, max, jsonAgg, jsonbAgg) onto an AggregateSqlFn base class, adding support for PostgreSQL FILTER (WHERE ...) clauses via .filter() and element ordering via .orderBy().

    Adds caseWhen(condition, then) builder for type-safe conditional CASE expressions. Supports chaining multiple .when(...) branches, .else(...), and .end(), with full TypeScript union inference across all branch results. Direct selection without .end() or .else() evaluates with an implicit null fallback.

    Enhances coalesce and function operand serialization to support plain object literals, arrays, Date, and BigInt with automatic JSON/JSONB type detection. Also detects nested aggregates inside coalesce and extracts referenced columns from scalar SQL functions during automatic GROUP BY clause generation.

    // Querying nested relations with jsonBuildObject and jsonAgg
    const postsWithComments = await db
    .from(Posts)
    .leftJoin(Comments, ({ posts, comments }) => eq(comments.postId, posts.id))
    .select(({ posts, comments }) => ({
    id: posts.id,
    title: posts.title,
    comments: coalesce(
    jsonAgg(
    jsonBuildObject({
    id: comments.id,
    body: comments.body,
    }),
    )
    .orderBy(asc(comments.id))
    .filter(isNotNull(comments.id)),
    [],
    ),
    }))
    .groupBy(({ posts }) => [posts.id]);

    // Conditional classification with caseWhen
    const users = await db.from(Users).select(({ users }) => ({
    username: users.username,
    roleBadge: caseWhen(eq(users.type, "admin"), "Administrator")
    .when(eq(users.type, "moderator"), "Moderator")
    .else("Member"),
    }));
  • a6caa59 - Thanks to @almahdi404 !

    feat: support exists and subquery functions

    Adds exists and notExists subquery functions implementing PostgreSQL's EXISTS (...) and NOT EXISTS (...) expressions. They accept SelectQuery instances, virtual subqueries, or raw Sql expressions, supporting both independent and correlated subqueries with outer scope column references.

    Unifies subquery expressions under src/functions/subquery.ts: isIn and notIn now extend SubquerySqlFn, allowing them to be projected directly in .select() as typed boolean fields in addition to their use in .where(), .having(), and caseWhen() conditional expressions.

    Expands notIn to support subquery results alongside literal arrays. Both isIn and notIn handle empty literal arrays safely at runtime, generating FALSE and TRUE respectively.

    Adds full type-safe parameter tracking (Arg) for prepared queries across all subquery functions, preventing unprepared queries from executing with unresolved arguments while propagating argument types in prepared statements.

    Subquery function projections in .select() are automatically identified as non-aggregate SQL functions, preventing erroneous automatic GROUP BY clause generation when combined with aggregate expressions.

    import { eq, exists, isIn, notExists, notIn } from "durcno";

    // Project subquery results as boolean columns in .select()
    const userProfiles = await db.from(Users).select(({ users }) => ({
    id: users.id,
    hasPosts: exists(
    db
    .from(Posts)
    .select("*")
    .where(({ posts }) => eq(posts.userId, users.id)),
    ),
    isAdmin: isIn(users.type, ["admin", "superadmin"]),
    }));

    // Filter using correlated EXISTS subquery
    const authors = await db
    .from(Users)
    .select("*")
    .where(({ users }) =>
    exists(
    db
    .from(Posts)
    .select("*")
    .where(({ posts }) => eq(posts.userId, users.id)),
    )
    );

    // Filter using NOT IN subquery
    const usersWithoutOrders = await db
    .from(Users)
    .select("*")
    .where(({ users }) =>
    notIn(
    users.id,
    db.from(Orders).select(({ orders }) => ({ userId: orders.userId })),
    )
    );
  • d46a1fd - Thanks to @almahdi404 !

    impr(qb): refer non-left-join columns from table directly

    Columns from non-left-joined tables can now be referenced directly from the original table objects, without destructuring them from the callback view.

    The callback parameter is now only needed for left-joined tables, where the view projects columns as nullable types. All other clauses (.select(), .where(), .orderBy(), .groupBy(), .having(), .distinctOn(), joins, and subqueries) accept parameter-less callbacks that close over table definitions.

    Updates JSDoc examples, type tests, integration tests, and website docs to use the direct-reference style.

    // Before: destructured callback view
    const admins = await db
    .from(Users)
    .select(({ users }) => ({ id: users.id }))
    .where(({ users }) => eq(users.type, "admin"));

    // After: direct table references
    const admins = await db
    .from(Users)
    .select(() => ({ id: Users.id }))
    .where(() => eq(Users.type, "admin"));

    // Left joins still use the callback view for nullable inference
    const rows = await db
    .from(Posts)
    .leftJoin(Users, () => eq(Users.id, Posts.userId))
    .select(({ users }) => ({
    title: Posts.title,
    author: users.username, // typed as string | null
    }));
  • c9e05da - Thanks to @almahdi404 !

    feat(rq): support alias-based selection in relational queries

    Adds alias-based selection via the select option in relational queries (findMany and findFirst), mirroring projection behavior in .select(). Keys define output aliases, while values are table columns or scalar SqlFn expressions.

    The select option can be used at the top level and within nested relations in with. select and columns are mutually exclusive at every level, enforced at compile time through overloaded signatures and discriminated option types, with runtime validation safeguards.

    Driver value deserialization (fromDriver and fromDriverValue) is preserved across aliased projections, using precomputed conversion contexts to avoid per-row allocations. Expressions are validated to ensure columns belong to the queried table, aggregate SQL functions are rejected, and aliases do not collide with sibling relation keys in with.

    import { lower } from "durcno";

    // Top-level alias selection with columns and scalar SqlFns
    const users = await db.query(Users).findMany({
    select: {
    userId: Users.id,
    name: Users.username,
    loweredName: lower(Users.username),
    },
    with: {
    posts: {
    select: {
    postId: Posts.id,
    heading: Posts.title,
    },
    },
    },
    });