drizzle-orm icon indicating copy to clipboard operation
drizzle-orm copied to clipboard

[FEATURE]: Drop the per-step `Omit` in `PgSelectWithout` to cut type-checker memory

Open andry-lebedev opened this issue 1 month ago โ€ข 1 comments

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)

  1. PgSelectWithout returns the builder type with K added to excludedMethods, without Omit.

  2. Each excludable method refuses an excluded receiver through its this parameter. The this type 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, offset and for get the same. PgSelectJoinFn gets this: PgSelectAllows<TIsLateral extends true ? never : `${TJoinType}Join`>, so set operators still exclude the four plain joins; lateral and cross joins behave as today.

  3. 0.45.x only: db builders skip the HKT lookup in PgSelectWithout (T['_']['hkt'] extends PgSelectHKT ? PgSelectBase<โ€ฆ> : PgSelectKind<โ€ฆ>). The result types are identical, and query-builder (qb) selects keep the lookup. On the 1.0 line one PgSelectBase<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-tests report no new diagnostics on main (TS 5.6.3, 5.8.3, 7.0.2) or rc5 (TS 6.0.3, 7.0.2) once 12 @ts-expect-error comments in type-tests/pg/select.ts and type-tests/pg/set-operators.ts move 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, offset or for; where after where and a join; qb mode; a union of two chain states; excluded methods after .union() and after union(). $dynamic() still allows repeats.
  • On main, declarations emit cleanly, and each excludable method's declaration carries this: 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">'. groupBy and orderBy have 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-error placed 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 PgSetOperator now refuses .where(), .having(), .groupBy(), .for() and the four plain joins. The alias records them in excludedMethods, which the guard reads; today only the Omit returned by a chain step hides excluded methods, and the alias is the bare class type.

Not proposed

  • The db dispatch in PgSelectJoin (last row of the first table). In drizzle's sources it adds TS2344 errors in select.types.ts and breaks withFriends<T extends PgSelectQueryBuilder> and dynamic<T extends PgSelectQueryBuilder> in type-tests/pg/select.ts. The failing comparisons go through the private createJoin, which the published .d.ts declares without a type, so our .d.ts patch 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 & {

andry-lebedev avatar Oct 20 '26 23:10 andry-lebedev

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.

scalebridge-jamie avatar Nov 29 '26 22:11 scalebridge-jamie