durcno@1.0.0-alpha.27
Major Changes
-
c323dbd - Thanks to @almahdi404 !
change(qb)!: adopt callback-based column views in select queries
Refactors
SelectBuilderandSelectQueryto 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 previousGroupByAliaswrapper class with direct alias references.// Querying with scoped column viewsconst 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
DatabaseandWithStatementto more closely mirror SQL statement syntax:- Renames
db.insert()todb.insertInto()(andwith(...).insert()towith(...).insertInto()). - Renames
db.delete()todb.deleteFrom()(andwith(...).delete()towith(...).deleteFrom()).
Calling
.select()with no arguments is no longer allowed. Selecting all table columns now requires explicitly passing"*"(select("*")), aligning with standard SQLSELECT *semantics while preserving callback-based selection for projecting specific columns.// Insert into tableawait db.insertInto(Users).values({name: "Alice",email: "alice@example.com",});// Delete from tableawait db.deleteFrom(Users).where(eq(Users.id, 1));// Select all columns explicitlyconst allUsers = await db.from(Users).select("*");// Select specific columnsconst userProfiles = await db.from(Users).select(({ users }) => ({id: users.id,name: users.name,})); - Renames
-
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.// Beforeconst rows = await db.with(activeUsers).from((ctes) => ctes.activeUsers).select("*").orderBy(({ activeUsers }) => asc(activeUsers.username));// Afterconst 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 rawsqltemplate expressions, literal primitives (string,number,bigint,boolean), andnullorsql.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,Sqlexpressions, andSqlFninstances. - Exports
SelectableItem,InferSelectRow, andInferSelectValueutility types for working with selectable projections. - Built-in SQL utilities
now(),uuidv4(), anduuidv7()now return typedSql<Date>andSql<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: returningnullwhen an argument is strictlynull,T | nullwhen an argument is nullable, and non-nullableTwhen all arguments are guaranteed non-null.Adds conditional SQL functions
coalesce(which dropsnullfrom the return type when a non-null fallback is provided),nullif,greatest, andleast, alongside string concatenation functionsconcatandconcatWs.// Selecting literals, raw SQL, and conditional expressionsconst users = await db.from(Users).select(({ users }) => ({username: users.username,displayName: coalesce(users.email, "Anonymous"),initial: left(users.username, 1), // typed as stringstatusLabel: "active", // literal stringcustomCalc: sql<number>`${users.id} * 10`,score: greatest(users.id, 0n),}));// Using literals and raw SQL inside CTEsconst 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 - In CTE queries defined via
-
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:
jsonBuildObjectandjsonbBuildObjectbuild key-value objects from columns, scalar expressions, or literals with compile-time object typing and runtime JSON deserialization.jsonBuildArrayandjsonbBuildArrayassemble structured JSON arrays from heterogeneous or homogeneous elements.jsonAggandjsonbAggaggregate rows into JSON arrays, supporting.orderBy(...),.filter(...), and.distinct().toJsonandtoJsonbconvert scalar values or entire table row views (e.g.toJson(users)) into JSON representations.jsonStripNullsandjsonbStripNullsstrip null object fields from JSON structures.
Refactors aggregate functions (
count,countDistinct,countStar,sum,avg,min,max,jsonAgg,jsonbAgg) onto anAggregateSqlFnbase class, adding support for PostgreSQLFILTER (WHERE ...)clauses via.filter()and element ordering via.orderBy().Adds
caseWhen(condition, then)builder for type-safe conditionalCASEexpressions. 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 implicitnullfallback.Enhances
coalesceand function operand serialization to support plain object literals, arrays,Date, andBigIntwith automatic JSON/JSONB type detection. Also detects nested aggregates insidecoalesceand extracts referenced columns from scalar SQL functions during automaticGROUP BYclause generation.// Querying nested relations with jsonBuildObject and jsonAggconst 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 caseWhenconst 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
existsandnotExistssubquery functions implementing PostgreSQL'sEXISTS (...)andNOT EXISTS (...)expressions. They acceptSelectQueryinstances, virtual subqueries, or rawSqlexpressions, supporting both independent and correlated subqueries with outer scope column references.Unifies subquery expressions under
src/functions/subquery.ts:isInandnotInnow extendSubquerySqlFn, allowing them to be projected directly in.select()as typed boolean fields in addition to their use in.where(),.having(), andcaseWhen()conditional expressions.Expands
notInto support subquery results alongside literal arrays. BothisInandnotInhandle empty literal arrays safely at runtime, generatingFALSEandTRUErespectively.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 automaticGROUP BYclause 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 subqueryconst authors = await db.from(Users).select("*").where(({ users }) =>exists(db.from(Posts).select("*").where(({ posts }) => eq(posts.userId, users.id)),));// Filter using NOT IN subqueryconst 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 viewconst admins = await db.from(Users).select(({ users }) => ({ id: users.id })).where(({ users }) => eq(users.type, "admin"));// After: direct table referencesconst admins = await db.from(Users).select(() => ({ id: Users.id })).where(() => eq(Users.type, "admin"));// Left joins still use the callback view for nullable inferenceconst 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
selectoption in relational queries (findManyandfindFirst), mirroring projection behavior in.select(). Keys define output aliases, while values are table columns or scalarSqlFnexpressions.The
selectoption can be used at the top level and within nested relations inwith.selectandcolumnsare mutually exclusive at every level, enforced at compile time through overloaded signatures and discriminated option types, with runtime validation safeguards.Driver value deserialization (
fromDriverandfromDriverValue) 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 inwith.import { lower } from "durcno";// Top-level alias selection with columns and scalar SqlFnsconst 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,},},},});