[FEATURE]: Drop the per-step `Omit` in `PgSelectWithout` to cut type-checker memory
Feature hasn't been suggested before.
- [x] I have verified this feature I'm about to request hasn't been suggested before.
Describe the enhancement you want to request
Every step of a select chain returns PgSelectWithout, which wraps the next builder type in Omit:
// pg-core/query-builders/select.types.ts, the same on main (0.45.4), beta (1.0.0-rc.4) and rc5
export type PgSelectWithout<T extends AnyPgSelectQueryBuilder, TDynamic extends boolean, K extends keyof T & string, TResetExcluded extends boolean = false> =
TDynamic extends true ? T : Omit<
PgSelectKind<T['_']['hkt'], /* โฆ */ TResetExcluded extends true ? K : T['_']['excludedMethods'] | K /* , โฆ */>,
TResetExcluded extends true ? K : T['_']['excludedMethods'] | K
>;
So for each .where(), .groupBy(), .having(), .orderBy(), .limit(), .offset(), .for(), join and set operator, TypeScript instantiates the next builder through the HKT lookup and then an Omit mapped type over its ~40 public members. The Omit is what makes a second .where() a compile error, and that refusal is worth keeping: at runtime the second call replaces the first condition. MySQL, SQLite, SingleStore and Gel (MSSQL and CockroachDB on the 1.0 line) use the same pattern, and so do the update, insert and delete builders.
Proposal (pg-core; full diff against main at the end)
-
PgSelectWithoutreturns the builder type withKadded toexcludedMethods, withoutOmit. -
Each excludable method refuses an excluded receiver through its
thisparameter. Thethistype mentions no type parameter of the builder, which keeps checking a call cheap:export interface PgSelectAllows<TMethod extends string> { readonly _: { readonly excludedMethods: Exclude<PgSelectExcludableMethod, TMethod> }; } // public overload; the implementation signature keeps the class `this` where(this: PgSelectAllows<'where'>, where: ((aliases: this['_']['selection']) => SQL | undefined) | SQL | undefined): PgSelectWithout<this, TDynamic, 'where'>;having,groupBy,orderBy,limit,offsetandforget the same.PgSelectJoinFngetsthis: PgSelectAllows<TIsLateral extends true ? never : `${TJoinType}Join`>, so set operators still exclude the four plain joins; lateral and cross joins behave as today. -
0.45.x only:
dbbuilders skip the HKT lookup inPgSelectWithout(T['_']['hkt'] extends PgSelectHKT ? PgSelectBase<โฆ> : PgSelectKind<โฆ>). The result types are identical, and query-builder (qb) selects keep the lookup. On the 1.0 line onePgSelectBase<THKT, โฆ>class serves every mode, so this step would need a different form there.
Measurements
We run this typing in a 10.6K-file backend as a pnpm patch of drizzle-orm 0.43.1's .d.ts. macOS arm64, Node 22.22.0, 0 errors in every run. Heap change ("Memory used") against the unpatched package:
| select-builder typing | 2nd .where() refused |
TS 7.0.2 | TS 5.8.3 |
|---|---|---|---|
PgSelectWithout returns T unchanged, like $dynamic() |
no | โ492 MiB | โ721 MiB |
no Omit, guard as a conditional this type over TExcludedMethods |
yes | โ153 MiB | โ124 MiB |
no Omit, constant PgSelectAllows guard (1โ2) |
yes | โ243 MiB | โ293 MiB |
โฆ plus db dispatch in PgSelectWithout (1โ3, proposed) |
yes | โ339 MiB | โ โ500 MiB |
โฆ plus db dispatch in PgSelectJoin (what we run, see "Not proposed") |
yes | โ366 MiB | โ โ553 MiB |
- TS 7.0.2:
tsc --noEmit --pretty false --checkers 1 --extendedDiagnostics. "Memory used" is the live heap after two forced GCs, so it is stable; baseline 6,336,705 K. The last row ends at 5,960,572 K with 0.89M fewer symbols (โ7.3%) and 21% fewer instantiations. - TS 5.8.3:
node --max-old-space-size=12288 node_modules/typescript/bin/tsc --noEmit --extendedDiagnostics. There is no forced GC, so the reading moves by up to ~100 MiB between runs (baseline 8,524,692โ8,635,552 K over three runs).
On drizzle's own type-tests (tsc -p drizzle-orm/type-tests --extendedDiagnostics; TS 5.x and 6.x run under node --expose-gc, so "Memory used" is read after a GC; two runs each, identical counts):
| branch, change | TypeScript | instantiations | types | memory used |
|---|---|---|---|---|
main @ eab8bed, 1โ3 |
5.6.3 | 8,365,912 โ 7,549,207 (โ9.8%) | 632,070 โ 594,668 (โ5.9%) | โ44 MiB (โ3.9%) |
| 7.0.2 ยน | 3,558,022 โ 3,324,801 (โ6.6%) | 655,069 โ 616,391 (โ5.9%) | โ25 MiB (โ3.0%) | |
rc5 @ 78476b3, 1โ2 |
6.0.3 | 5,926,835 โ 5,648,186 (โ4.7%) | 1,101,868 โ 1,058,100 (โ4.0%) | โ52 MiB (โ2.7%) |
| 7.0.2 | 5,804,182 โ 5,527,198 (โ4.8%) | 1,116,488 โ 1,070,931 (โ4.1%) | โ31 MiB (โ2.3%) |
ยน TS 7 rejects the baseUrl in main's type-tests/tsconfig.json; this run used the same options with absolute paths.
Checked against drizzle's sources
type-testsreport no new diagnostics onmain(TS 5.6.3, 5.8.3, 7.0.2) orrc5(TS 6.0.3, 7.0.2) once 12@ts-expect-errorcomments intype-tests/pg/select.tsandtype-tests/pg/set-operators.tsmove to the first line of their statements (see trade-offs). The dynamic-query helpers there (T extends PgSelect,T extends PgSelectQueryBuilder) still compile.- A separate 17-case test still fails where it should: a second
where,having,groupBy,orderBy,limit,offsetorfor;whereafterwhereand a join;qbmode; a union of two chain states; excluded methods after.union()and afterunion().$dynamic()still allows repeats. - On
main, declarations emit cleanly, and each excludable method's declaration carriesthis: PgSelectAllows<'โฆ'>.
Trade-offs
- A second call fails with TS2684 instead of TS2339:
The 'this' context of type 'PgSelectBase<โฆ>' is not assignable to method's 'this' of type 'PgSelectAllows<"where">'.groupByandorderByhave overloads, so they report TS2769 with that detail. - TypeScript reports the error on the receiver. In a multi-line chain it lands on the first line of the statement, and editors underline the receiver chain instead of the method name. An
@ts-expect-errorplaced above the repeated call no longer applies; these are the 12 comments in drizzle's tests. - Autocomplete lists methods that are already excluded; calling them still fails.
- A value typed as
PgSetOperatornow refuses.where(),.having(),.groupBy(),.for()and the four plain joins. The alias records them inexcludedMethods, which the guard reads; today only theOmitreturned by a chain step hides excluded methods, and the alias is the bare class type.
Not proposed
- The
dbdispatch inPgSelectJoin(last row of the first table). In drizzle's sources it adds TS2344 errors inselect.types.tsand breakswithFriends<T extends PgSelectQueryBuilder>anddynamic<T extends PgSelectQueryBuilder>intype-tests/pg/select.ts. The failing comparisons go through the privatecreateJoin, which the published.d.tsdeclares without a type, so our.d.tspatch does not hit them. - The update, insert and delete builders: same pattern, but at most 17 MiB in our backend.
Related, about other types: #800 (schema size and IntelliSense), #6391 ($inferInsert cost).
If this direction works for you, I can open a PR for pg-core and port it to the other dialects.
Diff against main (eab8bed): pg-core/query-builders/select.ts and select.types.ts
diff --git a/drizzle-orm/src/pg-core/query-builders/select.ts b/drizzle-orm/src/pg-core/query-builders/select.ts
index dafdb96..31ffd10 100644
--- a/drizzle-orm/src/pg-core/query-builders/select.ts
+++ b/drizzle-orm/src/pg-core/query-builders/select.ts
@@ -44,6 +44,7 @@ import type {
LockConfig,
LockStrength,
PgCreateSetOperatorFn,
+ PgSelectAllows,
PgSelectConfig,
PgSelectCrossJoinFn,
PgSelectDynamic,
@@ -762,6 +763,10 @@ export abstract class PgSelectQueryBuilderBase<
* await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
* ```
*/
+ where(
+ this: PgSelectAllows<'where'>,
+ where: ((aliases: this['_']['selection']) => SQL | undefined) | SQL | undefined,
+ ): PgSelectWithout<this, TDynamic, 'where'>;
where(
where: ((aliases: this['_']['selection']) => SQL | undefined) | SQL | undefined,
): PgSelectWithout<this, TDynamic, 'where'> {
@@ -799,6 +804,10 @@ export abstract class PgSelectQueryBuilderBase<
* .having(({ count }) => gt(count, 1));
* ```
*/
+ having(
+ this: PgSelectAllows<'having'>,
+ having: ((aliases: this['_']['selection']) => SQL | undefined) | SQL | undefined,
+ ): PgSelectWithout<this, TDynamic, 'having'>;
having(
having: ((aliases: this['_']['selection']) => SQL | undefined) | SQL | undefined,
): PgSelectWithout<this, TDynamic, 'having'> {
@@ -834,9 +843,13 @@ export abstract class PgSelectQueryBuilderBase<
* ```
*/
groupBy(
+ this: PgSelectAllows<'groupBy'>,
builder: (aliases: this['_']['selection']) => ValueOrArray<PgColumn | SQL | SQL.Aliased>,
): PgSelectWithout<this, TDynamic, 'groupBy'>;
- groupBy(...columns: (PgColumn | SQL | SQL.Aliased)[]): PgSelectWithout<this, TDynamic, 'groupBy'>;
+ groupBy(
+ this: PgSelectAllows<'groupBy'>,
+ ...columns: (PgColumn | SQL | SQL.Aliased)[]
+ ): PgSelectWithout<this, TDynamic, 'groupBy'>;
groupBy(
...columns:
| [(aliases: this['_']['selection']) => ValueOrArray<PgColumn | SQL | SQL.Aliased>]
@@ -881,9 +894,13 @@ export abstract class PgSelectQueryBuilderBase<
* ```
*/
orderBy(
+ this: PgSelectAllows<'orderBy'>,
builder: (aliases: this['_']['selection']) => ValueOrArray<PgColumn | SQL | SQL.Aliased>,
): PgSelectWithout<this, TDynamic, 'orderBy'>;
- orderBy(...columns: (PgColumn | SQL | SQL.Aliased)[]): PgSelectWithout<this, TDynamic, 'orderBy'>;
+ orderBy(
+ this: PgSelectAllows<'orderBy'>,
+ ...columns: (PgColumn | SQL | SQL.Aliased)[]
+ ): PgSelectWithout<this, TDynamic, 'orderBy'>;
orderBy(
...columns:
| [(aliases: this['_']['selection']) => ValueOrArray<PgColumn | SQL | SQL.Aliased>]
@@ -932,6 +949,7 @@ export abstract class PgSelectQueryBuilderBase<
* await db.select().from(people).limit(10);
* ```
*/
+ limit(this: PgSelectAllows<'limit'>, limit: number | Placeholder): PgSelectWithout<this, TDynamic, 'limit'>;
limit(limit: number | Placeholder): PgSelectWithout<this, TDynamic, 'limit'> {
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1)!.limit = limit;
@@ -957,6 +975,7 @@ export abstract class PgSelectQueryBuilderBase<
* await db.select().from(people).offset(10).limit(10);
* ```
*/
+ offset(this: PgSelectAllows<'offset'>, offset: number | Placeholder): PgSelectWithout<this, TDynamic, 'offset'>;
offset(offset: number | Placeholder): PgSelectWithout<this, TDynamic, 'offset'> {
if (this.config.setOperators.length > 0) {
this.config.setOperators.at(-1)!.offset = offset;
@@ -976,6 +995,7 @@ export abstract class PgSelectQueryBuilderBase<
* @param strength the lock strength.
* @param config the lock configuration.
*/
+ for(this: PgSelectAllows<'for'>, strength: LockStrength, config?: LockConfig): PgSelectWithout<this, TDynamic, 'for'>;
for(strength: LockStrength, config: LockConfig = {}): PgSelectWithout<this, TDynamic, 'for'> {
this.config.lockingClause = { strength, config };
return this as any;
diff --git a/drizzle-orm/src/pg-core/query-builders/select.types.ts b/drizzle-orm/src/pg-core/query-builders/select.types.ts
index 6a12030..6c84f8c 100644
--- a/drizzle-orm/src/pg-core/query-builders/select.types.ts
+++ b/drizzle-orm/src/pg-core/query-builders/select.types.ts
@@ -121,6 +121,7 @@ export type PgSelectJoinFn<
TJoinedTable extends (TIsLateral extends true ? Subquery | SQL : PgTable | Subquery | PgViewBase | SQL),
TJoinedName extends GetSelectTableName<TJoinedTable> = GetSelectTableName<TJoinedTable>,
>(
+ this: PgSelectAllows<TIsLateral extends true ? never : `${TJoinType}Join`>,
table: TableLikeHasEmptySelection<TJoinedTable> extends true ? DrizzleTypeError<
"Cannot reference a data-modifying statement subquery if it doesn't contain a `returning` clause"
>
@@ -248,8 +249,18 @@ export type PgSelectWithout<
TDynamic extends boolean,
K extends keyof T & string,
TResetExcluded extends boolean = false,
-> = TDynamic extends true ? T : Omit<
- PgSelectKind<
+> = TDynamic extends true ? T
+ : T['_']['hkt'] extends PgSelectHKT ? PgSelectBase<
+ T['_']['tableName'],
+ T['_']['selection'],
+ T['_']['selectMode'],
+ T['_']['nullabilityMap'],
+ TDynamic,
+ TResetExcluded extends true ? K : T['_']['excludedMethods'] | K,
+ T['_']['result'],
+ T['_']['selectedFields']
+ >
+ : PgSelectKind<
T['_']['hkt'],
T['_']['tableName'],
T['_']['selection'],
@@ -259,9 +270,31 @@ export type PgSelectWithout<
TResetExcluded extends true ? K : T['_']['excludedMethods'] | K,
T['_']['result'],
T['_']['selectedFields']
- >,
- TResetExcluded extends true ? K : T['_']['excludedMethods'] | K
->;
+ >;
+
+/** Methods that `PgSelectWithout` can record in `excludedMethods`. */
+export type PgSelectExcludableMethod =
+ | 'where'
+ | 'having'
+ | 'groupBy'
+ | 'orderBy'
+ | 'limit'
+ | 'offset'
+ | 'for'
+ | 'leftJoin'
+ | 'rightJoin'
+ | 'innerJoin'
+ | 'fullJoin';
+
+/**
+ * `this` type of an excludable method: the builder must not have `TMethod` among its excluded methods.
+ * It mentions no type parameter of the builder, so checking a call stays cheap.
+ */
+export interface PgSelectAllows<TMethod extends string> {
+ readonly _: {
+ readonly excludedMethods: Exclude<PgSelectExcludableMethod, TMethod>;
+ };
+}
export type PgSelectPrepare<T extends AnyPgSelect> = PgPreparedQuery<
PreparedQueryConfig & {
Independent data point in support of this proposal, from a production Next.js app on drizzle-orm 0.45.2 / TypeScript 5.9.3 (13.6K program files; about 5,000 select chains and 2,100 insert/update chains).
We patch the published .d.ts/.d.cts along the lines of row 2 of your first table: no Omit, with a conditional this guard over TExcludedMethods. We apply it to the select builder and to insert (returning, onConflictDo*), update (where, returning, joins) and delete (where, returning). The excluded set and the set-operator reset are carried unchanged in the generic.
Command: node --max-old-space-size=N tsc --noEmit --incremental false, Node 24, M-series, 0 errors in every run. "Min heap" is a bisection of N, with each boundary run twice.
| types | instantiations | check time | min heap that passes | |
|---|---|---|---|---|
| stock 0.45.2 | 2.90 M | 17.0 M | 46โ51 s | ~5,792 MB |
| patched | 1.83 M (โ37%) | 8.87 M (โ48%) | 33โ34 s | ~4,384 MB (โ24%) |
For scale: typing db as any gives 1.45 M types, so the Omit chains were about three quarters of everything Drizzle contributed to our program.
Almost all of the saving comes from the select builder. Removing Omit from select only gives 1.75 M types; removing it from all four builders gives 1.75 M too. The insert/update/delete guards are there for consistency rather than memory.
Type safety: a probe compiles identically against stock and patched declarations. It asserts exact result types for select, joins, insert, update and delete, and has 17 @ts-expect-error cases covering every repeatable clause across the four builders. With the guards stripped, all 17 fire TS2578. We saw the same trade-offs you list: TS2684 on the receiver, and excluded methods still shown in autocomplete.
It would be great to see this land for the insert, update and delete builders too.