@prisma-next/sql-builder 0.5.1 → 0.6.0-dev.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,7 @@ import { _ as ScopeField, f as FieldProxy, g as Scope, h as QueryContext, p as F
2
2
  import { AnyExpression } from "@prisma-next/sql-relational-core/ast";
3
3
  import { Expression } from "@prisma-next/sql-relational-core/expression";
4
4
  import { SqlStorage } from "@prisma-next/sql-contract/types";
5
+ import { CodecRef } from "@prisma-next/framework-components/codec";
5
6
  import { SqlOperationEntry } from "@prisma-next/sql-operations";
6
7
  import { Contract } from "@prisma-next/contract/types";
7
8
  import { ExecutionContext } from "@prisma-next/sql-relational-core/query-lane-context";
@@ -10,19 +11,13 @@ import { ExecutionContext } from "@prisma-next/sql-relational-core/query-lane-co
10
11
  /**
11
12
  * Runtime wrapper around a relational-core AST expression node. Carries ScopeField metadata (codecId, nullable) so aggregate-like combinators can propagate the input codec onto their result.
12
13
  *
13
- * `refs` records the column-bound binding (`{ table, column }`) when known — the field-proxy populates it for both the namespaced form (`f.user.email` → `ColumnRef`) and the top-level shortcut (`f.email` → `IdentifierRef` + refs metadata). Encode-side dispatch and the `validateParamRefRefs` pass read it via `refsOf(expression)`.
14
+ * `codec` records the column-bound {@link CodecRef} when the field-proxy knows the binding both the namespaced form (`f.user.email` → `ColumnRef`) and the top-level shortcut (`f.email` → `IdentifierRef`) stamp the ref derived from contract storage. `codecOf(expression)` exposes it for operation implementations forwarding the ref to `toExpr`.
14
15
  */
15
16
  declare class ExpressionImpl<T extends ScopeField = ScopeField> implements Expression<T> {
16
17
  private readonly ast;
17
18
  readonly returnType: T;
18
- readonly refs: {
19
- readonly table: string;
20
- readonly column: string;
21
- } | undefined;
22
- constructor(ast: AnyExpression, returnType: T, refs?: {
23
- readonly table: string;
24
- readonly column: string;
25
- });
19
+ readonly codec: CodecRef | undefined;
20
+ constructor(ast: AnyExpression, returnType: T, codec?: CodecRef);
26
21
  buildAst(): AnyExpression;
27
22
  }
28
23
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/runtime/expression-impl.ts","../../src/runtime/field-proxy.ts","../../src/runtime/functions.ts","../../src/runtime/sql.ts"],"mappings":";;;;;;;;;;;;;;cASa,cAAA,WAAyB,UAAA,GAAa,UAAA,aAAuB,UAAA,CAAW,CAAA;EAAA,iBAClE,GAAA;EAAA,SACR,UAAA,EAAY,CAAA;EAAA,SACZ,IAAA;IAAA,SAAiB,KAAA;IAAA,SAAwB,MAAA;EAAA;cAGhD,GAAA,EAAK,aAAA,EACL,UAAA,EAAY,CAAA,EACZ,IAAA;IAAA,SAAkB,KAAA;IAAA,SAAwB,MAAA;EAAA;EAO5C,QAAA,CAAA,GAAY,aAAA;AAAA;;;iBCJE,gBAAA,WAA2B,KAAA,CAAA,CAAO,KAAA,EAAO,CAAA,GAAI,UAAA,CAAW,CAAA;;;iBC+KxD,eAAA,YAA2B,YAAA,CAAA,CACzC,UAAA,EAAY,QAAA,CAAS,MAAA,SAAe,iBAAA,KACnC,SAAA,CAAU,EAAA;AAAA,iBAeG,wBAAA,YAAoC,YAAA,CAAA,CAClD,UAAA,EAAY,QAAA,CAAS,MAAA,SAAe,iBAAA,KACnC,kBAAA,CAAmB,EAAA;;;UC/ML,UAAA,WAAqB,QAAA,CAAS,UAAA;EAAA,SACpC,OAAA,EAAS,gBAAA,CAAiB,CAAA;AAAA;AAAA,iBAGrB,GAAA,WAAc,QAAA,CAAS,UAAA,EAAA,CAAa,OAAA,EAAS,UAAA,CAAW,CAAA,IAAK,EAAA,CAAG,CAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/runtime/expression-impl.ts","../../src/runtime/field-proxy.ts","../../src/runtime/functions.ts","../../src/runtime/sql.ts"],"mappings":";;;;;;;;;;;;;;;cAUa,cAAA,WAAyB,UAAA,GAAa,UAAA,aAAuB,UAAA,CAAW,CAAA;EAAA,iBAClE,GAAA;EAAA,SACR,UAAA,EAAY,CAAA;EAAA,SACZ,KAAA,EAAO,QAAA;cAEJ,GAAA,EAAK,aAAA,EAAe,UAAA,EAAY,CAAA,EAAG,KAAA,GAAQ,QAAA;EAMvD,QAAA,CAAA,GAAY,aAAA;AAAA;;;iBChBE,gBAAA,WAA2B,KAAA,CAAA,CAAO,KAAA,EAAO,CAAA,GAAI,UAAA,CAAW,CAAA;;;iBC8KxD,eAAA,YAA2B,YAAA,CAAA,CACzC,UAAA,EAAY,QAAA,CAAS,MAAA,SAAe,iBAAA,KACnC,SAAA,CAAU,EAAA;AAAA,iBAeG,wBAAA,YAAoC,YAAA,CAAA,CAClD,UAAA,EAAY,QAAA,CAAS,MAAA,SAAe,iBAAA,KACnC,kBAAA,CAAmB,EAAA;;;UC/LL,UAAA,WAAqB,QAAA,CAAS,UAAA;EAAA,SACpC,OAAA,EAAS,gBAAA,CAAiB,CAAA;AAAA;AAAA,iBAGrB,GAAA,WAAc,QAAA,CAAS,UAAA,EAAA,CAAa,OAAA,EAAS,UAAA,CAAW,CAAA,IAAK,EAAA,CAAG,CAAA"}
@@ -1,19 +1,20 @@
1
1
  import { AggregateExpr, AndExpr, BinaryExpr, ColumnRef, DeleteAst, DerivedTableSource, ExistsExpr, IdentifierRef, InsertAst, JoinAst, ListExpression, LiteralExpr, NullCheckExpr, OrExpr, OrderByItem, ParamRef, ProjectionItem, SelectAst, SubqueryExpr, TableSource, UpdateAst, collectOrderedParamRefs } from "@prisma-next/sql-relational-core/ast";
2
- import { refsOf, toExpr } from "@prisma-next/sql-relational-core/expression";
2
+ import { codecOf, toExpr } from "@prisma-next/sql-relational-core/expression";
3
+ import { codecRefForStorageColumn } from "@prisma-next/sql-relational-core/codec-descriptor-registry";
3
4
  //#region src/runtime/expression-impl.ts
4
5
  /**
5
6
  * Runtime wrapper around a relational-core AST expression node. Carries ScopeField metadata (codecId, nullable) so aggregate-like combinators can propagate the input codec onto their result.
6
7
  *
7
- * `refs` records the column-bound binding (`{ table, column }`) when known — the field-proxy populates it for both the namespaced form (`f.user.email` → `ColumnRef`) and the top-level shortcut (`f.email` → `IdentifierRef` + refs metadata). Encode-side dispatch and the `validateParamRefRefs` pass read it via `refsOf(expression)`.
8
+ * `codec` records the column-bound {@link CodecRef} when the field-proxy knows the binding both the namespaced form (`f.user.email` → `ColumnRef`) and the top-level shortcut (`f.email` → `IdentifierRef`) stamp the ref derived from contract storage. `codecOf(expression)` exposes it for operation implementations forwarding the ref to `toExpr`.
8
9
  */
9
10
  var ExpressionImpl = class {
10
11
  ast;
11
12
  returnType;
12
- refs;
13
- constructor(ast, returnType, refs) {
13
+ codec;
14
+ constructor(ast, returnType, codec) {
14
15
  this.ast = ast;
15
16
  this.returnType = returnType;
16
- this.refs = refs;
17
+ this.codec = codec;
17
18
  }
18
19
  buildAst() {
19
20
  return this.ast;
@@ -21,30 +22,11 @@ var ExpressionImpl = class {
21
22
  };
22
23
  //#endregion
23
24
  //#region src/runtime/field-proxy.ts
24
- /**
25
- * For a top-level field name, find the namespace (table alias) that contributed it. When exactly one namespace owns the field, the top-level binding is unambiguously column-bound and we record that `(table, column)` pair on the `ExpressionImpl` so encode-side dispatch (`forColumn`) and the `validateParamRefRefs` pass can find it. The AST stays as `IdentifierRef` to preserve SQL rendering — adapters render top-level
26
- * identifiers without an explicit table qualifier — so this change is metadata-only and produces no SQL drift.
27
- */
28
- function findUniqueNamespaceFor$1(scope, fieldName) {
29
- let found;
30
- for (const [namespace, fields] of Object.entries(scope.namespaces)) if (Object.hasOwn(fields, fieldName)) {
31
- if (found !== void 0) return void 0;
32
- found = namespace;
33
- }
34
- return found;
35
- }
36
25
  function createFieldProxy(scope) {
37
26
  return new Proxy({}, { get(_target, prop) {
38
27
  if (Object.hasOwn(scope.topLevel, prop)) {
39
28
  const topField = scope.topLevel[prop];
40
- if (topField) {
41
- const namespace = findUniqueNamespaceFor$1(scope, prop);
42
- const refs = namespace ? {
43
- table: namespace,
44
- column: prop
45
- } : void 0;
46
- return new ExpressionImpl(IdentifierRef.of(prop), topField, refs);
47
- }
29
+ if (topField) return new ExpressionImpl(IdentifierRef.of(prop), topField, topField.codec);
48
30
  }
49
31
  if (Object.hasOwn(scope.namespaces, prop)) {
50
32
  const nsFields = scope.namespaces[prop];
@@ -56,7 +38,7 @@ function createNamespaceProxy(namespaceName, fields) {
56
38
  return new Proxy({}, { get(_target, prop) {
57
39
  if (Object.hasOwn(fields, prop)) {
58
40
  const field = fields[prop];
59
- if (field) return new ExpressionImpl(ColumnRef.of(namespaceName, prop), field);
41
+ if (field) return new ExpressionImpl(ColumnRef.of(namespaceName, prop), field, field.codec);
60
42
  }
61
43
  } });
62
44
  }
@@ -68,25 +50,17 @@ const BOOL_FIELD = {
68
50
  };
69
51
  const resolve = toExpr;
70
52
  /**
71
- * Resolve a binary-comparison operand into an AST expression, threading the column-bound side's `codecId` + `refs` to the raw-value side.
53
+ * Resolve a binary-comparison operand into an AST expression, threading the column-bound side's {@link CodecRef} to the raw-value side.
72
54
  *
73
- * For `fns.eq(f.email, 'alice@example.com')`, `f.email` is the column-bound expression carrying a `ColumnRef` AST and a `returnType.codecId` (`pg/varchar@1`); the raw string operand has no codec context. By deriving the codec context from the column-bound side and forwarding it via `toExpr(value, codecId, refs)`, the resulting `ParamRef` carries the column refs that encode-side `forColumn` dispatch needs (and that the
74
- * validator pass requires for parameterized codec ids like `pg/varchar@1` with a length parameter).
55
+ * For `fns.eq(f.email, 'alice@example.com')`, `f.email` is the column-bound expression carrying a `ColumnRef` AST and a `CodecRef` derived from contract storage; the raw string operand has no codec context. By deriving the codec context from the column-bound side and forwarding it via `toExpr(value, codec)`, the resulting `ParamRef` carries the `CodecRef` that encode-side dispatch needs to materialise the per-instance codec for parameterized codec ids (`vector(1024)` vs. `vector(1536)`).
75
56
  */
76
- function resolveOperand(operand, otherCodecId, otherRefs) {
57
+ function resolveOperand(operand, otherCodec) {
77
58
  if (isExpressionLike(operand)) return operand.buildAst();
78
- return toExpr(operand, otherCodecId, otherRefs);
59
+ return toExpr(operand, otherCodec);
79
60
  }
80
61
  function isExpressionLike(value) {
81
62
  return typeof value === "object" && value !== null && "buildAst" in value && typeof value.buildAst === "function";
82
63
  }
83
- function operandCodecId(operand) {
84
- if (!isExpressionLike(operand)) return void 0;
85
- return operand.returnType?.codecId;
86
- }
87
- function operandRefs(operand) {
88
- return refsOf(operand);
89
- }
90
64
  /**
91
65
  * Resolves an Expression via `buildAst()`, or wraps a raw value as a `LiteralExpr` — an SQL literal inlined into the query text, not a bound parameter.
92
66
  *
@@ -100,10 +74,8 @@ function boolExpr(astNode) {
100
74
  return new ExpressionImpl(astNode, BOOL_FIELD);
101
75
  }
102
76
  function binaryWithSharedCodec(a, b, build) {
103
- const aCodecId = operandCodecId(a);
104
- const bCodecId = operandCodecId(b);
105
- const aRefs = operandRefs(a);
106
- return build(resolveOperand(a, bCodecId, operandRefs(b)), resolveOperand(b, aCodecId, aRefs));
77
+ const aCodec = codecOf(a);
78
+ return build(resolveOperand(a, codecOf(b)), resolveOperand(b, aCodec));
107
79
  }
108
80
  function eq(a, b) {
109
81
  if (b === null) return boolExpr(NullCheckExpr.isNull(resolve(a)));
@@ -120,11 +92,10 @@ function comparison(a, b, op) {
120
92
  }
121
93
  function inOrNotIn(expr, valuesOrSubquery, op) {
122
94
  const left = expr.buildAst();
123
- const leftCodecId = expr.returnType.codecId;
124
- const leftRefs = refsOf(expr);
95
+ const leftCodec = codecOf(expr);
125
96
  const binaryFn = op === "in" ? BinaryExpr.in : BinaryExpr.notIn;
126
97
  if (Array.isArray(valuesOrSubquery)) {
127
- const refs = valuesOrSubquery.map((v) => resolveOperand(v, leftCodecId, leftRefs));
98
+ const refs = valuesOrSubquery.map((v) => resolveOperand(v, leftCodec));
128
99
  return boolExpr(binaryFn(left, ListExpression.of(refs)));
129
100
  }
130
101
  return boolExpr(binaryFn(left, SubqueryExpr.of(valuesOrSubquery.buildAst())));
@@ -198,6 +169,13 @@ var BuilderBase = class {
198
169
  });
199
170
  }
200
171
  };
172
+ /**
173
+ * Derive the canonical {@link CodecRef} for a `(table, column)` from the builder context's storage. Returns `undefined` when the builder context has no storage attached or when the column is unknown to the contract.
174
+ */
175
+ function codecRefFor(ctx, tableName, columnName) {
176
+ if (!ctx.storage) return void 0;
177
+ return codecRefForStorageColumn(ctx.storage, tableName, columnName);
178
+ }
201
179
  function emptyState(from, scope) {
202
180
  return {
203
181
  from,
@@ -226,17 +204,6 @@ function combineWhereExprs(exprs) {
226
204
  if (exprs.length === 1) return exprs[0];
227
205
  return AndExpr.of(exprs);
228
206
  }
229
- /**
230
- * Same uniqueness rule as the field-proxy's `findUniqueNamespaceFor`: when exactly one namespace owns a top-level field, the binding is unambiguous. Used by `select('col', ...)` to attach `refs` metadata to the resulting `ProjectionItem` while keeping the AST as `IdentifierRef` (so SQL renders unchanged).
231
- */
232
- function findUniqueNamespaceFor(scope, fieldName) {
233
- let found;
234
- for (const [namespace, fields] of Object.entries(scope.namespaces)) if (Object.hasOwn(fields, fieldName)) {
235
- if (found !== void 0) return void 0;
236
- found = namespace;
237
- }
238
- return found;
239
- }
240
207
  function buildSelectAst(state) {
241
208
  const where = combineWhereExprs(state.where);
242
209
  return new SelectAst({
@@ -270,15 +237,21 @@ function buildQueryPlan(ast, ctx) {
270
237
  function buildPlan(state, ctx) {
271
238
  return buildQueryPlan(buildSelectAst(state), ctx);
272
239
  }
273
- function tableToScope(name, table) {
240
+ function tableToScope(alias, table, options) {
241
+ const storage = options?.storage;
242
+ const lookupName = options?.tableName;
274
243
  const fields = {};
275
- for (const [colName, col] of Object.entries(table.columns)) fields[colName] = {
276
- codecId: col.codecId,
277
- nullable: col.nullable
278
- };
244
+ for (const [colName, col] of Object.entries(table.columns)) {
245
+ const codec = storage && lookupName ? codecRefForStorageColumn(storage, lookupName, colName) : void 0;
246
+ fields[colName] = {
247
+ codecId: col.codecId,
248
+ nullable: col.nullable,
249
+ ...codec !== void 0 ? { codec } : {}
250
+ };
251
+ }
279
252
  return {
280
253
  topLevel: { ...fields },
281
- namespaces: { [name]: fields }
254
+ namespaces: { [alias]: fields }
282
255
  };
283
256
  }
284
257
  function mergeScopes(a, b) {
@@ -298,7 +271,8 @@ function nullableScope(scope) {
298
271
  const result = {};
299
272
  for (const [k, v] of Object.entries(tbl)) result[k] = {
300
273
  codecId: v.codecId,
301
- nullable: true
274
+ nullable: true,
275
+ ...v.codec !== void 0 ? { codec: v.codec } : {}
302
276
  };
303
277
  return result;
304
278
  };
@@ -332,12 +306,7 @@ function resolveSelectArgs(args, scope, ctx) {
332
306
  for (const colName of args) {
333
307
  const field = scope.topLevel[colName];
334
308
  if (!field) throw new Error(`Column "${colName}" not found in scope`);
335
- const namespace = findUniqueNamespaceFor(scope, colName);
336
- const refs = namespace ? {
337
- table: namespace,
338
- column: colName
339
- } : void 0;
340
- projections.push(ProjectionItem.of(colName, IdentifierRef.of(colName), field.codecId, refs));
309
+ projections.push(ProjectionItem.of(colName, IdentifierRef.of(colName), field.codec));
341
310
  newRowFields[colName] = field;
342
311
  }
343
312
  return {
@@ -351,7 +320,7 @@ function resolveSelectArgs(args, scope, ctx) {
351
320
  const fns = createAggregateFunctions(ctx.queryOperationTypes);
352
321
  const result = exprFn(createFieldProxy(scope), fns);
353
322
  const field = result.returnType;
354
- projections.push(ProjectionItem.of(alias, result.buildAst(), field.codecId));
323
+ projections.push(ProjectionItem.of(alias, result.buildAst(), field.codec));
355
324
  newRowFields[alias] = field;
356
325
  return {
357
326
  projections,
@@ -364,7 +333,7 @@ function resolveSelectArgs(args, scope, ctx) {
364
333
  const record = callbackFn(createFieldProxy(scope), fns);
365
334
  for (const [key, expr] of Object.entries(record)) {
366
335
  const field = expr.returnType;
367
- projections.push(ProjectionItem.of(key, expr.buildAst(), field.codecId));
336
+ projections.push(ProjectionItem.of(key, expr.buildAst(), field.codec));
368
337
  newRowFields[key] = field;
369
338
  }
370
339
  return {
@@ -583,33 +552,21 @@ var JoinedTablesImpl = class JoinedTablesImpl extends BuilderBase {
583
552
  function buildParamValues(values, table, tableName, op, ctx) {
584
553
  const params = {};
585
554
  for (const [col, value] of Object.entries(values)) {
586
- const column = table.columns[col];
587
- params[col] = ParamRef.of(value, column ? {
588
- codecId: column.codecId,
589
- refs: {
590
- table: tableName,
591
- column: col
592
- }
593
- } : void 0);
555
+ const codec = table.columns[col] ? codecRefFor(ctx, tableName, col) : void 0;
556
+ params[col] = ParamRef.of(value, codec ? { codec } : void 0);
594
557
  }
595
558
  for (const def of ctx.applyMutationDefaults({
596
559
  op,
597
560
  table: tableName,
598
561
  values
599
562
  })) {
600
- const column = table.columns[def.column];
601
- params[def.column] = ParamRef.of(def.value, column ? {
602
- codecId: column.codecId,
603
- refs: {
604
- table: tableName,
605
- column: def.column
606
- }
607
- } : void 0);
563
+ const codec = table.columns[def.column] ? codecRefFor(ctx, tableName, def.column) : void 0;
564
+ params[def.column] = ParamRef.of(def.value, codec ? { codec } : void 0);
608
565
  }
609
566
  return params;
610
567
  }
611
568
  function buildReturningProjections(tableName, columns, rowFields) {
612
- return columns.map((col) => ProjectionItem.of(col, ColumnRef.of(tableName, col), rowFields[col]?.codecId));
569
+ return columns.map((col) => ProjectionItem.of(col, ColumnRef.of(tableName, col), rowFields[col]?.codec));
613
570
  }
614
571
  function evaluateWhere(whereCallback, scope, queryOperationTypes) {
615
572
  return whereCallback(createFieldProxy(scope), createFunctions(queryOperationTypes)).buildAst();
@@ -728,7 +685,10 @@ var TableProxyImpl = class TableProxyImpl extends BuilderBase {
728
685
  super(ctx);
729
686
  this.#tableName = tableName;
730
687
  this.#table = table;
731
- this.#scope = tableToScope(alias, table);
688
+ this.#scope = tableToScope(alias, table, {
689
+ storage: ctx.storage,
690
+ tableName
691
+ });
732
692
  this.#fromSource = TableSource.named(tableName, alias !== tableName ? alias : void 0);
733
693
  }
734
694
  lateralJoin = this._gate({ sql: { lateral: true } }, "lateralJoin", (alias, builder) => {
@@ -783,6 +743,7 @@ function sql(options) {
783
743
  queryOperationTypes: context.queryOperations.entries(),
784
744
  target: context.contract.target ?? "unknown",
785
745
  storageHash: context.contract.storage.storageHash ?? "unknown",
746
+ storage: context.contract.storage,
786
747
  applyMutationDefaults: (options) => context.applyMutationDefaults(options)
787
748
  };
788
749
  return new Proxy({}, { get(_target, prop) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["findUniqueNamespaceFor","#state","#buildLateral","#addLateralJoin","#addJoin","#tableName","#table","#scope","#values","#returningColumns","#rowFields","#setValues","#whereCallbacks","#tableName","#table","#fromSource","#scope","#toJoined"],"sources":["../../src/runtime/expression-impl.ts","../../src/runtime/field-proxy.ts","../../src/runtime/functions.ts","../../src/runtime/builder-base.ts","../../src/runtime/query-impl.ts","../../src/runtime/joined-tables-impl.ts","../../src/runtime/mutation-impl.ts","../../src/runtime/table-proxy-impl.ts","../../src/runtime/sql.ts"],"sourcesContent":["import type { AnyExpression as AstExpression } from '@prisma-next/sql-relational-core/ast';\nimport type { Expression } from '@prisma-next/sql-relational-core/expression';\nimport type { ScopeField } from '../scope';\n\n/**\n * Runtime wrapper around a relational-core AST expression node. Carries ScopeField metadata (codecId, nullable) so aggregate-like combinators can propagate the input codec onto their result.\n *\n * `refs` records the column-bound binding (`{ table, column }`) when known — the field-proxy populates it for both the namespaced form (`f.user.email` → `ColumnRef`) and the top-level shortcut (`f.email` → `IdentifierRef` + refs metadata). Encode-side dispatch and the `validateParamRefRefs` pass read it via `refsOf(expression)`.\n */\nexport class ExpressionImpl<T extends ScopeField = ScopeField> implements Expression<T> {\n private readonly ast: AstExpression;\n readonly returnType: T;\n readonly refs: { readonly table: string; readonly column: string } | undefined;\n\n constructor(\n ast: AstExpression,\n returnType: T,\n refs?: { readonly table: string; readonly column: string },\n ) {\n this.ast = ast;\n this.returnType = returnType;\n this.refs = refs;\n }\n\n buildAst(): AstExpression {\n return this.ast;\n }\n}\n","import { ColumnRef, IdentifierRef } from '@prisma-next/sql-relational-core/ast';\nimport type { FieldProxy } from '../expression';\nimport type { Scope, ScopeTable } from '../scope';\nimport { ExpressionImpl } from './expression-impl';\n\n/**\n * For a top-level field name, find the namespace (table alias) that contributed it. When exactly one namespace owns the field, the top-level binding is unambiguously column-bound and we record that `(table, column)` pair on the `ExpressionImpl` so encode-side dispatch (`forColumn`) and the `validateParamRefRefs` pass can find it. The AST stays as `IdentifierRef` to preserve SQL rendering — adapters render top-level\n * identifiers without an explicit table qualifier — so this change is metadata-only and produces no SQL drift.\n */\nfunction findUniqueNamespaceFor(scope: Scope, fieldName: string): string | undefined {\n let found: string | undefined;\n for (const [namespace, fields] of Object.entries(scope.namespaces)) {\n if (Object.hasOwn(fields, fieldName)) {\n if (found !== undefined) return undefined;\n found = namespace;\n }\n }\n return found;\n}\n\nexport function createFieldProxy<S extends Scope>(scope: S): FieldProxy<S> {\n return new Proxy({} as FieldProxy<S>, {\n get(_target, prop: string) {\n if (Object.hasOwn(scope.topLevel, prop)) {\n const topField = scope.topLevel[prop];\n if (topField) {\n const namespace = findUniqueNamespaceFor(scope, prop);\n const refs = namespace ? { table: namespace, column: prop } : undefined;\n return new ExpressionImpl(IdentifierRef.of(prop), topField, refs);\n }\n }\n\n if (Object.hasOwn(scope.namespaces, prop)) {\n const nsFields = scope.namespaces[prop];\n if (nsFields) return createNamespaceProxy(prop, nsFields);\n }\n\n return undefined;\n },\n });\n}\n\nfunction createNamespaceProxy(\n namespaceName: string,\n fields: ScopeTable,\n): Record<string, ExpressionImpl> {\n return new Proxy({} as Record<string, ExpressionImpl>, {\n get(_target, prop: string) {\n if (Object.hasOwn(fields, prop)) {\n const field = fields[prop];\n if (field) return new ExpressionImpl(ColumnRef.of(namespaceName, prop), field);\n }\n return undefined;\n },\n });\n}\n","import type { SqlOperationEntry } from '@prisma-next/sql-operations';\nimport {\n AggregateExpr,\n AndExpr,\n type AnyExpression as AstExpression,\n BinaryExpr,\n type BinaryOp,\n ExistsExpr,\n ListExpression,\n LiteralExpr,\n NullCheckExpr,\n OrExpr,\n SubqueryExpr,\n} from '@prisma-next/sql-relational-core/ast';\nimport { refsOf, toExpr } from '@prisma-next/sql-relational-core/expression';\nimport type {\n AggregateFunctions,\n AggregateOnlyFunctions,\n BooleanCodecType,\n BuiltinFunctions,\n CodecExpression,\n Expression,\n Functions,\n} from '../expression';\nimport type { QueryContext, ScopeField, Subquery } from '../scope';\nimport { ExpressionImpl } from './expression-impl';\n\ntype CodecTypes = Record<string, { readonly input: unknown }>;\n// Runtime-level ExprOrVal — accepts any codec, any nullability. Concrete codec typing lives on the public BuiltinFunctions surface in `../expression`.\ntype ExprOrVal<CodecId extends string = string, N extends boolean = boolean> = CodecExpression<\n CodecId,\n N,\n CodecTypes\n>;\n\nconst BOOL_FIELD: BooleanCodecType = { codecId: 'pg/bool@1', nullable: false };\n\nconst resolve = toExpr;\n\n/**\n * Resolve a binary-comparison operand into an AST expression, threading the column-bound side's `codecId` + `refs` to the raw-value side.\n *\n * For `fns.eq(f.email, 'alice@example.com')`, `f.email` is the column-bound expression carrying a `ColumnRef` AST and a `returnType.codecId` (`pg/varchar@1`); the raw string operand has no codec context. By deriving the codec context from the column-bound side and forwarding it via `toExpr(value, codecId, refs)`, the resulting `ParamRef` carries the column refs that encode-side `forColumn` dispatch needs (and that the\n * validator pass requires for parameterized codec ids like `pg/varchar@1` with a length parameter).\n */\nfunction resolveOperand(\n operand: ExprOrVal,\n otherCodecId?: string,\n otherRefs?: { table: string; column: string },\n): AstExpression {\n if (isExpressionLike(operand)) return operand.buildAst();\n return toExpr(operand, otherCodecId, otherRefs);\n}\n\nfunction isExpressionLike(\n value: unknown,\n): value is { buildAst: () => AstExpression; returnType?: { codecId: string } } {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'buildAst' in value &&\n typeof (value as { buildAst: unknown }).buildAst === 'function'\n );\n}\n\nfunction operandCodecId(operand: ExprOrVal): string | undefined {\n if (!isExpressionLike(operand)) return undefined;\n return (operand as { returnType?: { codecId: string } }).returnType?.codecId;\n}\n\nfunction operandRefs(operand: ExprOrVal): { table: string; column: string } | undefined {\n return refsOf(operand);\n}\n\n/**\n * Resolves an Expression via `buildAst()`, or wraps a raw value as a `LiteralExpr` — an SQL literal inlined into the query text, not a bound parameter.\n *\n * Used for `and` / `or` operands. The usual operand is an `Expression<bool>` (e.g. the result of `fns.eq`), which this function passes through by calling `buildAst()`. The only time the raw-value branch fires is when the caller writes `fns.and(true, x)` or similar — inlining `TRUE`/`FALSE` literals lets the SQL planner statically simplify `TRUE AND x` to `x`, which it cannot do for an opaque `ParamRef`.\n */\nfunction toLiteralExpr(value: unknown): AstExpression {\n if (\n typeof value === 'object' &&\n value !== null &&\n 'buildAst' in value &&\n typeof (value as { buildAst: unknown }).buildAst === 'function'\n ) {\n return (value as { buildAst(): AstExpression }).buildAst();\n }\n return new LiteralExpr(value);\n}\n\nfunction boolExpr(astNode: AstExpression): ExpressionImpl<BooleanCodecType> {\n return new ExpressionImpl(astNode, BOOL_FIELD);\n}\n\nfunction binaryWithSharedCodec(\n a: ExprOrVal,\n b: ExprOrVal,\n build: (left: AstExpression, right: AstExpression) => AstExpression,\n): AstExpression {\n const aCodecId = operandCodecId(a);\n const bCodecId = operandCodecId(b);\n const aRefs = operandRefs(a);\n const bRefs = operandRefs(b);\n const left = resolveOperand(a, bCodecId, bRefs);\n const right = resolveOperand(b, aCodecId, aRefs);\n return build(left, right);\n}\n\nfunction eq(a: ExprOrVal, b: ExprOrVal): ExpressionImpl<BooleanCodecType> {\n if (b === null) return boolExpr(NullCheckExpr.isNull(resolve(a)));\n if (a === null) return boolExpr(NullCheckExpr.isNull(resolve(b)));\n return boolExpr(binaryWithSharedCodec(a, b, (l, r) => new BinaryExpr('eq', l, r)));\n}\n\nfunction ne(a: ExprOrVal, b: ExprOrVal): ExpressionImpl<BooleanCodecType> {\n if (b === null) return boolExpr(NullCheckExpr.isNotNull(resolve(a)));\n if (a === null) return boolExpr(NullCheckExpr.isNotNull(resolve(b)));\n return boolExpr(binaryWithSharedCodec(a, b, (l, r) => new BinaryExpr('neq', l, r)));\n}\n\nfunction comparison(a: ExprOrVal, b: ExprOrVal, op: BinaryOp): ExpressionImpl<BooleanCodecType> {\n return boolExpr(binaryWithSharedCodec(a, b, (l, r) => new BinaryExpr(op, l, r)));\n}\n\nfunction inOrNotIn(\n expr: Expression<ScopeField>,\n valuesOrSubquery: Subquery<Record<string, ScopeField>> | ExprOrVal[],\n op: 'in' | 'notIn',\n): ExpressionImpl<BooleanCodecType> {\n const left = expr.buildAst();\n const leftCodecId = expr.returnType.codecId;\n const leftRefs = refsOf(expr);\n const binaryFn = op === 'in' ? BinaryExpr.in : BinaryExpr.notIn;\n\n if (Array.isArray(valuesOrSubquery)) {\n const refs = valuesOrSubquery.map((v) => resolveOperand(v, leftCodecId, leftRefs));\n return boolExpr(binaryFn(left, ListExpression.of(refs)));\n }\n return boolExpr(binaryFn(left, SubqueryExpr.of(valuesOrSubquery.buildAst())));\n}\n\nfunction numericAgg(\n fn: 'sum' | 'avg' | 'min' | 'max',\n expr: Expression<ScopeField>,\n): ExpressionImpl<{ codecId: string; nullable: true }> {\n return new ExpressionImpl(AggregateExpr[fn](expr.buildAst()), {\n codecId: expr.returnType.codecId,\n nullable: true as const,\n });\n}\n\nfunction createBuiltinFunctions() {\n return {\n eq: (a: ExprOrVal, b: ExprOrVal) => eq(a, b),\n ne: (a: ExprOrVal, b: ExprOrVal) => ne(a, b),\n gt: (a: ExprOrVal, b: ExprOrVal) => comparison(a, b, 'gt'),\n gte: (a: ExprOrVal, b: ExprOrVal) => comparison(a, b, 'gte'),\n lt: (a: ExprOrVal, b: ExprOrVal) => comparison(a, b, 'lt'),\n lte: (a: ExprOrVal, b: ExprOrVal) => comparison(a, b, 'lte'),\n and: (...exprs: ExprOrVal<'pg/bool@1', boolean>[]) =>\n boolExpr(AndExpr.of(exprs.map(toLiteralExpr))),\n or: (...exprs: ExprOrVal<'pg/bool@1', boolean>[]) =>\n boolExpr(OrExpr.of(exprs.map(toLiteralExpr))),\n exists: (subquery: Subquery<Record<string, ScopeField>>) =>\n boolExpr(ExistsExpr.exists(subquery.buildAst())),\n notExists: (subquery: Subquery<Record<string, ScopeField>>) =>\n boolExpr(ExistsExpr.notExists(subquery.buildAst())),\n in: (\n expr: Expression<ScopeField>,\n valuesOrSubquery: Subquery<Record<string, ScopeField>> | ExprOrVal[],\n ) => inOrNotIn(expr, valuesOrSubquery, 'in'),\n notIn: (\n expr: Expression<ScopeField>,\n valuesOrSubquery: Subquery<Record<string, ScopeField>> | ExprOrVal[],\n ) => inOrNotIn(expr, valuesOrSubquery, 'notIn'),\n } satisfies BuiltinFunctions<CodecTypes>;\n}\n\nfunction createAggregateOnlyFunctions() {\n return {\n count: (expr?: Expression<ScopeField>) => {\n const astExpr = expr ? expr.buildAst() : undefined;\n return new ExpressionImpl(AggregateExpr.count(astExpr), {\n codecId: 'pg/int8@1',\n nullable: false,\n });\n },\n sum: (expr: Expression<ScopeField>) => numericAgg('sum', expr),\n avg: (expr: Expression<ScopeField>) => numericAgg('avg', expr),\n min: (expr: Expression<ScopeField>) => numericAgg('min', expr),\n max: (expr: Expression<ScopeField>) => numericAgg('max', expr),\n } satisfies AggregateOnlyFunctions;\n}\n\nexport function createFunctions<QC extends QueryContext>(\n operations: Readonly<Record<string, SqlOperationEntry>>,\n): Functions<QC> {\n const builtins = createBuiltinFunctions();\n\n return new Proxy({} as Functions<QC>, {\n get(_target, prop: string) {\n const builtin = (builtins as Record<string, unknown>)[prop];\n if (builtin) return builtin;\n\n const op = operations[prop];\n if (op) return op.impl;\n return undefined;\n },\n });\n}\n\nexport function createAggregateFunctions<QC extends QueryContext>(\n operations: Readonly<Record<string, SqlOperationEntry>>,\n): AggregateFunctions<QC> {\n const baseFns = createFunctions<QC>(operations);\n const aggregates = createAggregateOnlyFunctions();\n\n return new Proxy({} as AggregateFunctions<QC>, {\n get(_target, prop: string) {\n const agg = (aggregates as Record<string, unknown>)[prop];\n if (agg) return agg;\n\n return (baseFns as Record<string, unknown>)[prop];\n },\n });\n}\n","import type { PlanMeta } from '@prisma-next/contract/types';\nimport type { StorageTable } from '@prisma-next/sql-contract/types';\nimport type { SqlOperationEntry } from '@prisma-next/sql-operations';\nimport {\n AndExpr,\n type AnyExpression as AstExpression,\n collectOrderedParamRefs,\n IdentifierRef,\n OrderByItem,\n ProjectionItem,\n SelectAst,\n type TableSource,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type {\n AppliedMutationDefault,\n MutationDefaultsOptions,\n} from '@prisma-next/sql-relational-core/query-lane-context';\nimport type {\n AggregateFunctions,\n Expression,\n FieldProxy,\n OrderByOptions,\n OrderByScope,\n} from '../expression';\nimport type {\n GatedMethod,\n MergeScopes,\n NullableScope,\n QueryContext,\n Scope,\n ScopeField,\n ScopeTable,\n} from '../scope';\nimport { createFieldProxy } from './field-proxy';\nimport { createAggregateFunctions, createFunctions } from './functions';\n\nexport type ExprCallback = (fields: FieldProxy<Scope>, fns: unknown) => Expression<ScopeField>;\n\nexport class BuilderBase<Capabilities = unknown> {\n protected readonly ctx: BuilderContext;\n\n constructor(ctx: BuilderContext) {\n this.ctx = ctx;\n }\n\n protected _gate<Req extends Record<string, Record<string, boolean>>, Args extends unknown[], R>(\n required: Req,\n methodName: string,\n method: (...args: Args) => R,\n ): GatedMethod<Capabilities, Req, (...args: Args) => R> {\n return ((...args: Args): R => {\n assertCapability(this.ctx, required, methodName);\n return method(...args);\n }) as GatedMethod<Capabilities, Req, (...args: Args) => R>;\n }\n}\n\nexport interface BuilderState {\n readonly from: TableSource;\n readonly joins: readonly import('@prisma-next/sql-relational-core/ast').JoinAst[];\n readonly projections: readonly ProjectionItem[];\n readonly where: readonly AstExpression[];\n readonly orderBy: readonly OrderByItem[];\n readonly groupBy: readonly AstExpression[];\n readonly having: AstExpression | undefined;\n readonly limit: number | undefined;\n readonly offset: number | undefined;\n readonly distinct: true | undefined;\n readonly distinctOn: readonly AstExpression[] | undefined;\n readonly scope: Scope;\n readonly rowFields: Record<string, ScopeField>;\n}\n\nexport interface BuilderContext {\n readonly capabilities: Record<string, Record<string, boolean>>;\n readonly queryOperationTypes: Readonly<Record<string, SqlOperationEntry>>;\n readonly target: string;\n readonly storageHash: string;\n readonly applyMutationDefaults: (\n options: MutationDefaultsOptions,\n ) => ReadonlyArray<AppliedMutationDefault>;\n}\n\nexport function emptyState(from: TableSource, scope: Scope): BuilderState {\n return {\n from,\n joins: [],\n projections: [],\n where: [],\n orderBy: [],\n groupBy: [],\n having: undefined,\n limit: undefined,\n offset: undefined,\n distinct: undefined,\n distinctOn: undefined,\n scope,\n rowFields: {},\n };\n}\n\nexport function cloneState(state: BuilderState, overrides: Partial<BuilderState>): BuilderState {\n return { ...state, ...overrides };\n}\n\nexport function combineWhereExprs(exprs: readonly AstExpression[]): AstExpression | undefined {\n if (exprs.length === 0) return undefined;\n if (exprs.length === 1) return exprs[0];\n return AndExpr.of(exprs);\n}\n\n/**\n * Same uniqueness rule as the field-proxy's `findUniqueNamespaceFor`: when exactly one namespace owns a top-level field, the binding is unambiguous. Used by `select('col', ...)` to attach `refs` metadata to the resulting `ProjectionItem` while keeping the AST as `IdentifierRef` (so SQL renders unchanged).\n */\nfunction findUniqueNamespaceFor(scope: Scope, fieldName: string): string | undefined {\n let found: string | undefined;\n for (const [namespace, fields] of Object.entries(scope.namespaces)) {\n if (Object.hasOwn(fields, fieldName)) {\n if (found !== undefined) return undefined;\n found = namespace;\n }\n }\n return found;\n}\n\nexport function buildSelectAst(state: BuilderState): SelectAst {\n const where = combineWhereExprs(state.where);\n return new SelectAst({\n from: state.from,\n joins: state.joins.length > 0 ? state.joins : undefined,\n projection: state.projections,\n where,\n orderBy: state.orderBy.length > 0 ? state.orderBy : undefined,\n distinct: state.distinct,\n distinctOn: state.distinctOn && state.distinctOn.length > 0 ? state.distinctOn : undefined,\n groupBy: state.groupBy.length > 0 ? state.groupBy : undefined,\n having: state.having,\n limit: state.limit,\n offset: state.offset,\n selectAllIntent: undefined,\n });\n}\n\nexport function buildQueryPlan<Row = unknown>(\n ast: import('@prisma-next/sql-relational-core/ast').AnyQueryAst,\n ctx: BuilderContext,\n): SqlQueryPlan<Row> {\n const paramValues = collectOrderedParamRefs(ast).map((r) => r.value);\n\n const meta: PlanMeta = Object.freeze({\n target: ctx.target,\n storageHash: ctx.storageHash,\n lane: 'dsl',\n });\n\n return Object.freeze({ ast, params: paramValues, meta });\n}\n\nexport function buildPlan<Row = unknown>(\n state: BuilderState,\n ctx: BuilderContext,\n): SqlQueryPlan<Row> {\n return buildQueryPlan<Row>(buildSelectAst(state), ctx);\n}\n\nexport function tableToScope(name: string, table: StorageTable): Scope {\n const fields: ScopeTable = {};\n for (const [colName, col] of Object.entries(table.columns)) {\n fields[colName] = { codecId: col.codecId, nullable: col.nullable };\n }\n return { topLevel: { ...fields }, namespaces: { [name]: fields } };\n}\n\nexport function mergeScopes<A extends Scope, B extends Scope>(a: A, b: B): MergeScopes<A, B> {\n const topLevel: ScopeTable = {};\n for (const [k, v] of Object.entries(a.topLevel)) {\n if (!(k in b.topLevel)) topLevel[k] = v;\n }\n for (const [k, v] of Object.entries(b.topLevel)) {\n if (!(k in a.topLevel)) topLevel[k] = v;\n }\n return {\n topLevel,\n namespaces: { ...a.namespaces, ...b.namespaces },\n } as MergeScopes<A, B>;\n}\n\nexport function nullableScope<S extends Scope>(scope: S): NullableScope<S> {\n const mkNullable = (tbl: ScopeTable): ScopeTable => {\n const result: ScopeTable = {};\n for (const [k, v] of Object.entries(tbl)) {\n result[k] = { codecId: v.codecId, nullable: true };\n }\n return result;\n };\n const namespaces: Record<string, ScopeTable> = {};\n for (const [k, v] of Object.entries(scope.namespaces)) {\n namespaces[k] = mkNullable(v);\n }\n return { topLevel: mkNullable(scope.topLevel), namespaces } as NullableScope<S>;\n}\n\nexport function orderByScopeOf<S extends Scope, R extends Record<string, ScopeField>>(\n scope: S,\n rowFields: R,\n): OrderByScope<S, R> {\n return {\n topLevel: { ...scope.topLevel, ...rowFields },\n namespaces: scope.namespaces,\n };\n}\n\nexport function assertCapability(\n ctx: BuilderContext,\n required: Record<string, Record<string, boolean>>,\n methodName: string,\n): void {\n for (const [ns, keys] of Object.entries(required)) {\n for (const key of Object.keys(keys)) {\n if (!ctx.capabilities[ns]?.[key]) {\n throw new Error(`${methodName}() requires capability ${ns}.${key}`);\n }\n }\n }\n}\n\nexport function resolveSelectArgs(\n args: unknown[],\n scope: Scope,\n ctx: BuilderContext,\n): { projections: ProjectionItem[]; newRowFields: Record<string, ScopeField> } {\n const projections: ProjectionItem[] = [];\n const newRowFields: Record<string, ScopeField> = {};\n\n if (args.length === 0) return { projections, newRowFields };\n\n if (typeof args[0] === 'string' && (args.length === 1 || typeof args[1] !== 'function')) {\n for (const colName of args as string[]) {\n const field = scope.topLevel[colName];\n if (!field) throw new Error(`Column \"${colName}\" not found in scope`);\n const namespace = findUniqueNamespaceFor(scope, colName);\n const refs = namespace ? { table: namespace, column: colName } : undefined;\n projections.push(ProjectionItem.of(colName, IdentifierRef.of(colName), field.codecId, refs));\n newRowFields[colName] = field;\n }\n return { projections, newRowFields };\n }\n\n if (typeof args[0] === 'string' && typeof args[1] === 'function') {\n const alias = args[0] as string;\n const exprFn = args[1] as (\n f: FieldProxy<Scope>,\n fns: AggregateFunctions<QueryContext>,\n ) => Expression<ScopeField>;\n const fns = createAggregateFunctions(ctx.queryOperationTypes);\n const result = exprFn(createFieldProxy(scope), fns);\n const field = result.returnType;\n projections.push(ProjectionItem.of(alias, result.buildAst(), field.codecId));\n newRowFields[alias] = field;\n return { projections, newRowFields };\n }\n\n if (typeof args[0] === 'function') {\n const callbackFn = args[0] as (\n f: FieldProxy<Scope>,\n fns: AggregateFunctions<QueryContext>,\n ) => Record<string, Expression<ScopeField>>;\n const fns = createAggregateFunctions(ctx.queryOperationTypes);\n const record = callbackFn(createFieldProxy(scope), fns);\n for (const [key, expr] of Object.entries(record)) {\n const field = expr.returnType;\n projections.push(ProjectionItem.of(key, expr.buildAst(), field.codecId));\n newRowFields[key] = field;\n }\n return { projections, newRowFields };\n }\n\n throw new Error('Invalid .select() arguments');\n}\n\nexport function resolveOrderBy(\n arg: unknown,\n options: OrderByOptions | undefined,\n scope: Scope,\n rowFields: Record<string, ScopeField>,\n ctx: BuilderContext,\n useAggregateFns: boolean,\n): OrderByItem {\n const dir = options?.direction ?? 'asc';\n\n if (typeof arg === 'string') {\n const combined = orderByScopeOf(scope, rowFields);\n if (!(arg in combined.topLevel))\n throw new Error(`Column \"${arg}\" not found in scope for orderBy`);\n const expr = IdentifierRef.of(arg);\n return dir === 'asc' ? OrderByItem.asc(expr) : OrderByItem.desc(expr);\n }\n\n if (typeof arg === 'function') {\n const combined = orderByScopeOf(scope, rowFields);\n const fns = useAggregateFns\n ? createAggregateFunctions(ctx.queryOperationTypes)\n : createFunctions(ctx.queryOperationTypes);\n const result = (arg as ExprCallback)(createFieldProxy(combined), fns);\n return dir === 'asc' ? OrderByItem.asc(result.buildAst()) : OrderByItem.desc(result.buildAst());\n }\n\n throw new Error('Invalid orderBy argument');\n}\n\nexport function resolveGroupBy(\n args: unknown[],\n scope: Scope,\n rowFields: Record<string, ScopeField>,\n ctx: BuilderContext,\n): AstExpression[] {\n if (typeof args[0] === 'string') {\n const combined = orderByScopeOf(scope, rowFields);\n return (args as string[]).map((colName) => {\n if (!(colName in combined.topLevel))\n throw new Error(`Column \"${colName}\" not found in scope for groupBy`);\n return IdentifierRef.of(colName);\n });\n }\n\n if (typeof args[0] === 'function') {\n const combined = orderByScopeOf(scope, rowFields);\n const fns = createFunctions(ctx.queryOperationTypes);\n const result = (args[0] as ExprCallback)(createFieldProxy(combined), fns);\n return [result.buildAst()];\n }\n\n throw new Error('Invalid groupBy arguments');\n}\n\nexport function resolveDistinctOn(\n args: unknown[],\n scope: Scope,\n rowFields: Record<string, ScopeField>,\n ctx: BuilderContext,\n): AstExpression[] {\n if (args.length === 1 && typeof args[0] === 'function') {\n const combined = orderByScopeOf(scope, rowFields);\n const fns = createFunctions(ctx.queryOperationTypes);\n const result = (args[0] as ExprCallback)(createFieldProxy(combined), fns);\n return [result.buildAst()];\n }\n const combined = orderByScopeOf(scope, rowFields);\n return (args as string[]).map((colName) => {\n if (!(colName in combined.topLevel))\n throw new Error(`Column \"${colName}\" not found in scope for distinctOn`);\n return IdentifierRef.of(colName);\n });\n}\n","import { DerivedTableSource, type SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type {\n AggregateFunctions,\n BooleanCodecType,\n Expression,\n ExpressionBuilder,\n ExtractScopeFields,\n FieldProxy,\n Functions,\n OrderByOptions,\n OrderByScope,\n WithField,\n WithFields,\n} from '../expression';\nimport type { ResolveRow } from '../resolve';\nimport type {\n Expand,\n JoinOuterScope,\n JoinSource,\n QueryContext,\n Scope,\n ScopeField,\n // biome-ignore lint/correctness/noUnusedImports: used in `declare` property\n SubqueryMarker,\n} from '../scope';\nimport type { GroupedQuery } from '../types/grouped-query';\nimport type { SelectQuery } from '../types/select-query';\nimport {\n BuilderBase,\n type BuilderContext,\n type BuilderState,\n buildPlan,\n buildSelectAst,\n cloneState,\n orderByScopeOf,\n resolveDistinctOn,\n resolveGroupBy,\n resolveOrderBy,\n resolveSelectArgs,\n} from './builder-base';\nimport { createFieldProxy } from './field-proxy';\nimport { createAggregateFunctions, createFunctions } from './functions';\n\nabstract class QueryBase<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n> extends BuilderBase<QC['capabilities']> {\n protected readonly state: BuilderState;\n\n constructor(state: BuilderState, ctx: BuilderContext) {\n super(ctx);\n this.state = state;\n }\n\n protected abstract clone(state: BuilderState): this;\n\n distinctOn = this._gate(\n { postgres: { distinctOn: true } },\n 'distinctOn',\n (...args: unknown[]) => {\n const exprs = resolveDistinctOn(args, this.state.scope, this.state.rowFields, this.ctx);\n return this.clone(\n cloneState(this.state, {\n distinctOn: [...(this.state.distinctOn ?? []), ...exprs],\n }),\n );\n },\n );\n\n limit(count: number): this {\n return this.clone(cloneState(this.state, { limit: count }));\n }\n\n offset(count: number): this {\n return this.clone(cloneState(this.state, { offset: count }));\n }\n\n distinct(): this {\n return this.clone(cloneState(this.state, { distinct: true }));\n }\n\n groupBy(\n ...fields: ((keyof RowType | keyof AvailableScope['topLevel']) & string)[]\n ): GroupedQuery<QC, AvailableScope, RowType>;\n groupBy(\n expr: (\n fields: FieldProxy<OrderByScope<AvailableScope, RowType>>,\n fns: Functions<QC>,\n ) => Expression<ScopeField>,\n ): GroupedQuery<QC, AvailableScope, RowType>;\n groupBy(...args: unknown[]): unknown {\n const exprs = resolveGroupBy(args, this.state.scope, this.state.rowFields, this.ctx);\n return new GroupedQueryImpl<QC, AvailableScope, RowType>(\n cloneState(this.state, { groupBy: [...this.state.groupBy, ...exprs] }),\n this.ctx,\n );\n }\n\n as<Alias extends string>(alias: Alias): JoinSource<RowType, Alias> {\n const ast = buildSelectAst(this.state);\n const derivedSource = DerivedTableSource.as(alias, ast);\n const scope = {\n topLevel: this.state.rowFields as RowType,\n namespaces: { [alias]: this.state.rowFields } as Record<Alias, RowType>,\n };\n return {\n getJoinOuterScope: () => scope,\n buildAst: () => derivedSource,\n\n // `as unknown` is necessary, because JoinOuterScope is a phantom type-only property that does not exist at runtime\n } satisfies Omit<JoinSource<RowType, Alias>, typeof JoinOuterScope> as unknown as JoinSource<\n RowType,\n Alias\n >;\n }\n\n getRowFields(): Record<string, ScopeField> {\n return this.state.rowFields;\n }\n\n buildAst(): SelectAst {\n return buildSelectAst(this.state);\n }\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n return buildPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(\n this.state,\n this.ctx,\n );\n }\n}\n\nexport class SelectQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends QueryBase<QC, AvailableScope, RowType>\n implements SelectQuery<QC, AvailableScope, RowType>\n{\n declare readonly [SubqueryMarker]: RowType;\n\n protected clone(state: BuilderState): this {\n return new SelectQueryImpl<QC, AvailableScope, RowType>(state, this.ctx) as this;\n }\n\n select<Columns extends (keyof AvailableScope['topLevel'] & string)[]>(\n ...columns: Columns\n ): SelectQuery<QC, AvailableScope, WithFields<RowType, AvailableScope['topLevel'], Columns>>;\n select<Alias extends string, Field extends ScopeField>(\n alias: Alias,\n expr: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Expression<Field>,\n ): SelectQuery<QC, AvailableScope, WithField<RowType, Field, Alias>>;\n select<Result extends Record<string, Expression<ScopeField>>>(\n callback: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Result,\n ): SelectQuery<QC, AvailableScope, Expand<RowType & ExtractScopeFields<Result>>>;\n select(...args: unknown[]): unknown {\n const { projections, newRowFields } = resolveSelectArgs(args, this.state.scope, this.ctx);\n return new SelectQueryImpl(\n cloneState(this.state, {\n projections: [...this.state.projections, ...projections],\n rowFields: { ...this.state.rowFields, ...newRowFields },\n }),\n this.ctx,\n );\n }\n\n where(expr: ExpressionBuilder<AvailableScope, QC>): SelectQuery<QC, AvailableScope, RowType> {\n const fieldProxy = createFieldProxy(this.state.scope);\n const fns = createFunctions<QC>(this.ctx.queryOperationTypes);\n const result = (expr as ExpressionBuilder<Scope, QueryContext>)(fieldProxy, fns as never);\n return new SelectQueryImpl(\n cloneState(this.state, {\n where: [...this.state.where, result.buildAst()],\n }),\n this.ctx,\n );\n }\n\n orderBy(\n field: (keyof RowType | keyof AvailableScope['topLevel']) & string,\n options?: OrderByOptions,\n ): SelectQuery<QC, AvailableScope, RowType>;\n orderBy(\n expr: (\n fields: FieldProxy<OrderByScope<AvailableScope, RowType>>,\n fns: Functions<QC>,\n ) => Expression<ScopeField>,\n options?: OrderByOptions,\n ): SelectQuery<QC, AvailableScope, RowType>;\n orderBy(arg: unknown, options?: OrderByOptions): unknown {\n const item = resolveOrderBy(\n arg,\n options,\n this.state.scope,\n this.state.rowFields,\n this.ctx,\n false,\n );\n return this.clone(cloneState(this.state, { orderBy: [...this.state.orderBy, item] }));\n }\n}\n\nexport class GroupedQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends QueryBase<QC, AvailableScope, RowType>\n implements GroupedQuery<QC, AvailableScope, RowType>\n{\n declare readonly [SubqueryMarker]: RowType;\n\n protected clone(state: BuilderState): this {\n return new GroupedQueryImpl<QC, AvailableScope, RowType>(state, this.ctx) as this;\n }\n\n having(\n expr: (\n fields: FieldProxy<OrderByScope<AvailableScope, RowType>>,\n fns: AggregateFunctions<QC>,\n ) => Expression<BooleanCodecType>,\n ): GroupedQuery<QC, AvailableScope, RowType> {\n const combined = orderByScopeOf(\n this.state.scope as AvailableScope,\n this.state.rowFields as RowType,\n );\n const fns = createAggregateFunctions(this.ctx.queryOperationTypes);\n const result = expr(createFieldProxy(combined), fns);\n return new GroupedQueryImpl(cloneState(this.state, { having: result.buildAst() }), this.ctx);\n }\n\n orderBy(\n field: (keyof RowType | keyof AvailableScope['topLevel']) & string,\n options?: OrderByOptions,\n ): GroupedQuery<QC, AvailableScope, RowType>;\n orderBy(\n expr: (\n fields: FieldProxy<OrderByScope<AvailableScope, RowType>>,\n fns: AggregateFunctions<QC>,\n ) => Expression<ScopeField>,\n options?: OrderByOptions,\n ): GroupedQuery<QC, AvailableScope, RowType>;\n orderBy(arg: unknown, options?: OrderByOptions): unknown {\n const item = resolveOrderBy(\n arg,\n options,\n this.state.scope,\n this.state.rowFields,\n this.ctx,\n true,\n );\n return this.clone(cloneState(this.state, { orderBy: [...this.state.orderBy, item] }));\n }\n}\n","import {\n AndExpr,\n DerivedTableSource,\n JoinAst,\n type TableSource,\n} from '@prisma-next/sql-relational-core/ast';\nimport type {\n AggregateFunctions,\n Expression,\n ExpressionBuilder,\n ExtractScopeFields,\n FieldProxy,\n WithField,\n WithFields,\n} from '../expression';\nimport type {\n EmptyRow,\n Expand,\n JoinOuterScope,\n JoinSource,\n MergeScopes,\n NullableScope,\n QueryContext,\n Scope,\n ScopeField,\n ScopeTable,\n Subquery,\n} from '../scope';\nimport type { JoinedTables } from '../types/joined-tables';\nimport type { SelectQuery } from '../types/select-query';\nimport type { LateralBuilder } from '../types/shared';\nimport {\n BuilderBase,\n type BuilderContext,\n type BuilderState,\n cloneState,\n emptyState,\n mergeScopes,\n nullableScope,\n resolveSelectArgs,\n} from './builder-base';\nimport { createFieldProxy } from './field-proxy';\nimport { createFunctions } from './functions';\nimport { SelectQueryImpl } from './query-impl';\n\nexport class JoinedTablesImpl<QC extends QueryContext, AvailableScope extends Scope>\n extends BuilderBase<QC['capabilities']>\n implements JoinedTables<QC, AvailableScope>\n{\n readonly #state: BuilderState;\n\n constructor(state: BuilderState, ctx: BuilderContext) {\n super(ctx);\n this.#state = state;\n }\n\n lateralJoin = this._gate(\n { sql: { lateral: true } },\n 'lateralJoin',\n <Alias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: Alias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<AvailableScope, { topLevel: LateralRow; namespaces: Record<Alias, LateralRow> }>\n > => {\n const { derivedSource, lateralScope } = this.#buildLateral(alias, builder);\n const resultScope = mergeScopes(\n this.#state.scope as AvailableScope,\n lateralScope as { topLevel: LateralRow; namespaces: Record<Alias, LateralRow> },\n );\n return this.#addLateralJoin('inner', resultScope, derivedSource);\n },\n ) as JoinedTables<QC, AvailableScope>['lateralJoin'];\n\n outerLateralJoin = this._gate(\n { sql: { lateral: true } },\n 'outerLateralJoin',\n <Alias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: Alias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<\n AvailableScope,\n NullableScope<{ topLevel: LateralRow; namespaces: Record<Alias, LateralRow> }>\n >\n > => {\n const { derivedSource, lateralScope } = this.#buildLateral(alias, builder);\n const resultScope = mergeScopes(\n this.#state.scope as AvailableScope,\n nullableScope(\n lateralScope as { topLevel: LateralRow; namespaces: Record<Alias, LateralRow> },\n ),\n );\n return this.#addLateralJoin('left', resultScope, derivedSource);\n },\n ) as JoinedTables<QC, AvailableScope>['outerLateralJoin'];\n\n select<Columns extends (keyof AvailableScope['topLevel'] & string)[]>(\n ...columns: Columns\n ): SelectQuery<QC, AvailableScope, WithFields<EmptyRow, AvailableScope['topLevel'], Columns>>;\n select<Alias extends string, Field extends ScopeField>(\n alias: Alias,\n expr: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Expression<Field>,\n ): SelectQuery<QC, AvailableScope, WithField<EmptyRow, Field, Alias>>;\n select<Result extends Record<string, Expression<ScopeField>>>(\n callback: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Result,\n ): SelectQuery<QC, AvailableScope, Expand<ExtractScopeFields<Result>>>;\n select(...args: unknown[]): unknown {\n const { projections, newRowFields } = resolveSelectArgs(args, this.#state.scope, this.ctx);\n return new SelectQueryImpl<QC, AvailableScope>(\n cloneState(this.#state, {\n projections: [...this.#state.projections, ...projections],\n rowFields: { ...this.#state.rowFields, ...newRowFields },\n }),\n this.ctx,\n );\n }\n\n innerJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>> {\n const targetScope = mergeScopes(\n this.#state.scope as AvailableScope,\n other.getJoinOuterScope() as Other[typeof JoinOuterScope],\n );\n return this.#addJoin(other, 'inner', targetScope, on);\n }\n\n outerLeftJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<AvailableScope, NullableScope<Other[typeof JoinOuterScope]>>> {\n const targetScope = mergeScopes(\n this.#state.scope as AvailableScope,\n nullableScope(other.getJoinOuterScope() as Other[typeof JoinOuterScope]),\n );\n return this.#addJoin(other, 'left', targetScope, on);\n }\n\n outerRightJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<NullableScope<AvailableScope>, Other[typeof JoinOuterScope]>> {\n const targetScope = mergeScopes(\n nullableScope(this.#state.scope as AvailableScope),\n other.getJoinOuterScope() as Other[typeof JoinOuterScope],\n );\n return this.#addJoin(other, 'right', targetScope, on);\n }\n\n outerFullJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<\n QC,\n MergeScopes<NullableScope<AvailableScope>, NullableScope<Other[typeof JoinOuterScope]>>\n > {\n const targetScope = mergeScopes(\n nullableScope(this.#state.scope as AvailableScope),\n nullableScope(other.getJoinOuterScope() as Other[typeof JoinOuterScope]),\n );\n return this.#addJoin(other, 'full', targetScope, on);\n }\n\n #addJoin<Other extends JoinSource<ScopeTable, string | never>, ResultScope extends Scope>(\n other: Other,\n joinType: 'inner' | 'left' | 'right' | 'full',\n resultScope: ResultScope,\n onExpr: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, ResultScope> {\n const fieldProxy = createFieldProxy(\n mergeScopes(\n this.#state.scope as AvailableScope,\n other.getJoinOuterScope() as Other[typeof JoinOuterScope],\n ),\n ) as FieldProxy<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>>;\n const fns = createFunctions<QC>(this.ctx.queryOperationTypes);\n const onResult = onExpr(fieldProxy, fns);\n const joinAst = new JoinAst(joinType, other.buildAst(), onResult.buildAst());\n\n return new JoinedTablesImpl(\n cloneState(this.#state, {\n joins: [...this.#state.joins, joinAst],\n scope: resultScope,\n }),\n this.ctx,\n );\n }\n\n #buildLateral(\n alias: string,\n builderFn: (\n lateral: LateralBuilder<QC, AvailableScope>,\n ) => Subquery<Record<string, ScopeField>>,\n ) {\n const lateralBuilder: LateralBuilder<QC, AvailableScope> = {\n from: (other) => {\n const otherScope = other.getJoinOuterScope();\n const parentMerged = mergeScopes(this.#state.scope, otherScope);\n return new SelectQueryImpl(\n emptyState(other.buildAst() as TableSource, parentMerged),\n this.ctx,\n ) as unknown as SelectQuery<QC, AvailableScope, EmptyRow>;\n },\n };\n\n const subquery = builderFn(lateralBuilder);\n const subqueryAst = subquery.buildAst();\n const derivedSource = DerivedTableSource.as(alias, subqueryAst);\n const subqueryRowFields: ScopeTable = subquery.getRowFields();\n const lateralScope: Scope = {\n topLevel: subqueryRowFields,\n namespaces: { [alias]: subqueryRowFields },\n };\n\n return { derivedSource, lateralScope };\n }\n\n #addLateralJoin<ResultScope extends Scope>(\n joinType: 'inner' | 'left',\n resultScope: ResultScope,\n derivedSource: DerivedTableSource,\n ): JoinedTables<QC, ResultScope> {\n const onExpr = AndExpr.of([]);\n const joinAst = new JoinAst(joinType, derivedSource, onExpr, true);\n\n return new JoinedTablesImpl(\n cloneState(this.#state, {\n joins: [...this.#state.joins, joinAst],\n scope: resultScope,\n }),\n this.ctx,\n );\n }\n}\n","import type { StorageTable } from '@prisma-next/sql-contract/types';\nimport {\n type AnyExpression as AstExpression,\n ColumnRef,\n DeleteAst,\n InsertAst,\n ParamRef,\n ProjectionItem,\n TableSource,\n UpdateAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type { MutationDefaultsOp } from '@prisma-next/sql-relational-core/query-lane-context';\nimport type { ExpressionBuilder } from '../expression';\nimport type { ResolveRow } from '../resolve';\nimport type { QueryContext, Scope, ScopeField } from '../scope';\nimport type {\n DeleteQuery,\n InsertQuery,\n ReturningCapability,\n UpdateQuery,\n} from '../types/mutation-query';\nimport {\n BuilderBase,\n type BuilderContext,\n buildQueryPlan,\n combineWhereExprs,\n} from './builder-base';\nimport { createFieldProxy } from './field-proxy';\nimport { createFunctions } from './functions';\n\ntype WhereCallback = ExpressionBuilder<Scope, QueryContext>;\n\nfunction buildParamValues(\n values: Record<string, unknown>,\n table: StorageTable,\n tableName: string,\n op: MutationDefaultsOp,\n ctx: BuilderContext,\n): Record<string, ParamRef> {\n const params: Record<string, ParamRef> = {};\n for (const [col, value] of Object.entries(values)) {\n const column = table.columns[col];\n params[col] = ParamRef.of(\n value,\n column ? { codecId: column.codecId, refs: { table: tableName, column: col } } : undefined,\n );\n }\n for (const def of ctx.applyMutationDefaults({ op, table: tableName, values })) {\n const column = table.columns[def.column];\n params[def.column] = ParamRef.of(\n def.value,\n column\n ? { codecId: column.codecId, refs: { table: tableName, column: def.column } }\n : undefined,\n );\n }\n return params;\n}\n\nfunction buildReturningProjections(\n tableName: string,\n columns: string[],\n rowFields: Record<string, ScopeField>,\n): ProjectionItem[] {\n return columns.map((col) =>\n ProjectionItem.of(col, ColumnRef.of(tableName, col), rowFields[col]?.codecId),\n );\n}\n\nfunction evaluateWhere(\n whereCallback: WhereCallback,\n scope: Scope,\n queryOperationTypes: BuilderContext['queryOperationTypes'],\n): AstExpression {\n const fieldProxy = createFieldProxy(scope);\n const fns = createFunctions(queryOperationTypes);\n const result = whereCallback(fieldProxy, fns as never);\n return result.buildAst();\n}\n\nexport class InsertQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends BuilderBase<QC['capabilities']>\n implements InsertQuery<QC, AvailableScope, RowType>\n{\n readonly #tableName: string;\n readonly #table: StorageTable;\n readonly #scope: Scope;\n readonly #values: Record<string, unknown>;\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n\n constructor(\n tableName: string,\n table: StorageTable,\n scope: Scope,\n values: Record<string, unknown>,\n ctx: BuilderContext,\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n ) {\n super(ctx);\n this.#tableName = tableName;\n this.#table = table;\n this.#scope = scope;\n this.#values = values;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n }\n\n returning = this._gate<ReturningCapability, string[], InsertQuery<QC, AvailableScope, never>>(\n { sql: { returning: true } },\n 'returning',\n (...columns: string[]) => {\n const newRowFields: Record<string, ScopeField> = {};\n for (const col of columns) {\n const field = this.#scope.topLevel[col];\n if (!field) throw new Error(`Column \"${col}\" not found in scope`);\n newRowFields[col] = field;\n }\n return new InsertQueryImpl(\n this.#tableName,\n this.#table,\n this.#scope,\n this.#values,\n this.ctx,\n columns,\n newRowFields,\n ) as unknown as InsertQuery<QC, AvailableScope, never>;\n },\n );\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n const paramValues = buildParamValues(\n this.#values,\n this.#table,\n this.#tableName,\n 'create',\n this.ctx,\n );\n\n let ast = InsertAst.into(TableSource.named(this.#tableName)).withValues(paramValues);\n\n if (this.#returningColumns.length > 0) {\n ast = ast.withReturning(\n buildReturningProjections(this.#tableName, this.#returningColumns, this.#rowFields),\n );\n }\n\n return buildQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(\n ast,\n this.ctx,\n );\n }\n}\n\nexport class UpdateQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends BuilderBase<QC['capabilities']>\n implements UpdateQuery<QC, AvailableScope, RowType>\n{\n readonly #tableName: string;\n readonly #table: StorageTable;\n readonly #scope: Scope;\n readonly #setValues: Record<string, unknown>;\n readonly #whereCallbacks: readonly WhereCallback[];\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n\n constructor(\n tableName: string,\n table: StorageTable,\n scope: Scope,\n setValues: Record<string, unknown>,\n ctx: BuilderContext,\n whereCallbacks: readonly WhereCallback[] = [],\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n ) {\n super(ctx);\n this.#tableName = tableName;\n this.#table = table;\n this.#scope = scope;\n this.#setValues = setValues;\n this.#whereCallbacks = whereCallbacks;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n }\n\n where(expr: ExpressionBuilder<AvailableScope, QC>): UpdateQuery<QC, AvailableScope, RowType> {\n return new UpdateQueryImpl(\n this.#tableName,\n this.#table,\n this.#scope,\n this.#setValues,\n this.ctx,\n [...this.#whereCallbacks, expr as unknown as WhereCallback],\n this.#returningColumns,\n this.#rowFields,\n );\n }\n\n returning = this._gate<ReturningCapability, string[], UpdateQuery<QC, AvailableScope, never>>(\n { sql: { returning: true } },\n 'returning',\n (...columns: string[]) => {\n const newRowFields: Record<string, ScopeField> = {};\n for (const col of columns) {\n const field = this.#scope.topLevel[col];\n if (!field) throw new Error(`Column \"${col}\" not found in scope`);\n newRowFields[col] = field;\n }\n return new UpdateQueryImpl(\n this.#tableName,\n this.#table,\n this.#scope,\n this.#setValues,\n this.ctx,\n this.#whereCallbacks,\n columns,\n newRowFields,\n ) as unknown as UpdateQuery<QC, AvailableScope, never>;\n },\n );\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n const setParams = buildParamValues(\n this.#setValues,\n this.#table,\n this.#tableName,\n 'update',\n this.ctx,\n );\n\n const whereExpr = combineWhereExprs(\n this.#whereCallbacks.map((cb) =>\n evaluateWhere(cb, this.#scope, this.ctx.queryOperationTypes),\n ),\n );\n\n let ast = UpdateAst.table(TableSource.named(this.#tableName))\n .withSet(setParams)\n .withWhere(whereExpr);\n\n if (this.#returningColumns.length > 0) {\n ast = ast.withReturning(\n buildReturningProjections(this.#tableName, this.#returningColumns, this.#rowFields),\n );\n }\n\n return buildQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(\n ast,\n this.ctx,\n );\n }\n}\n\nexport class DeleteQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends BuilderBase<QC['capabilities']>\n implements DeleteQuery<QC, AvailableScope, RowType>\n{\n readonly #tableName: string;\n readonly #scope: Scope;\n readonly #whereCallbacks: readonly WhereCallback[];\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n\n constructor(\n tableName: string,\n scope: Scope,\n ctx: BuilderContext,\n whereCallbacks: readonly WhereCallback[] = [],\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n ) {\n super(ctx);\n this.#tableName = tableName;\n this.#scope = scope;\n this.#whereCallbacks = whereCallbacks;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n }\n\n where(expr: ExpressionBuilder<AvailableScope, QC>): DeleteQuery<QC, AvailableScope, RowType> {\n return new DeleteQueryImpl(\n this.#tableName,\n this.#scope,\n this.ctx,\n [...this.#whereCallbacks, expr as unknown as WhereCallback],\n this.#returningColumns,\n this.#rowFields,\n );\n }\n\n returning = this._gate<ReturningCapability, string[], DeleteQuery<QC, AvailableScope, never>>(\n { sql: { returning: true } },\n 'returning',\n (...columns: string[]) => {\n const newRowFields: Record<string, ScopeField> = {};\n for (const col of columns) {\n const field = this.#scope.topLevel[col];\n if (!field) throw new Error(`Column \"${col}\" not found in scope`);\n newRowFields[col] = field;\n }\n return new DeleteQueryImpl(\n this.#tableName,\n this.#scope,\n this.ctx,\n this.#whereCallbacks,\n columns,\n newRowFields,\n ) as unknown as DeleteQuery<QC, AvailableScope, never>;\n },\n );\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n const whereExpr = combineWhereExprs(\n this.#whereCallbacks.map((cb) =>\n evaluateWhere(cb, this.#scope, this.ctx.queryOperationTypes),\n ),\n );\n\n let ast = DeleteAst.from(TableSource.named(this.#tableName)).withWhere(whereExpr);\n\n if (this.#returningColumns.length > 0) {\n ast = ast.withReturning(\n buildReturningProjections(this.#tableName, this.#returningColumns, this.#rowFields),\n );\n }\n\n return buildQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(\n ast,\n this.ctx,\n );\n }\n}\n","import type { StorageTable } from '@prisma-next/sql-contract/types';\nimport { type AnyFromSource, TableSource } from '@prisma-next/sql-relational-core/ast';\nimport type {\n AggregateFunctions,\n Expression,\n ExpressionBuilder,\n ExtractScopeFields,\n FieldProxy,\n WithField,\n WithFields,\n} from '../expression';\nimport type {\n EmptyRow,\n Expand,\n JoinOuterScope,\n JoinSource,\n MergeScopes,\n NullableScope,\n QueryContext,\n RebindScope,\n Scope,\n ScopeField,\n ScopeTable,\n StorageTableToScopeTable,\n Subquery,\n} from '../scope';\nimport type { TableProxyContract } from '../types/db';\nimport type { JoinedTables } from '../types/joined-tables';\nimport type { DeleteQuery, InsertQuery, UpdateQuery } from '../types/mutation-query';\nimport type { SelectQuery } from '../types/select-query';\nimport type { LateralBuilder } from '../types/shared';\nimport type { TableProxy } from '../types/table-proxy';\nimport { BuilderBase, type BuilderContext, emptyState, tableToScope } from './builder-base';\nimport { JoinedTablesImpl } from './joined-tables-impl';\nimport { DeleteQueryImpl, InsertQueryImpl, UpdateQueryImpl } from './mutation-impl';\nimport { SelectQueryImpl } from './query-impl';\n\nexport class TableProxyImpl<\n C extends TableProxyContract,\n Name extends string & keyof C['storage']['tables'],\n Alias extends string,\n AvailableScope extends Scope,\n QC extends QueryContext,\n >\n extends BuilderBase<C['capabilities']>\n implements TableProxy<C, Name, Alias, AvailableScope, QC>\n{\n declare readonly [JoinOuterScope]: JoinSource<\n StorageTableToScopeTable<C['storage']['tables'][Name]>,\n Alias\n >[typeof JoinOuterScope];\n\n readonly #tableName: string;\n readonly #table: StorageTable;\n readonly #fromSource: TableSource;\n readonly #scope: Scope;\n\n constructor(tableName: string, table: StorageTable, alias: string, ctx: BuilderContext) {\n super(ctx);\n this.#tableName = tableName;\n this.#table = table;\n this.#scope = tableToScope(alias, table);\n this.#fromSource = TableSource.named(tableName, alias !== tableName ? alias : undefined);\n }\n\n lateralJoin = this._gate(\n { sql: { lateral: true } },\n 'lateralJoin',\n <LAlias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: LAlias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<AvailableScope, { topLevel: LateralRow; namespaces: Record<LAlias, LateralRow> }>\n > => {\n return this.#toJoined().lateralJoin(alias, builder);\n },\n ) as TableProxy<C, Name, Alias, AvailableScope, QC>['lateralJoin'];\n\n outerLateralJoin = this._gate(\n { sql: { lateral: true } },\n 'outerLateralJoin',\n <LAlias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: LAlias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<\n AvailableScope,\n NullableScope<{ topLevel: LateralRow; namespaces: Record<LAlias, LateralRow> }>\n >\n > => {\n return this.#toJoined().outerLateralJoin(alias, builder);\n },\n ) as TableProxy<C, Name, Alias, AvailableScope, QC>['outerLateralJoin'];\n\n getJoinOuterScope(): Scope {\n return this.#scope;\n }\n\n buildAst(): AnyFromSource {\n return this.#fromSource;\n }\n\n as<NewAlias extends string>(\n newAlias: NewAlias,\n ): TableProxy<C, Name, NewAlias, RebindScope<AvailableScope, Alias, NewAlias>> {\n return new TableProxyImpl(this.#tableName, this.#table, newAlias, this.ctx);\n }\n\n select<Columns extends (keyof AvailableScope['topLevel'] & string)[]>(\n ...columns: Columns\n ): SelectQuery<QC, AvailableScope, WithFields<EmptyRow, AvailableScope['topLevel'], Columns>>;\n select<LAlias extends string, Field extends ScopeField>(\n alias: LAlias,\n expr: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Expression<Field>,\n ): SelectQuery<QC, AvailableScope, WithField<EmptyRow, Field, LAlias>>;\n select<Result extends Record<string, Expression<ScopeField>>>(\n callback: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Result,\n ): SelectQuery<QC, AvailableScope, Expand<ExtractScopeFields<Result>>>;\n select(...args: unknown[]): unknown {\n return new SelectQueryImpl(emptyState(this.#fromSource, this.#scope), this.ctx).select(\n ...(args as string[]),\n );\n }\n\n innerJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>> {\n return this.#toJoined().innerJoin(other, on);\n }\n\n outerLeftJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<AvailableScope, NullableScope<Other[typeof JoinOuterScope]>>> {\n return this.#toJoined().outerLeftJoin(other, on);\n }\n\n outerRightJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<NullableScope<AvailableScope>, Other[typeof JoinOuterScope]>> {\n return this.#toJoined().outerRightJoin(other, on);\n }\n\n outerFullJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<\n QC,\n MergeScopes<NullableScope<AvailableScope>, NullableScope<Other[typeof JoinOuterScope]>>\n > {\n return this.#toJoined().outerFullJoin(other, on);\n }\n\n insert(values: Record<string, unknown>): InsertQuery<QC, AvailableScope, EmptyRow> {\n return new InsertQueryImpl(this.#tableName, this.#table, this.#scope, values, this.ctx);\n }\n\n update(set: Record<string, unknown>): UpdateQuery<QC, AvailableScope, EmptyRow> {\n return new UpdateQueryImpl(this.#tableName, this.#table, this.#scope, set, this.ctx);\n }\n\n delete(): DeleteQuery<QC, AvailableScope, EmptyRow> {\n return new DeleteQueryImpl(this.#tableName, this.#scope, this.ctx);\n }\n\n #toJoined(): JoinedTables<QC, AvailableScope> {\n return new JoinedTablesImpl(emptyState(this.#fromSource, this.#scope), this.ctx);\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { ExecutionContext } from '@prisma-next/sql-relational-core/query-lane-context';\nimport type { Db } from '../types/db';\nimport type { BuilderContext } from './builder-base';\nimport { TableProxyImpl } from './table-proxy-impl';\n\nexport interface SqlOptions<C extends Contract<SqlStorage>> {\n readonly context: ExecutionContext<C>;\n}\n\nexport function sql<C extends Contract<SqlStorage>>(options: SqlOptions<C>): Db<C> {\n const { context } = options;\n const ctx: BuilderContext = {\n capabilities: context.contract.capabilities,\n queryOperationTypes: context.queryOperations.entries(),\n target: context.contract.target ?? 'unknown',\n storageHash: context.contract.storage.storageHash ?? 'unknown',\n applyMutationDefaults: (options) => context.applyMutationDefaults(options),\n };\n\n return new Proxy({} as Db<C>, {\n get(_target, prop: string) {\n const tables = context.contract.storage.tables;\n const table = Object.hasOwn(tables, prop) ? tables[prop] : undefined;\n if (table) {\n return new TableProxyImpl(prop, table, prop, ctx);\n }\n return undefined;\n },\n });\n}\n"],"mappings":";;;;;;;;AASA,IAAa,iBAAb,MAAwF;CACtF;CACA;CACA;CAEA,YACE,KACA,YACA,MACA;EACA,KAAK,MAAM;EACX,KAAK,aAAa;EAClB,KAAK,OAAO;;CAGd,WAA0B;EACxB,OAAO,KAAK;;;;;;;;;AChBhB,SAASA,yBAAuB,OAAc,WAAuC;CACnF,IAAI;CACJ,KAAK,MAAM,CAAC,WAAW,WAAW,OAAO,QAAQ,MAAM,WA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;EAC5F,OAAO,KAAKA,WAAW,CAAC,cAAc,OAAO,GAAG;;CAGlD,eACE,OACA,IAC4F;EAC5F,OAAO,KAAKA,WAAW,CAAC,eAAe,OAAO,GAAG;;CAGnD,cACE,OACA,IAIA;EACA,OAAO,KAAKA,WAAW,CAAC,cAAc,OAAO,GAAG;;CAGlD,OAAO,QAA4E;EACjF,OAAO,IAAI,gBAAgB,KAAKJ,YAAY,KAAKC,QAAQ,KAAKE,QAAQ,QAAQ,KAAK,IAAI;;CAGzF,OAAO,KAAyE;EAC9E,OAAO,IAAI,gBAAgB,KAAKH,YAAY,KAAKC,QAAQ,KAAKE,QAAQ,KAAK,KAAK,IAAI;;CAGtF,SAAoD;EAClD,OAAO,IAAI,gBAAgB,KAAKH,YAAY,KAAKG,QAAQ,KAAK,IAAI;;CAGpE,YAA8C;EAC5C,OAAO,IAAI,iBAAiB,WAAW,KAAKD,aAAa,KAAKC,OAAO,EAAE,KAAK,IAAI;;;;;AC/JpF,SAAgB,IAAoC,SAA+B;CACjF,MAAM,EAAE,YAAY;CACpB,MAAM,MAAsB;EAC1B,cAAc,QAAQ,SAAS;EAC/B,qBAAqB,QAAQ,gBAAgB,SAAS;EACtD,QAAQ,QAAQ,SAAS,UAAU;EACnC,aAAa,QAAQ,SAAS,QAAQ,eAAe;EACrD,wBAAwB,YAAY,QAAQ,sBAAsB,QAAQ;EAC3E;CAED,OAAO,IAAI,MAAM,EAAE,EAAW,EAC5B,IAAI,SAAS,MAAc;EACzB,MAAM,SAAS,QAAQ,SAAS,QAAQ;EACxC,MAAM,QAAQ,OAAO,OAAO,QAAQ,KAAK,GAAG,OAAO,QAAQ,KAAA;EAC3D,IAAI,OACF,OAAO,IAAI,eAAe,MAAM,OAAO,MAAM,IAAI;IAItD,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":["#state","#buildLateral","#addLateralJoin","#addJoin","#tableName","#table","#scope","#values","#returningColumns","#rowFields","#setValues","#whereCallbacks","#tableName","#table","#fromSource","#scope","#toJoined"],"sources":["../../src/runtime/expression-impl.ts","../../src/runtime/field-proxy.ts","../../src/runtime/functions.ts","../../src/runtime/builder-base.ts","../../src/runtime/query-impl.ts","../../src/runtime/joined-tables-impl.ts","../../src/runtime/mutation-impl.ts","../../src/runtime/table-proxy-impl.ts","../../src/runtime/sql.ts"],"sourcesContent":["import type { CodecRef } from '@prisma-next/framework-components/codec';\nimport type { AnyExpression as AstExpression } from '@prisma-next/sql-relational-core/ast';\nimport type { Expression } from '@prisma-next/sql-relational-core/expression';\nimport type { ScopeField } from '../scope';\n\n/**\n * Runtime wrapper around a relational-core AST expression node. Carries ScopeField metadata (codecId, nullable) so aggregate-like combinators can propagate the input codec onto their result.\n *\n * `codec` records the column-bound {@link CodecRef} when the field-proxy knows the binding — both the namespaced form (`f.user.email` → `ColumnRef`) and the top-level shortcut (`f.email` → `IdentifierRef`) stamp the ref derived from contract storage. `codecOf(expression)` exposes it for operation implementations forwarding the ref to `toExpr`.\n */\nexport class ExpressionImpl<T extends ScopeField = ScopeField> implements Expression<T> {\n private readonly ast: AstExpression;\n readonly returnType: T;\n readonly codec: CodecRef | undefined;\n\n constructor(ast: AstExpression, returnType: T, codec?: CodecRef) {\n this.ast = ast;\n this.returnType = returnType;\n this.codec = codec;\n }\n\n buildAst(): AstExpression {\n return this.ast;\n }\n}\n","import { ColumnRef, IdentifierRef } from '@prisma-next/sql-relational-core/ast';\nimport type { FieldProxy } from '../expression';\nimport type { Scope, ScopeTable } from '../scope';\nimport { ExpressionImpl } from './expression-impl';\n\nexport function createFieldProxy<S extends Scope>(scope: S): FieldProxy<S> {\n return new Proxy({} as FieldProxy<S>, {\n get(_target, prop: string) {\n if (Object.hasOwn(scope.topLevel, prop)) {\n const topField = scope.topLevel[prop];\n if (topField) {\n return new ExpressionImpl(IdentifierRef.of(prop), topField, topField.codec);\n }\n }\n\n if (Object.hasOwn(scope.namespaces, prop)) {\n const nsFields = scope.namespaces[prop];\n if (nsFields) return createNamespaceProxy(prop, nsFields);\n }\n\n return undefined;\n },\n });\n}\n\nfunction createNamespaceProxy(\n namespaceName: string,\n fields: ScopeTable,\n): Record<string, ExpressionImpl> {\n return new Proxy({} as Record<string, ExpressionImpl>, {\n get(_target, prop: string) {\n if (Object.hasOwn(fields, prop)) {\n const field = fields[prop];\n if (field) return new ExpressionImpl(ColumnRef.of(namespaceName, prop), field, field.codec);\n }\n return undefined;\n },\n });\n}\n","import type { SqlOperationEntry } from '@prisma-next/sql-operations';\nimport {\n AggregateExpr,\n AndExpr,\n type AnyExpression as AstExpression,\n BinaryExpr,\n type BinaryOp,\n type CodecRef,\n ExistsExpr,\n ListExpression,\n LiteralExpr,\n NullCheckExpr,\n OrExpr,\n SubqueryExpr,\n} from '@prisma-next/sql-relational-core/ast';\nimport { codecOf, toExpr } from '@prisma-next/sql-relational-core/expression';\nimport type {\n AggregateFunctions,\n AggregateOnlyFunctions,\n BooleanCodecType,\n BuiltinFunctions,\n CodecExpression,\n Expression,\n Functions,\n} from '../expression';\nimport type { QueryContext, ScopeField, Subquery } from '../scope';\nimport { ExpressionImpl } from './expression-impl';\n\ntype CodecTypes = Record<string, { readonly input: unknown }>;\n// Runtime-level ExprOrVal — accepts any codec, any nullability. Concrete codec typing lives on the public BuiltinFunctions surface in `../expression`.\ntype ExprOrVal<CodecId extends string = string, N extends boolean = boolean> = CodecExpression<\n CodecId,\n N,\n CodecTypes\n>;\n\nconst BOOL_FIELD: BooleanCodecType = { codecId: 'pg/bool@1', nullable: false };\n\nconst resolve = toExpr;\n\n/**\n * Resolve a binary-comparison operand into an AST expression, threading the column-bound side's {@link CodecRef} to the raw-value side.\n *\n * For `fns.eq(f.email, 'alice@example.com')`, `f.email` is the column-bound expression carrying a `ColumnRef` AST and a `CodecRef` derived from contract storage; the raw string operand has no codec context. By deriving the codec context from the column-bound side and forwarding it via `toExpr(value, codec)`, the resulting `ParamRef` carries the `CodecRef` that encode-side dispatch needs to materialise the per-instance codec for parameterized codec ids (`vector(1024)` vs. `vector(1536)`).\n */\nfunction resolveOperand(operand: ExprOrVal, otherCodec?: CodecRef): AstExpression {\n if (isExpressionLike(operand)) return operand.buildAst();\n return toExpr(operand, otherCodec);\n}\n\nfunction isExpressionLike(\n value: unknown,\n): value is { buildAst: () => AstExpression; returnType?: { codecId: string } } {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'buildAst' in value &&\n typeof (value as { buildAst: unknown }).buildAst === 'function'\n );\n}\n\n/**\n * Resolves an Expression via `buildAst()`, or wraps a raw value as a `LiteralExpr` — an SQL literal inlined into the query text, not a bound parameter.\n *\n * Used for `and` / `or` operands. The usual operand is an `Expression<bool>` (e.g. the result of `fns.eq`), which this function passes through by calling `buildAst()`. The only time the raw-value branch fires is when the caller writes `fns.and(true, x)` or similar — inlining `TRUE`/`FALSE` literals lets the SQL planner statically simplify `TRUE AND x` to `x`, which it cannot do for an opaque `ParamRef`.\n */\nfunction toLiteralExpr(value: unknown): AstExpression {\n if (\n typeof value === 'object' &&\n value !== null &&\n 'buildAst' in value &&\n typeof (value as { buildAst: unknown }).buildAst === 'function'\n ) {\n return (value as { buildAst(): AstExpression }).buildAst();\n }\n return new LiteralExpr(value);\n}\n\nfunction boolExpr(astNode: AstExpression): ExpressionImpl<BooleanCodecType> {\n return new ExpressionImpl(astNode, BOOL_FIELD);\n}\n\nfunction binaryWithSharedCodec(\n a: ExprOrVal,\n b: ExprOrVal,\n build: (left: AstExpression, right: AstExpression) => AstExpression,\n): AstExpression {\n const aCodec = codecOf(a);\n const bCodec = codecOf(b);\n const left = resolveOperand(a, bCodec);\n const right = resolveOperand(b, aCodec);\n return build(left, right);\n}\n\nfunction eq(a: ExprOrVal, b: ExprOrVal): ExpressionImpl<BooleanCodecType> {\n if (b === null) return boolExpr(NullCheckExpr.isNull(resolve(a)));\n if (a === null) return boolExpr(NullCheckExpr.isNull(resolve(b)));\n return boolExpr(binaryWithSharedCodec(a, b, (l, r) => new BinaryExpr('eq', l, r)));\n}\n\nfunction ne(a: ExprOrVal, b: ExprOrVal): ExpressionImpl<BooleanCodecType> {\n if (b === null) return boolExpr(NullCheckExpr.isNotNull(resolve(a)));\n if (a === null) return boolExpr(NullCheckExpr.isNotNull(resolve(b)));\n return boolExpr(binaryWithSharedCodec(a, b, (l, r) => new BinaryExpr('neq', l, r)));\n}\n\nfunction comparison(a: ExprOrVal, b: ExprOrVal, op: BinaryOp): ExpressionImpl<BooleanCodecType> {\n return boolExpr(binaryWithSharedCodec(a, b, (l, r) => new BinaryExpr(op, l, r)));\n}\n\nfunction inOrNotIn(\n expr: Expression<ScopeField>,\n valuesOrSubquery: Subquery<Record<string, ScopeField>> | ExprOrVal[],\n op: 'in' | 'notIn',\n): ExpressionImpl<BooleanCodecType> {\n const left = expr.buildAst();\n const leftCodec = codecOf(expr);\n const binaryFn = op === 'in' ? BinaryExpr.in : BinaryExpr.notIn;\n\n if (Array.isArray(valuesOrSubquery)) {\n const refs = valuesOrSubquery.map((v) => resolveOperand(v, leftCodec));\n return boolExpr(binaryFn(left, ListExpression.of(refs)));\n }\n return boolExpr(binaryFn(left, SubqueryExpr.of(valuesOrSubquery.buildAst())));\n}\n\nfunction numericAgg(\n fn: 'sum' | 'avg' | 'min' | 'max',\n expr: Expression<ScopeField>,\n): ExpressionImpl<{ codecId: string; nullable: true }> {\n return new ExpressionImpl(AggregateExpr[fn](expr.buildAst()), {\n codecId: expr.returnType.codecId,\n nullable: true as const,\n });\n}\n\nfunction createBuiltinFunctions() {\n return {\n eq: (a: ExprOrVal, b: ExprOrVal) => eq(a, b),\n ne: (a: ExprOrVal, b: ExprOrVal) => ne(a, b),\n gt: (a: ExprOrVal, b: ExprOrVal) => comparison(a, b, 'gt'),\n gte: (a: ExprOrVal, b: ExprOrVal) => comparison(a, b, 'gte'),\n lt: (a: ExprOrVal, b: ExprOrVal) => comparison(a, b, 'lt'),\n lte: (a: ExprOrVal, b: ExprOrVal) => comparison(a, b, 'lte'),\n and: (...exprs: ExprOrVal<'pg/bool@1', boolean>[]) =>\n boolExpr(AndExpr.of(exprs.map(toLiteralExpr))),\n or: (...exprs: ExprOrVal<'pg/bool@1', boolean>[]) =>\n boolExpr(OrExpr.of(exprs.map(toLiteralExpr))),\n exists: (subquery: Subquery<Record<string, ScopeField>>) =>\n boolExpr(ExistsExpr.exists(subquery.buildAst())),\n notExists: (subquery: Subquery<Record<string, ScopeField>>) =>\n boolExpr(ExistsExpr.notExists(subquery.buildAst())),\n in: (\n expr: Expression<ScopeField>,\n valuesOrSubquery: Subquery<Record<string, ScopeField>> | ExprOrVal[],\n ) => inOrNotIn(expr, valuesOrSubquery, 'in'),\n notIn: (\n expr: Expression<ScopeField>,\n valuesOrSubquery: Subquery<Record<string, ScopeField>> | ExprOrVal[],\n ) => inOrNotIn(expr, valuesOrSubquery, 'notIn'),\n } satisfies BuiltinFunctions<CodecTypes>;\n}\n\nfunction createAggregateOnlyFunctions() {\n return {\n count: (expr?: Expression<ScopeField>) => {\n const astExpr = expr ? expr.buildAst() : undefined;\n return new ExpressionImpl(AggregateExpr.count(astExpr), {\n codecId: 'pg/int8@1',\n nullable: false,\n });\n },\n sum: (expr: Expression<ScopeField>) => numericAgg('sum', expr),\n avg: (expr: Expression<ScopeField>) => numericAgg('avg', expr),\n min: (expr: Expression<ScopeField>) => numericAgg('min', expr),\n max: (expr: Expression<ScopeField>) => numericAgg('max', expr),\n } satisfies AggregateOnlyFunctions;\n}\n\nexport function createFunctions<QC extends QueryContext>(\n operations: Readonly<Record<string, SqlOperationEntry>>,\n): Functions<QC> {\n const builtins = createBuiltinFunctions();\n\n return new Proxy({} as Functions<QC>, {\n get(_target, prop: string) {\n const builtin = (builtins as Record<string, unknown>)[prop];\n if (builtin) return builtin;\n\n const op = operations[prop];\n if (op) return op.impl;\n return undefined;\n },\n });\n}\n\nexport function createAggregateFunctions<QC extends QueryContext>(\n operations: Readonly<Record<string, SqlOperationEntry>>,\n): AggregateFunctions<QC> {\n const baseFns = createFunctions<QC>(operations);\n const aggregates = createAggregateOnlyFunctions();\n\n return new Proxy({} as AggregateFunctions<QC>, {\n get(_target, prop: string) {\n const agg = (aggregates as Record<string, unknown>)[prop];\n if (agg) return agg;\n\n return (baseFns as Record<string, unknown>)[prop];\n },\n });\n}\n","import type { PlanMeta } from '@prisma-next/contract/types';\nimport type { CodecRef } from '@prisma-next/framework-components/codec';\nimport type { SqlStorage, StorageTable } from '@prisma-next/sql-contract/types';\nimport type { SqlOperationEntry } from '@prisma-next/sql-operations';\nimport {\n AndExpr,\n type AnyExpression as AstExpression,\n collectOrderedParamRefs,\n IdentifierRef,\n OrderByItem,\n ProjectionItem,\n SelectAst,\n type TableSource,\n} from '@prisma-next/sql-relational-core/ast';\nimport { codecRefForStorageColumn } from '@prisma-next/sql-relational-core/codec-descriptor-registry';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type {\n AppliedMutationDefault,\n MutationDefaultsOptions,\n} from '@prisma-next/sql-relational-core/query-lane-context';\nimport type {\n AggregateFunctions,\n Expression,\n FieldProxy,\n OrderByOptions,\n OrderByScope,\n} from '../expression';\nimport type {\n GatedMethod,\n MergeScopes,\n NullableScope,\n QueryContext,\n Scope,\n ScopeField,\n ScopeTable,\n} from '../scope';\nimport { createFieldProxy } from './field-proxy';\nimport { createAggregateFunctions, createFunctions } from './functions';\n\nexport type ExprCallback = (fields: FieldProxy<Scope>, fns: unknown) => Expression<ScopeField>;\n\nexport class BuilderBase<Capabilities = unknown> {\n protected readonly ctx: BuilderContext;\n\n constructor(ctx: BuilderContext) {\n this.ctx = ctx;\n }\n\n protected _gate<Req extends Record<string, Record<string, boolean>>, Args extends unknown[], R>(\n required: Req,\n methodName: string,\n method: (...args: Args) => R,\n ): GatedMethod<Capabilities, Req, (...args: Args) => R> {\n return ((...args: Args): R => {\n assertCapability(this.ctx, required, methodName);\n return method(...args);\n }) as GatedMethod<Capabilities, Req, (...args: Args) => R>;\n }\n}\n\nexport interface BuilderState {\n readonly from: TableSource;\n readonly joins: readonly import('@prisma-next/sql-relational-core/ast').JoinAst[];\n readonly projections: readonly ProjectionItem[];\n readonly where: readonly AstExpression[];\n readonly orderBy: readonly OrderByItem[];\n readonly groupBy: readonly AstExpression[];\n readonly having: AstExpression | undefined;\n readonly limit: number | undefined;\n readonly offset: number | undefined;\n readonly distinct: true | undefined;\n readonly distinctOn: readonly AstExpression[] | undefined;\n readonly scope: Scope;\n readonly rowFields: Record<string, ScopeField>;\n}\n\nexport interface BuilderContext {\n readonly capabilities: Record<string, Record<string, boolean>>;\n readonly queryOperationTypes: Readonly<Record<string, SqlOperationEntry>>;\n readonly target: string;\n readonly storageHash: string;\n /**\n * Contract storage carried by the builder context so column-bound `ParamRef` / `ProjectionItem` construction sites can derive a {@link CodecRef} for each `(table, column)` via {@link codecRefFor}. Builder paths that mint AST nodes without storage (rare — tests, ad-hoc lower paths) leave it undefined; the codec slot then stays `undefined` on the resulting nodes.\n */\n readonly storage: SqlStorage | undefined;\n readonly applyMutationDefaults: (\n options: MutationDefaultsOptions,\n ) => ReadonlyArray<AppliedMutationDefault>;\n}\n\n/**\n * Derive the canonical {@link CodecRef} for a `(table, column)` from the builder context's storage. Returns `undefined` when the builder context has no storage attached or when the column is unknown to the contract.\n */\nexport function codecRefFor(\n ctx: BuilderContext,\n tableName: string,\n columnName: string,\n): CodecRef | undefined {\n if (!ctx.storage) return undefined;\n return codecRefForStorageColumn(ctx.storage, tableName, columnName);\n}\n\nexport function emptyState(from: TableSource, scope: Scope): BuilderState {\n return {\n from,\n joins: [],\n projections: [],\n where: [],\n orderBy: [],\n groupBy: [],\n having: undefined,\n limit: undefined,\n offset: undefined,\n distinct: undefined,\n distinctOn: undefined,\n scope,\n rowFields: {},\n };\n}\n\nexport function cloneState(state: BuilderState, overrides: Partial<BuilderState>): BuilderState {\n return { ...state, ...overrides };\n}\n\nexport function combineWhereExprs(exprs: readonly AstExpression[]): AstExpression | undefined {\n if (exprs.length === 0) return undefined;\n if (exprs.length === 1) return exprs[0];\n return AndExpr.of(exprs);\n}\n\nexport function buildSelectAst(state: BuilderState): SelectAst {\n const where = combineWhereExprs(state.where);\n return new SelectAst({\n from: state.from,\n joins: state.joins.length > 0 ? state.joins : undefined,\n projection: state.projections,\n where,\n orderBy: state.orderBy.length > 0 ? state.orderBy : undefined,\n distinct: state.distinct,\n distinctOn: state.distinctOn && state.distinctOn.length > 0 ? state.distinctOn : undefined,\n groupBy: state.groupBy.length > 0 ? state.groupBy : undefined,\n having: state.having,\n limit: state.limit,\n offset: state.offset,\n selectAllIntent: undefined,\n });\n}\n\nexport function buildQueryPlan<Row = unknown>(\n ast: import('@prisma-next/sql-relational-core/ast').AnyQueryAst,\n ctx: BuilderContext,\n): SqlQueryPlan<Row> {\n const paramValues = collectOrderedParamRefs(ast).map((r) => r.value);\n\n const meta: PlanMeta = Object.freeze({\n target: ctx.target,\n storageHash: ctx.storageHash,\n lane: 'dsl',\n });\n\n return Object.freeze({ ast, params: paramValues, meta });\n}\n\nexport function buildPlan<Row = unknown>(\n state: BuilderState,\n ctx: BuilderContext,\n): SqlQueryPlan<Row> {\n return buildQueryPlan<Row>(buildSelectAst(state), ctx);\n}\n\nexport function tableToScope(\n alias: string,\n table: StorageTable,\n options?: { readonly storage?: SqlStorage | undefined; readonly tableName?: string | undefined },\n): Scope {\n const storage = options?.storage;\n const lookupName = options?.tableName;\n const fields: ScopeTable = {};\n for (const [colName, col] of Object.entries(table.columns)) {\n const codec =\n storage && lookupName ? codecRefForStorageColumn(storage, lookupName, colName) : undefined;\n fields[colName] = {\n codecId: col.codecId,\n nullable: col.nullable,\n ...(codec !== undefined ? { codec } : {}),\n };\n }\n return { topLevel: { ...fields }, namespaces: { [alias]: fields } };\n}\n\nexport function mergeScopes<A extends Scope, B extends Scope>(a: A, b: B): MergeScopes<A, B> {\n const topLevel: ScopeTable = {};\n for (const [k, v] of Object.entries(a.topLevel)) {\n if (!(k in b.topLevel)) topLevel[k] = v;\n }\n for (const [k, v] of Object.entries(b.topLevel)) {\n if (!(k in a.topLevel)) topLevel[k] = v;\n }\n return {\n topLevel,\n namespaces: { ...a.namespaces, ...b.namespaces },\n } as MergeScopes<A, B>;\n}\n\nexport function nullableScope<S extends Scope>(scope: S): NullableScope<S> {\n const mkNullable = (tbl: ScopeTable): ScopeTable => {\n const result: ScopeTable = {};\n for (const [k, v] of Object.entries(tbl)) {\n result[k] = {\n codecId: v.codecId,\n nullable: true,\n ...(v.codec !== undefined ? { codec: v.codec } : {}),\n };\n }\n return result;\n };\n const namespaces: Record<string, ScopeTable> = {};\n for (const [k, v] of Object.entries(scope.namespaces)) {\n namespaces[k] = mkNullable(v);\n }\n return { topLevel: mkNullable(scope.topLevel), namespaces } as NullableScope<S>;\n}\n\nexport function orderByScopeOf<S extends Scope, R extends Record<string, ScopeField>>(\n scope: S,\n rowFields: R,\n): OrderByScope<S, R> {\n return {\n topLevel: { ...scope.topLevel, ...rowFields },\n namespaces: scope.namespaces,\n };\n}\n\nexport function assertCapability(\n ctx: BuilderContext,\n required: Record<string, Record<string, boolean>>,\n methodName: string,\n): void {\n for (const [ns, keys] of Object.entries(required)) {\n for (const key of Object.keys(keys)) {\n if (!ctx.capabilities[ns]?.[key]) {\n throw new Error(`${methodName}() requires capability ${ns}.${key}`);\n }\n }\n }\n}\n\nexport function resolveSelectArgs(\n args: unknown[],\n scope: Scope,\n ctx: BuilderContext,\n): { projections: ProjectionItem[]; newRowFields: Record<string, ScopeField> } {\n const projections: ProjectionItem[] = [];\n const newRowFields: Record<string, ScopeField> = {};\n\n if (args.length === 0) return { projections, newRowFields };\n\n if (typeof args[0] === 'string' && (args.length === 1 || typeof args[1] !== 'function')) {\n for (const colName of args as string[]) {\n const field = scope.topLevel[colName];\n if (!field) throw new Error(`Column \"${colName}\" not found in scope`);\n projections.push(ProjectionItem.of(colName, IdentifierRef.of(colName), field.codec));\n newRowFields[colName] = field;\n }\n return { projections, newRowFields };\n }\n\n if (typeof args[0] === 'string' && typeof args[1] === 'function') {\n const alias = args[0] as string;\n const exprFn = args[1] as (\n f: FieldProxy<Scope>,\n fns: AggregateFunctions<QueryContext>,\n ) => Expression<ScopeField>;\n const fns = createAggregateFunctions(ctx.queryOperationTypes);\n const result = exprFn(createFieldProxy(scope), fns);\n const field = result.returnType;\n projections.push(ProjectionItem.of(alias, result.buildAst(), field.codec));\n newRowFields[alias] = field;\n return { projections, newRowFields };\n }\n\n if (typeof args[0] === 'function') {\n const callbackFn = args[0] as (\n f: FieldProxy<Scope>,\n fns: AggregateFunctions<QueryContext>,\n ) => Record<string, Expression<ScopeField>>;\n const fns = createAggregateFunctions(ctx.queryOperationTypes);\n const record = callbackFn(createFieldProxy(scope), fns);\n for (const [key, expr] of Object.entries(record)) {\n const field = expr.returnType;\n projections.push(ProjectionItem.of(key, expr.buildAst(), field.codec));\n newRowFields[key] = field;\n }\n return { projections, newRowFields };\n }\n\n throw new Error('Invalid .select() arguments');\n}\n\nexport function resolveOrderBy(\n arg: unknown,\n options: OrderByOptions | undefined,\n scope: Scope,\n rowFields: Record<string, ScopeField>,\n ctx: BuilderContext,\n useAggregateFns: boolean,\n): OrderByItem {\n const dir = options?.direction ?? 'asc';\n\n if (typeof arg === 'string') {\n const combined = orderByScopeOf(scope, rowFields);\n if (!(arg in combined.topLevel))\n throw new Error(`Column \"${arg}\" not found in scope for orderBy`);\n const expr = IdentifierRef.of(arg);\n return dir === 'asc' ? OrderByItem.asc(expr) : OrderByItem.desc(expr);\n }\n\n if (typeof arg === 'function') {\n const combined = orderByScopeOf(scope, rowFields);\n const fns = useAggregateFns\n ? createAggregateFunctions(ctx.queryOperationTypes)\n : createFunctions(ctx.queryOperationTypes);\n const result = (arg as ExprCallback)(createFieldProxy(combined), fns);\n return dir === 'asc' ? OrderByItem.asc(result.buildAst()) : OrderByItem.desc(result.buildAst());\n }\n\n throw new Error('Invalid orderBy argument');\n}\n\nexport function resolveGroupBy(\n args: unknown[],\n scope: Scope,\n rowFields: Record<string, ScopeField>,\n ctx: BuilderContext,\n): AstExpression[] {\n if (typeof args[0] === 'string') {\n const combined = orderByScopeOf(scope, rowFields);\n return (args as string[]).map((colName) => {\n if (!(colName in combined.topLevel))\n throw new Error(`Column \"${colName}\" not found in scope for groupBy`);\n return IdentifierRef.of(colName);\n });\n }\n\n if (typeof args[0] === 'function') {\n const combined = orderByScopeOf(scope, rowFields);\n const fns = createFunctions(ctx.queryOperationTypes);\n const result = (args[0] as ExprCallback)(createFieldProxy(combined), fns);\n return [result.buildAst()];\n }\n\n throw new Error('Invalid groupBy arguments');\n}\n\nexport function resolveDistinctOn(\n args: unknown[],\n scope: Scope,\n rowFields: Record<string, ScopeField>,\n ctx: BuilderContext,\n): AstExpression[] {\n if (args.length === 1 && typeof args[0] === 'function') {\n const combined = orderByScopeOf(scope, rowFields);\n const fns = createFunctions(ctx.queryOperationTypes);\n const result = (args[0] as ExprCallback)(createFieldProxy(combined), fns);\n return [result.buildAst()];\n }\n const combined = orderByScopeOf(scope, rowFields);\n return (args as string[]).map((colName) => {\n if (!(colName in combined.topLevel))\n throw new Error(`Column \"${colName}\" not found in scope for distinctOn`);\n return IdentifierRef.of(colName);\n });\n}\n","import { DerivedTableSource, type SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type {\n AggregateFunctions,\n BooleanCodecType,\n Expression,\n ExpressionBuilder,\n ExtractScopeFields,\n FieldProxy,\n Functions,\n OrderByOptions,\n OrderByScope,\n WithField,\n WithFields,\n} from '../expression';\nimport type { ResolveRow } from '../resolve';\nimport type {\n Expand,\n JoinOuterScope,\n JoinSource,\n QueryContext,\n Scope,\n ScopeField,\n // biome-ignore lint/correctness/noUnusedImports: used in `declare` property\n SubqueryMarker,\n} from '../scope';\nimport type { GroupedQuery } from '../types/grouped-query';\nimport type { SelectQuery } from '../types/select-query';\nimport {\n BuilderBase,\n type BuilderContext,\n type BuilderState,\n buildPlan,\n buildSelectAst,\n cloneState,\n orderByScopeOf,\n resolveDistinctOn,\n resolveGroupBy,\n resolveOrderBy,\n resolveSelectArgs,\n} from './builder-base';\nimport { createFieldProxy } from './field-proxy';\nimport { createAggregateFunctions, createFunctions } from './functions';\n\nabstract class QueryBase<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n> extends BuilderBase<QC['capabilities']> {\n protected readonly state: BuilderState;\n\n constructor(state: BuilderState, ctx: BuilderContext) {\n super(ctx);\n this.state = state;\n }\n\n protected abstract clone(state: BuilderState): this;\n\n distinctOn = this._gate(\n { postgres: { distinctOn: true } },\n 'distinctOn',\n (...args: unknown[]) => {\n const exprs = resolveDistinctOn(args, this.state.scope, this.state.rowFields, this.ctx);\n return this.clone(\n cloneState(this.state, {\n distinctOn: [...(this.state.distinctOn ?? []), ...exprs],\n }),\n );\n },\n );\n\n limit(count: number): this {\n return this.clone(cloneState(this.state, { limit: count }));\n }\n\n offset(count: number): this {\n return this.clone(cloneState(this.state, { offset: count }));\n }\n\n distinct(): this {\n return this.clone(cloneState(this.state, { distinct: true }));\n }\n\n groupBy(\n ...fields: ((keyof RowType | keyof AvailableScope['topLevel']) & string)[]\n ): GroupedQuery<QC, AvailableScope, RowType>;\n groupBy(\n expr: (\n fields: FieldProxy<OrderByScope<AvailableScope, RowType>>,\n fns: Functions<QC>,\n ) => Expression<ScopeField>,\n ): GroupedQuery<QC, AvailableScope, RowType>;\n groupBy(...args: unknown[]): unknown {\n const exprs = resolveGroupBy(args, this.state.scope, this.state.rowFields, this.ctx);\n return new GroupedQueryImpl<QC, AvailableScope, RowType>(\n cloneState(this.state, { groupBy: [...this.state.groupBy, ...exprs] }),\n this.ctx,\n );\n }\n\n as<Alias extends string>(alias: Alias): JoinSource<RowType, Alias> {\n const ast = buildSelectAst(this.state);\n const derivedSource = DerivedTableSource.as(alias, ast);\n const scope = {\n topLevel: this.state.rowFields as RowType,\n namespaces: { [alias]: this.state.rowFields } as Record<Alias, RowType>,\n };\n return {\n getJoinOuterScope: () => scope,\n buildAst: () => derivedSource,\n\n // `as unknown` is necessary, because JoinOuterScope is a phantom type-only property that does not exist at runtime\n } satisfies Omit<JoinSource<RowType, Alias>, typeof JoinOuterScope> as unknown as JoinSource<\n RowType,\n Alias\n >;\n }\n\n getRowFields(): Record<string, ScopeField> {\n return this.state.rowFields;\n }\n\n buildAst(): SelectAst {\n return buildSelectAst(this.state);\n }\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n return buildPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(\n this.state,\n this.ctx,\n );\n }\n}\n\nexport class SelectQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends QueryBase<QC, AvailableScope, RowType>\n implements SelectQuery<QC, AvailableScope, RowType>\n{\n declare readonly [SubqueryMarker]: RowType;\n\n protected clone(state: BuilderState): this {\n return new SelectQueryImpl<QC, AvailableScope, RowType>(state, this.ctx) as this;\n }\n\n select<Columns extends (keyof AvailableScope['topLevel'] & string)[]>(\n ...columns: Columns\n ): SelectQuery<QC, AvailableScope, WithFields<RowType, AvailableScope['topLevel'], Columns>>;\n select<Alias extends string, Field extends ScopeField>(\n alias: Alias,\n expr: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Expression<Field>,\n ): SelectQuery<QC, AvailableScope, WithField<RowType, Field, Alias>>;\n select<Result extends Record<string, Expression<ScopeField>>>(\n callback: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Result,\n ): SelectQuery<QC, AvailableScope, Expand<RowType & ExtractScopeFields<Result>>>;\n select(...args: unknown[]): unknown {\n const { projections, newRowFields } = resolveSelectArgs(args, this.state.scope, this.ctx);\n return new SelectQueryImpl(\n cloneState(this.state, {\n projections: [...this.state.projections, ...projections],\n rowFields: { ...this.state.rowFields, ...newRowFields },\n }),\n this.ctx,\n );\n }\n\n where(expr: ExpressionBuilder<AvailableScope, QC>): SelectQuery<QC, AvailableScope, RowType> {\n const fieldProxy = createFieldProxy(this.state.scope);\n const fns = createFunctions<QC>(this.ctx.queryOperationTypes);\n const result = (expr as ExpressionBuilder<Scope, QueryContext>)(fieldProxy, fns as never);\n return new SelectQueryImpl(\n cloneState(this.state, {\n where: [...this.state.where, result.buildAst()],\n }),\n this.ctx,\n );\n }\n\n orderBy(\n field: (keyof RowType | keyof AvailableScope['topLevel']) & string,\n options?: OrderByOptions,\n ): SelectQuery<QC, AvailableScope, RowType>;\n orderBy(\n expr: (\n fields: FieldProxy<OrderByScope<AvailableScope, RowType>>,\n fns: Functions<QC>,\n ) => Expression<ScopeField>,\n options?: OrderByOptions,\n ): SelectQuery<QC, AvailableScope, RowType>;\n orderBy(arg: unknown, options?: OrderByOptions): unknown {\n const item = resolveOrderBy(\n arg,\n options,\n this.state.scope,\n this.state.rowFields,\n this.ctx,\n false,\n );\n return this.clone(cloneState(this.state, { orderBy: [...this.state.orderBy, item] }));\n }\n}\n\nexport class GroupedQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends QueryBase<QC, AvailableScope, RowType>\n implements GroupedQuery<QC, AvailableScope, RowType>\n{\n declare readonly [SubqueryMarker]: RowType;\n\n protected clone(state: BuilderState): this {\n return new GroupedQueryImpl<QC, AvailableScope, RowType>(state, this.ctx) as this;\n }\n\n having(\n expr: (\n fields: FieldProxy<OrderByScope<AvailableScope, RowType>>,\n fns: AggregateFunctions<QC>,\n ) => Expression<BooleanCodecType>,\n ): GroupedQuery<QC, AvailableScope, RowType> {\n const combined = orderByScopeOf(\n this.state.scope as AvailableScope,\n this.state.rowFields as RowType,\n );\n const fns = createAggregateFunctions(this.ctx.queryOperationTypes);\n const result = expr(createFieldProxy(combined), fns);\n return new GroupedQueryImpl(cloneState(this.state, { having: result.buildAst() }), this.ctx);\n }\n\n orderBy(\n field: (keyof RowType | keyof AvailableScope['topLevel']) & string,\n options?: OrderByOptions,\n ): GroupedQuery<QC, AvailableScope, RowType>;\n orderBy(\n expr: (\n fields: FieldProxy<OrderByScope<AvailableScope, RowType>>,\n fns: AggregateFunctions<QC>,\n ) => Expression<ScopeField>,\n options?: OrderByOptions,\n ): GroupedQuery<QC, AvailableScope, RowType>;\n orderBy(arg: unknown, options?: OrderByOptions): unknown {\n const item = resolveOrderBy(\n arg,\n options,\n this.state.scope,\n this.state.rowFields,\n this.ctx,\n true,\n );\n return this.clone(cloneState(this.state, { orderBy: [...this.state.orderBy, item] }));\n }\n}\n","import {\n AndExpr,\n DerivedTableSource,\n JoinAst,\n type TableSource,\n} from '@prisma-next/sql-relational-core/ast';\nimport type {\n AggregateFunctions,\n Expression,\n ExpressionBuilder,\n ExtractScopeFields,\n FieldProxy,\n WithField,\n WithFields,\n} from '../expression';\nimport type {\n EmptyRow,\n Expand,\n JoinOuterScope,\n JoinSource,\n MergeScopes,\n NullableScope,\n QueryContext,\n Scope,\n ScopeField,\n ScopeTable,\n Subquery,\n} from '../scope';\nimport type { JoinedTables } from '../types/joined-tables';\nimport type { SelectQuery } from '../types/select-query';\nimport type { LateralBuilder } from '../types/shared';\nimport {\n BuilderBase,\n type BuilderContext,\n type BuilderState,\n cloneState,\n emptyState,\n mergeScopes,\n nullableScope,\n resolveSelectArgs,\n} from './builder-base';\nimport { createFieldProxy } from './field-proxy';\nimport { createFunctions } from './functions';\nimport { SelectQueryImpl } from './query-impl';\n\nexport class JoinedTablesImpl<QC extends QueryContext, AvailableScope extends Scope>\n extends BuilderBase<QC['capabilities']>\n implements JoinedTables<QC, AvailableScope>\n{\n readonly #state: BuilderState;\n\n constructor(state: BuilderState, ctx: BuilderContext) {\n super(ctx);\n this.#state = state;\n }\n\n lateralJoin = this._gate(\n { sql: { lateral: true } },\n 'lateralJoin',\n <Alias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: Alias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<AvailableScope, { topLevel: LateralRow; namespaces: Record<Alias, LateralRow> }>\n > => {\n const { derivedSource, lateralScope } = this.#buildLateral(alias, builder);\n const resultScope = mergeScopes(\n this.#state.scope as AvailableScope,\n lateralScope as { topLevel: LateralRow; namespaces: Record<Alias, LateralRow> },\n );\n return this.#addLateralJoin('inner', resultScope, derivedSource);\n },\n ) as JoinedTables<QC, AvailableScope>['lateralJoin'];\n\n outerLateralJoin = this._gate(\n { sql: { lateral: true } },\n 'outerLateralJoin',\n <Alias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: Alias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<\n AvailableScope,\n NullableScope<{ topLevel: LateralRow; namespaces: Record<Alias, LateralRow> }>\n >\n > => {\n const { derivedSource, lateralScope } = this.#buildLateral(alias, builder);\n const resultScope = mergeScopes(\n this.#state.scope as AvailableScope,\n nullableScope(\n lateralScope as { topLevel: LateralRow; namespaces: Record<Alias, LateralRow> },\n ),\n );\n return this.#addLateralJoin('left', resultScope, derivedSource);\n },\n ) as JoinedTables<QC, AvailableScope>['outerLateralJoin'];\n\n select<Columns extends (keyof AvailableScope['topLevel'] & string)[]>(\n ...columns: Columns\n ): SelectQuery<QC, AvailableScope, WithFields<EmptyRow, AvailableScope['topLevel'], Columns>>;\n select<Alias extends string, Field extends ScopeField>(\n alias: Alias,\n expr: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Expression<Field>,\n ): SelectQuery<QC, AvailableScope, WithField<EmptyRow, Field, Alias>>;\n select<Result extends Record<string, Expression<ScopeField>>>(\n callback: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Result,\n ): SelectQuery<QC, AvailableScope, Expand<ExtractScopeFields<Result>>>;\n select(...args: unknown[]): unknown {\n const { projections, newRowFields } = resolveSelectArgs(args, this.#state.scope, this.ctx);\n return new SelectQueryImpl<QC, AvailableScope>(\n cloneState(this.#state, {\n projections: [...this.#state.projections, ...projections],\n rowFields: { ...this.#state.rowFields, ...newRowFields },\n }),\n this.ctx,\n );\n }\n\n innerJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>> {\n const targetScope = mergeScopes(\n this.#state.scope as AvailableScope,\n other.getJoinOuterScope() as Other[typeof JoinOuterScope],\n );\n return this.#addJoin(other, 'inner', targetScope, on);\n }\n\n outerLeftJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<AvailableScope, NullableScope<Other[typeof JoinOuterScope]>>> {\n const targetScope = mergeScopes(\n this.#state.scope as AvailableScope,\n nullableScope(other.getJoinOuterScope() as Other[typeof JoinOuterScope]),\n );\n return this.#addJoin(other, 'left', targetScope, on);\n }\n\n outerRightJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<NullableScope<AvailableScope>, Other[typeof JoinOuterScope]>> {\n const targetScope = mergeScopes(\n nullableScope(this.#state.scope as AvailableScope),\n other.getJoinOuterScope() as Other[typeof JoinOuterScope],\n );\n return this.#addJoin(other, 'right', targetScope, on);\n }\n\n outerFullJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<\n QC,\n MergeScopes<NullableScope<AvailableScope>, NullableScope<Other[typeof JoinOuterScope]>>\n > {\n const targetScope = mergeScopes(\n nullableScope(this.#state.scope as AvailableScope),\n nullableScope(other.getJoinOuterScope() as Other[typeof JoinOuterScope]),\n );\n return this.#addJoin(other, 'full', targetScope, on);\n }\n\n #addJoin<Other extends JoinSource<ScopeTable, string | never>, ResultScope extends Scope>(\n other: Other,\n joinType: 'inner' | 'left' | 'right' | 'full',\n resultScope: ResultScope,\n onExpr: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, ResultScope> {\n const fieldProxy = createFieldProxy(\n mergeScopes(\n this.#state.scope as AvailableScope,\n other.getJoinOuterScope() as Other[typeof JoinOuterScope],\n ),\n ) as FieldProxy<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>>;\n const fns = createFunctions<QC>(this.ctx.queryOperationTypes);\n const onResult = onExpr(fieldProxy, fns);\n const joinAst = new JoinAst(joinType, other.buildAst(), onResult.buildAst());\n\n return new JoinedTablesImpl(\n cloneState(this.#state, {\n joins: [...this.#state.joins, joinAst],\n scope: resultScope,\n }),\n this.ctx,\n );\n }\n\n #buildLateral(\n alias: string,\n builderFn: (\n lateral: LateralBuilder<QC, AvailableScope>,\n ) => Subquery<Record<string, ScopeField>>,\n ) {\n const lateralBuilder: LateralBuilder<QC, AvailableScope> = {\n from: (other) => {\n const otherScope = other.getJoinOuterScope();\n const parentMerged = mergeScopes(this.#state.scope, otherScope);\n return new SelectQueryImpl(\n emptyState(other.buildAst() as TableSource, parentMerged),\n this.ctx,\n ) as unknown as SelectQuery<QC, AvailableScope, EmptyRow>;\n },\n };\n\n const subquery = builderFn(lateralBuilder);\n const subqueryAst = subquery.buildAst();\n const derivedSource = DerivedTableSource.as(alias, subqueryAst);\n const subqueryRowFields: ScopeTable = subquery.getRowFields();\n const lateralScope: Scope = {\n topLevel: subqueryRowFields,\n namespaces: { [alias]: subqueryRowFields },\n };\n\n return { derivedSource, lateralScope };\n }\n\n #addLateralJoin<ResultScope extends Scope>(\n joinType: 'inner' | 'left',\n resultScope: ResultScope,\n derivedSource: DerivedTableSource,\n ): JoinedTables<QC, ResultScope> {\n const onExpr = AndExpr.of([]);\n const joinAst = new JoinAst(joinType, derivedSource, onExpr, true);\n\n return new JoinedTablesImpl(\n cloneState(this.#state, {\n joins: [...this.#state.joins, joinAst],\n scope: resultScope,\n }),\n this.ctx,\n );\n }\n}\n","import type { StorageTable } from '@prisma-next/sql-contract/types';\nimport {\n type AnyExpression as AstExpression,\n ColumnRef,\n DeleteAst,\n InsertAst,\n ParamRef,\n ProjectionItem,\n TableSource,\n UpdateAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type { MutationDefaultsOp } from '@prisma-next/sql-relational-core/query-lane-context';\nimport type { ExpressionBuilder } from '../expression';\nimport type { ResolveRow } from '../resolve';\nimport type { QueryContext, Scope, ScopeField } from '../scope';\nimport type {\n DeleteQuery,\n InsertQuery,\n ReturningCapability,\n UpdateQuery,\n} from '../types/mutation-query';\nimport {\n BuilderBase,\n type BuilderContext,\n buildQueryPlan,\n codecRefFor,\n combineWhereExprs,\n} from './builder-base';\nimport { createFieldProxy } from './field-proxy';\nimport { createFunctions } from './functions';\n\ntype WhereCallback = ExpressionBuilder<Scope, QueryContext>;\n\nfunction buildParamValues(\n values: Record<string, unknown>,\n table: StorageTable,\n tableName: string,\n op: MutationDefaultsOp,\n ctx: BuilderContext,\n): Record<string, ParamRef> {\n const params: Record<string, ParamRef> = {};\n for (const [col, value] of Object.entries(values)) {\n const column = table.columns[col];\n const codec = column ? codecRefFor(ctx, tableName, col) : undefined;\n params[col] = ParamRef.of(value, codec ? { codec } : undefined);\n }\n for (const def of ctx.applyMutationDefaults({ op, table: tableName, values })) {\n const column = table.columns[def.column];\n const codec = column ? codecRefFor(ctx, tableName, def.column) : undefined;\n params[def.column] = ParamRef.of(def.value, codec ? { codec } : undefined);\n }\n return params;\n}\n\nfunction buildReturningProjections(\n tableName: string,\n columns: string[],\n rowFields: Record<string, ScopeField>,\n): ProjectionItem[] {\n return columns.map((col) =>\n ProjectionItem.of(col, ColumnRef.of(tableName, col), rowFields[col]?.codec),\n );\n}\n\nfunction evaluateWhere(\n whereCallback: WhereCallback,\n scope: Scope,\n queryOperationTypes: BuilderContext['queryOperationTypes'],\n): AstExpression {\n const fieldProxy = createFieldProxy(scope);\n const fns = createFunctions(queryOperationTypes);\n const result = whereCallback(fieldProxy, fns as never);\n return result.buildAst();\n}\n\nexport class InsertQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends BuilderBase<QC['capabilities']>\n implements InsertQuery<QC, AvailableScope, RowType>\n{\n readonly #tableName: string;\n readonly #table: StorageTable;\n readonly #scope: Scope;\n readonly #values: Record<string, unknown>;\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n\n constructor(\n tableName: string,\n table: StorageTable,\n scope: Scope,\n values: Record<string, unknown>,\n ctx: BuilderContext,\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n ) {\n super(ctx);\n this.#tableName = tableName;\n this.#table = table;\n this.#scope = scope;\n this.#values = values;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n }\n\n returning = this._gate<ReturningCapability, string[], InsertQuery<QC, AvailableScope, never>>(\n { sql: { returning: true } },\n 'returning',\n (...columns: string[]) => {\n const newRowFields: Record<string, ScopeField> = {};\n for (const col of columns) {\n const field = this.#scope.topLevel[col];\n if (!field) throw new Error(`Column \"${col}\" not found in scope`);\n newRowFields[col] = field;\n }\n return new InsertQueryImpl(\n this.#tableName,\n this.#table,\n this.#scope,\n this.#values,\n this.ctx,\n columns,\n newRowFields,\n ) as unknown as InsertQuery<QC, AvailableScope, never>;\n },\n );\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n const paramValues = buildParamValues(\n this.#values,\n this.#table,\n this.#tableName,\n 'create',\n this.ctx,\n );\n\n let ast = InsertAst.into(TableSource.named(this.#tableName)).withValues(paramValues);\n\n if (this.#returningColumns.length > 0) {\n ast = ast.withReturning(\n buildReturningProjections(this.#tableName, this.#returningColumns, this.#rowFields),\n );\n }\n\n return buildQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(\n ast,\n this.ctx,\n );\n }\n}\n\nexport class UpdateQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends BuilderBase<QC['capabilities']>\n implements UpdateQuery<QC, AvailableScope, RowType>\n{\n readonly #tableName: string;\n readonly #table: StorageTable;\n readonly #scope: Scope;\n readonly #setValues: Record<string, unknown>;\n readonly #whereCallbacks: readonly WhereCallback[];\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n\n constructor(\n tableName: string,\n table: StorageTable,\n scope: Scope,\n setValues: Record<string, unknown>,\n ctx: BuilderContext,\n whereCallbacks: readonly WhereCallback[] = [],\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n ) {\n super(ctx);\n this.#tableName = tableName;\n this.#table = table;\n this.#scope = scope;\n this.#setValues = setValues;\n this.#whereCallbacks = whereCallbacks;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n }\n\n where(expr: ExpressionBuilder<AvailableScope, QC>): UpdateQuery<QC, AvailableScope, RowType> {\n return new UpdateQueryImpl(\n this.#tableName,\n this.#table,\n this.#scope,\n this.#setValues,\n this.ctx,\n [...this.#whereCallbacks, expr as unknown as WhereCallback],\n this.#returningColumns,\n this.#rowFields,\n );\n }\n\n returning = this._gate<ReturningCapability, string[], UpdateQuery<QC, AvailableScope, never>>(\n { sql: { returning: true } },\n 'returning',\n (...columns: string[]) => {\n const newRowFields: Record<string, ScopeField> = {};\n for (const col of columns) {\n const field = this.#scope.topLevel[col];\n if (!field) throw new Error(`Column \"${col}\" not found in scope`);\n newRowFields[col] = field;\n }\n return new UpdateQueryImpl(\n this.#tableName,\n this.#table,\n this.#scope,\n this.#setValues,\n this.ctx,\n this.#whereCallbacks,\n columns,\n newRowFields,\n ) as unknown as UpdateQuery<QC, AvailableScope, never>;\n },\n );\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n const setParams = buildParamValues(\n this.#setValues,\n this.#table,\n this.#tableName,\n 'update',\n this.ctx,\n );\n\n const whereExpr = combineWhereExprs(\n this.#whereCallbacks.map((cb) =>\n evaluateWhere(cb, this.#scope, this.ctx.queryOperationTypes),\n ),\n );\n\n let ast = UpdateAst.table(TableSource.named(this.#tableName))\n .withSet(setParams)\n .withWhere(whereExpr);\n\n if (this.#returningColumns.length > 0) {\n ast = ast.withReturning(\n buildReturningProjections(this.#tableName, this.#returningColumns, this.#rowFields),\n );\n }\n\n return buildQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(\n ast,\n this.ctx,\n );\n }\n}\n\nexport class DeleteQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends BuilderBase<QC['capabilities']>\n implements DeleteQuery<QC, AvailableScope, RowType>\n{\n readonly #tableName: string;\n readonly #scope: Scope;\n readonly #whereCallbacks: readonly WhereCallback[];\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n\n constructor(\n tableName: string,\n scope: Scope,\n ctx: BuilderContext,\n whereCallbacks: readonly WhereCallback[] = [],\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n ) {\n super(ctx);\n this.#tableName = tableName;\n this.#scope = scope;\n this.#whereCallbacks = whereCallbacks;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n }\n\n where(expr: ExpressionBuilder<AvailableScope, QC>): DeleteQuery<QC, AvailableScope, RowType> {\n return new DeleteQueryImpl(\n this.#tableName,\n this.#scope,\n this.ctx,\n [...this.#whereCallbacks, expr as unknown as WhereCallback],\n this.#returningColumns,\n this.#rowFields,\n );\n }\n\n returning = this._gate<ReturningCapability, string[], DeleteQuery<QC, AvailableScope, never>>(\n { sql: { returning: true } },\n 'returning',\n (...columns: string[]) => {\n const newRowFields: Record<string, ScopeField> = {};\n for (const col of columns) {\n const field = this.#scope.topLevel[col];\n if (!field) throw new Error(`Column \"${col}\" not found in scope`);\n newRowFields[col] = field;\n }\n return new DeleteQueryImpl(\n this.#tableName,\n this.#scope,\n this.ctx,\n this.#whereCallbacks,\n columns,\n newRowFields,\n ) as unknown as DeleteQuery<QC, AvailableScope, never>;\n },\n );\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n const whereExpr = combineWhereExprs(\n this.#whereCallbacks.map((cb) =>\n evaluateWhere(cb, this.#scope, this.ctx.queryOperationTypes),\n ),\n );\n\n let ast = DeleteAst.from(TableSource.named(this.#tableName)).withWhere(whereExpr);\n\n if (this.#returningColumns.length > 0) {\n ast = ast.withReturning(\n buildReturningProjections(this.#tableName, this.#returningColumns, this.#rowFields),\n );\n }\n\n return buildQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(\n ast,\n this.ctx,\n );\n }\n}\n","import type { StorageTable } from '@prisma-next/sql-contract/types';\nimport { type AnyFromSource, TableSource } from '@prisma-next/sql-relational-core/ast';\nimport type {\n AggregateFunctions,\n Expression,\n ExpressionBuilder,\n ExtractScopeFields,\n FieldProxy,\n WithField,\n WithFields,\n} from '../expression';\nimport type {\n EmptyRow,\n Expand,\n JoinOuterScope,\n JoinSource,\n MergeScopes,\n NullableScope,\n QueryContext,\n RebindScope,\n Scope,\n ScopeField,\n ScopeTable,\n StorageTableToScopeTable,\n Subquery,\n} from '../scope';\nimport type { TableProxyContract } from '../types/db';\nimport type { JoinedTables } from '../types/joined-tables';\nimport type { DeleteQuery, InsertQuery, UpdateQuery } from '../types/mutation-query';\nimport type { SelectQuery } from '../types/select-query';\nimport type { LateralBuilder } from '../types/shared';\nimport type { TableProxy } from '../types/table-proxy';\nimport { BuilderBase, type BuilderContext, emptyState, tableToScope } from './builder-base';\nimport { JoinedTablesImpl } from './joined-tables-impl';\nimport { DeleteQueryImpl, InsertQueryImpl, UpdateQueryImpl } from './mutation-impl';\nimport { SelectQueryImpl } from './query-impl';\n\nexport class TableProxyImpl<\n C extends TableProxyContract,\n Name extends string & keyof C['storage']['tables'],\n Alias extends string,\n AvailableScope extends Scope,\n QC extends QueryContext,\n >\n extends BuilderBase<C['capabilities']>\n implements TableProxy<C, Name, Alias, AvailableScope, QC>\n{\n declare readonly [JoinOuterScope]: JoinSource<\n StorageTableToScopeTable<C['storage']['tables'][Name]>,\n Alias\n >[typeof JoinOuterScope];\n\n readonly #tableName: string;\n readonly #table: StorageTable;\n readonly #fromSource: TableSource;\n readonly #scope: Scope;\n\n constructor(tableName: string, table: StorageTable, alias: string, ctx: BuilderContext) {\n super(ctx);\n this.#tableName = tableName;\n this.#table = table;\n this.#scope = tableToScope(alias, table, { storage: ctx.storage, tableName });\n this.#fromSource = TableSource.named(tableName, alias !== tableName ? alias : undefined);\n }\n\n lateralJoin = this._gate(\n { sql: { lateral: true } },\n 'lateralJoin',\n <LAlias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: LAlias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<AvailableScope, { topLevel: LateralRow; namespaces: Record<LAlias, LateralRow> }>\n > => {\n return this.#toJoined().lateralJoin(alias, builder);\n },\n ) as TableProxy<C, Name, Alias, AvailableScope, QC>['lateralJoin'];\n\n outerLateralJoin = this._gate(\n { sql: { lateral: true } },\n 'outerLateralJoin',\n <LAlias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: LAlias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<\n AvailableScope,\n NullableScope<{ topLevel: LateralRow; namespaces: Record<LAlias, LateralRow> }>\n >\n > => {\n return this.#toJoined().outerLateralJoin(alias, builder);\n },\n ) as TableProxy<C, Name, Alias, AvailableScope, QC>['outerLateralJoin'];\n\n getJoinOuterScope(): Scope {\n return this.#scope;\n }\n\n buildAst(): AnyFromSource {\n return this.#fromSource;\n }\n\n as<NewAlias extends string>(\n newAlias: NewAlias,\n ): TableProxy<C, Name, NewAlias, RebindScope<AvailableScope, Alias, NewAlias>> {\n return new TableProxyImpl(this.#tableName, this.#table, newAlias, this.ctx);\n }\n\n select<Columns extends (keyof AvailableScope['topLevel'] & string)[]>(\n ...columns: Columns\n ): SelectQuery<QC, AvailableScope, WithFields<EmptyRow, AvailableScope['topLevel'], Columns>>;\n select<LAlias extends string, Field extends ScopeField>(\n alias: LAlias,\n expr: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Expression<Field>,\n ): SelectQuery<QC, AvailableScope, WithField<EmptyRow, Field, LAlias>>;\n select<Result extends Record<string, Expression<ScopeField>>>(\n callback: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Result,\n ): SelectQuery<QC, AvailableScope, Expand<ExtractScopeFields<Result>>>;\n select(...args: unknown[]): unknown {\n return new SelectQueryImpl(emptyState(this.#fromSource, this.#scope), this.ctx).select(\n ...(args as string[]),\n );\n }\n\n innerJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>> {\n return this.#toJoined().innerJoin(other, on);\n }\n\n outerLeftJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<AvailableScope, NullableScope<Other[typeof JoinOuterScope]>>> {\n return this.#toJoined().outerLeftJoin(other, on);\n }\n\n outerRightJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<NullableScope<AvailableScope>, Other[typeof JoinOuterScope]>> {\n return this.#toJoined().outerRightJoin(other, on);\n }\n\n outerFullJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<\n QC,\n MergeScopes<NullableScope<AvailableScope>, NullableScope<Other[typeof JoinOuterScope]>>\n > {\n return this.#toJoined().outerFullJoin(other, on);\n }\n\n insert(values: Record<string, unknown>): InsertQuery<QC, AvailableScope, EmptyRow> {\n return new InsertQueryImpl(this.#tableName, this.#table, this.#scope, values, this.ctx);\n }\n\n update(set: Record<string, unknown>): UpdateQuery<QC, AvailableScope, EmptyRow> {\n return new UpdateQueryImpl(this.#tableName, this.#table, this.#scope, set, this.ctx);\n }\n\n delete(): DeleteQuery<QC, AvailableScope, EmptyRow> {\n return new DeleteQueryImpl(this.#tableName, this.#scope, this.ctx);\n }\n\n #toJoined(): JoinedTables<QC, AvailableScope> {\n return new JoinedTablesImpl(emptyState(this.#fromSource, this.#scope), this.ctx);\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { ExecutionContext } from '@prisma-next/sql-relational-core/query-lane-context';\nimport type { Db } from '../types/db';\nimport type { BuilderContext } from './builder-base';\nimport { TableProxyImpl } from './table-proxy-impl';\n\nexport interface SqlOptions<C extends Contract<SqlStorage>> {\n readonly context: ExecutionContext<C>;\n}\n\nexport function sql<C extends Contract<SqlStorage>>(options: SqlOptions<C>): Db<C> {\n const { context } = options;\n const ctx: BuilderContext = {\n capabilities: context.contract.capabilities,\n queryOperationTypes: context.queryOperations.entries(),\n target: context.contract.target ?? 'unknown',\n storageHash: context.contract.storage.storageHash ?? 'unknown',\n storage: context.contract.storage,\n applyMutationDefaults: (options) => context.applyMutationDefaults(options),\n };\n\n return new Proxy({} as Db<C>, {\n get(_target, prop: string) {\n const tables = context.contract.storage.tables;\n const table = Object.hasOwn(tables, prop) ? tables[prop] : undefined;\n if (table) {\n return new TableProxyImpl(prop, table, prop, ctx);\n }\n return undefined;\n },\n });\n}\n"],"mappings":";;;;;;;;;AAUA,IAAa,iBAAb,MAAwF;CACtF;CACA;CACA;CAEA,YAAY,KAAoB,YAAe,OAAkB;EAC/D,KAAK,MAAM;EACX,KAAK,aAAa;EAClB,KAAK,QAAQ;;CAGf,WAA0B;EACxB,OAAO,KAAK;;;;;ACjBhB,SAAgB,iBAAkC,OAAyB;CACzE,OAAO,IAAI,MAAM,EAAE,EAAmB,EACpC,IAAI,SAAS,MAAc;EACzB,IAAI,OAAO,OAAO,MAAM,UAAU,KAAK,EAAE;GACvC,MAAM,WAAW,MAAM,SAAS;GAChC,IAAI,UACF,OAAO,IAAI,eAAe,cAAc,GAAG,KAAK,EAAE,UAAU,SAAS,MAAM;;EAI/E,IAAI,OAAO,OAAO,MAAM,YAAY,KAAK,EAAE;GACzC,MAAM,WAAW,MAAM,WAAW;GAClC,IAAI,UAAU,OAAO,qBAAqB,MAAM,SAAS;;IAK9D,CAAC;;AAGJ,SAAS,qBACP,eACA,QACgC;CAChC,OAAO,IAAI,MAAM,EAAE,EAAoC,EACrD,IAAI,SAAS,MAAc;EACzB,IAAI,OAAO,OAAO,QAAQ,KAAK,EAAE;GAC/B,MAAM,QAAQ,OAAO;GACrB,IAAI,OAAO,OAAO,IAAI,eAAe,UAAU,GAAG,eAAe,KAAK,EAAE,OAAO,MAAM,MAAM;;IAIhG,CAAC;;;;ACDJ,MAAM,aAA+B;CAAE,SAAS;CAAa,UAAU;CAAO;AAE9E,MAAM,UAAU;;;;;;AAOhB,SAAS,eAAe,SAAoB,YAAsC;CAChF,IAAI,iBAAiB,QAAQ,EAAE,O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": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "description": "SQL builder lane for Prisma Next",
8
8
  "dependencies": {
9
- "@prisma-next/contract": "0.5.1",
10
- "@prisma-next/framework-components": "0.5.1",
11
- "@prisma-next/sql-contract": "0.5.1",
12
- "@prisma-next/sql-relational-core": "0.5.1",
13
- "@prisma-next/sql-operations": "0.5.1"
9
+ "@prisma-next/contract": "0.6.0-dev.17",
10
+ "@prisma-next/framework-components": "0.6.0-dev.17",
11
+ "@prisma-next/sql-operations": "0.6.0-dev.17",
12
+ "@prisma-next/sql-relational-core": "0.6.0-dev.17",
13
+ "@prisma-next/sql-contract": "0.6.0-dev.17"
14
14
  },
15
15
  "devDependencies": {
16
16
  "tsdown": "0.22.0",
17
17
  "typescript": "5.9.3",
18
18
  "vitest": "4.1.5",
19
- "@prisma-next/ids": "0.5.1",
20
- "@prisma-next/adapter-postgres": "0.5.1",
21
- "@prisma-next/sql-contract-ts": "0.5.1",
22
- "@prisma-next/target-postgres": "0.5.1",
19
+ "@prisma-next/adapter-postgres": "0.6.0-dev.17",
20
+ "@prisma-next/extension-pgvector": "0.6.0-dev.17",
21
+ "@prisma-next/sql-contract-ts": "0.6.0-dev.17",
22
+ "@prisma-next/ids": "0.6.0-dev.17",
23
23
  "@prisma-next/test-utils": "0.0.1",
24
- "@prisma-next/utils": "0.5.1",
25
- "@prisma-next/extension-pgvector": "0.5.1",
24
+ "@prisma-next/target-postgres": "0.6.0-dev.17",
26
25
  "@prisma-next/tsconfig": "0.0.0",
26
+ "@prisma-next/utils": "0.6.0-dev.17",
27
27
  "@prisma-next/tsdown": "0.0.0"
28
28
  },
29
29
  "files": [
@@ -1,5 +1,6 @@
1
1
  import type { PlanMeta } from '@prisma-next/contract/types';
2
- import type { StorageTable } from '@prisma-next/sql-contract/types';
2
+ import type { CodecRef } from '@prisma-next/framework-components/codec';
3
+ import type { SqlStorage, StorageTable } from '@prisma-next/sql-contract/types';
3
4
  import type { SqlOperationEntry } from '@prisma-next/sql-operations';
4
5
  import {
5
6
  AndExpr,
@@ -11,6 +12,7 @@ import {
11
12
  SelectAst,
12
13
  type TableSource,
13
14
  } from '@prisma-next/sql-relational-core/ast';
15
+ import { codecRefForStorageColumn } from '@prisma-next/sql-relational-core/codec-descriptor-registry';
14
16
  import type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';
15
17
  import type {
16
18
  AppliedMutationDefault,
@@ -77,11 +79,27 @@ export interface BuilderContext {
77
79
  readonly queryOperationTypes: Readonly<Record<string, SqlOperationEntry>>;
78
80
  readonly target: string;
79
81
  readonly storageHash: string;
82
+ /**
83
+ * Contract storage carried by the builder context so column-bound `ParamRef` / `ProjectionItem` construction sites can derive a {@link CodecRef} for each `(table, column)` via {@link codecRefFor}. Builder paths that mint AST nodes without storage (rare — tests, ad-hoc lower paths) leave it undefined; the codec slot then stays `undefined` on the resulting nodes.
84
+ */
85
+ readonly storage: SqlStorage | undefined;
80
86
  readonly applyMutationDefaults: (
81
87
  options: MutationDefaultsOptions,
82
88
  ) => ReadonlyArray<AppliedMutationDefault>;
83
89
  }
84
90
 
91
+ /**
92
+ * Derive the canonical {@link CodecRef} for a `(table, column)` from the builder context's storage. Returns `undefined` when the builder context has no storage attached or when the column is unknown to the contract.
93
+ */
94
+ export function codecRefFor(
95
+ ctx: BuilderContext,
96
+ tableName: string,
97
+ columnName: string,
98
+ ): CodecRef | undefined {
99
+ if (!ctx.storage) return undefined;
100
+ return codecRefForStorageColumn(ctx.storage, tableName, columnName);
101
+ }
102
+
85
103
  export function emptyState(from: TableSource, scope: Scope): BuilderState {
86
104
  return {
87
105
  from,
@@ -110,20 +128,6 @@ export function combineWhereExprs(exprs: readonly AstExpression[]): AstExpressio
110
128
  return AndExpr.of(exprs);
111
129
  }
112
130
 
113
- /**
114
- * Same uniqueness rule as the field-proxy's `findUniqueNamespaceFor`: when exactly one namespace owns a top-level field, the binding is unambiguous. Used by `select('col', ...)` to attach `refs` metadata to the resulting `ProjectionItem` while keeping the AST as `IdentifierRef` (so SQL renders unchanged).
115
- */
116
- function findUniqueNamespaceFor(scope: Scope, fieldName: string): string | undefined {
117
- let found: string | undefined;
118
- for (const [namespace, fields] of Object.entries(scope.namespaces)) {
119
- if (Object.hasOwn(fields, fieldName)) {
120
- if (found !== undefined) return undefined;
121
- found = namespace;
122
- }
123
- }
124
- return found;
125
- }
126
-
127
131
  export function buildSelectAst(state: BuilderState): SelectAst {
128
132
  const where = combineWhereExprs(state.where);
129
133
  return new SelectAst({
@@ -164,12 +168,24 @@ export function buildPlan<Row = unknown>(
164
168
  return buildQueryPlan<Row>(buildSelectAst(state), ctx);
165
169
  }
166
170
 
167
- export function tableToScope(name: string, table: StorageTable): Scope {
171
+ export function tableToScope(
172
+ alias: string,
173
+ table: StorageTable,
174
+ options?: { readonly storage?: SqlStorage | undefined; readonly tableName?: string | undefined },
175
+ ): Scope {
176
+ const storage = options?.storage;
177
+ const lookupName = options?.tableName;
168
178
  const fields: ScopeTable = {};
169
179
  for (const [colName, col] of Object.entries(table.columns)) {
170
- fields[colName] = { codecId: col.codecId, nullable: col.nullable };
180
+ const codec =
181
+ storage && lookupName ? codecRefForStorageColumn(storage, lookupName, colName) : undefined;
182
+ fields[colName] = {
183
+ codecId: col.codecId,
184
+ nullable: col.nullable,
185
+ ...(codec !== undefined ? { codec } : {}),
186
+ };
171
187
  }
172
- return { topLevel: { ...fields }, namespaces: { [name]: fields } };
188
+ return { topLevel: { ...fields }, namespaces: { [alias]: fields } };
173
189
  }
174
190
 
175
191
  export function mergeScopes<A extends Scope, B extends Scope>(a: A, b: B): MergeScopes<A, B> {
@@ -190,7 +206,11 @@ export function nullableScope<S extends Scope>(scope: S): NullableScope<S> {
190
206
  const mkNullable = (tbl: ScopeTable): ScopeTable => {
191
207
  const result: ScopeTable = {};
192
208
  for (const [k, v] of Object.entries(tbl)) {
193
- result[k] = { codecId: v.codecId, nullable: true };
209
+ result[k] = {
210
+ codecId: v.codecId,
211
+ nullable: true,
212
+ ...(v.codec !== undefined ? { codec: v.codec } : {}),
213
+ };
194
214
  }
195
215
  return result;
196
216
  };
@@ -239,9 +259,7 @@ export function resolveSelectArgs(
239
259
  for (const colName of args as string[]) {
240
260
  const field = scope.topLevel[colName];
241
261
  if (!field) throw new Error(`Column "${colName}" not found in scope`);
242
- const namespace = findUniqueNamespaceFor(scope, colName);
243
- const refs = namespace ? { table: namespace, column: colName } : undefined;
244
- projections.push(ProjectionItem.of(colName, IdentifierRef.of(colName), field.codecId, refs));
262
+ projections.push(ProjectionItem.of(colName, IdentifierRef.of(colName), field.codec));
245
263
  newRowFields[colName] = field;
246
264
  }
247
265
  return { projections, newRowFields };
@@ -256,7 +274,7 @@ export function resolveSelectArgs(
256
274
  const fns = createAggregateFunctions(ctx.queryOperationTypes);
257
275
  const result = exprFn(createFieldProxy(scope), fns);
258
276
  const field = result.returnType;
259
- projections.push(ProjectionItem.of(alias, result.buildAst(), field.codecId));
277
+ projections.push(ProjectionItem.of(alias, result.buildAst(), field.codec));
260
278
  newRowFields[alias] = field;
261
279
  return { projections, newRowFields };
262
280
  }
@@ -270,7 +288,7 @@ export function resolveSelectArgs(
270
288
  const record = callbackFn(createFieldProxy(scope), fns);
271
289
  for (const [key, expr] of Object.entries(record)) {
272
290
  const field = expr.returnType;
273
- projections.push(ProjectionItem.of(key, expr.buildAst(), field.codecId));
291
+ projections.push(ProjectionItem.of(key, expr.buildAst(), field.codec));
274
292
  newRowFields[key] = field;
275
293
  }
276
294
  return { projections, newRowFields };
@@ -1,3 +1,4 @@
1
+ import type { CodecRef } from '@prisma-next/framework-components/codec';
1
2
  import type { AnyExpression as AstExpression } from '@prisma-next/sql-relational-core/ast';
2
3
  import type { Expression } from '@prisma-next/sql-relational-core/expression';
3
4
  import type { ScopeField } from '../scope';
@@ -5,21 +6,17 @@ import type { ScopeField } from '../scope';
5
6
  /**
6
7
  * Runtime wrapper around a relational-core AST expression node. Carries ScopeField metadata (codecId, nullable) so aggregate-like combinators can propagate the input codec onto their result.
7
8
  *
8
- * `refs` records the column-bound binding (`{ table, column }`) when known — the field-proxy populates it for both the namespaced form (`f.user.email` → `ColumnRef`) and the top-level shortcut (`f.email` → `IdentifierRef` + refs metadata). Encode-side dispatch and the `validateParamRefRefs` pass read it via `refsOf(expression)`.
9
+ * `codec` records the column-bound {@link CodecRef} when the field-proxy knows the binding both the namespaced form (`f.user.email` → `ColumnRef`) and the top-level shortcut (`f.email` → `IdentifierRef`) stamp the ref derived from contract storage. `codecOf(expression)` exposes it for operation implementations forwarding the ref to `toExpr`.
9
10
  */
10
11
  export class ExpressionImpl<T extends ScopeField = ScopeField> implements Expression<T> {
11
12
  private readonly ast: AstExpression;
12
13
  readonly returnType: T;
13
- readonly refs: { readonly table: string; readonly column: string } | undefined;
14
+ readonly codec: CodecRef | undefined;
14
15
 
15
- constructor(
16
- ast: AstExpression,
17
- returnType: T,
18
- refs?: { readonly table: string; readonly column: string },
19
- ) {
16
+ constructor(ast: AstExpression, returnType: T, codec?: CodecRef) {
20
17
  this.ast = ast;
21
18
  this.returnType = returnType;
22
- this.refs = refs;
19
+ this.codec = codec;
23
20
  }
24
21
 
25
22
  buildAst(): AstExpression {
@@ -3,30 +3,13 @@ import type { FieldProxy } from '../expression';
3
3
  import type { Scope, ScopeTable } from '../scope';
4
4
  import { ExpressionImpl } from './expression-impl';
5
5
 
6
- /**
7
- * For a top-level field name, find the namespace (table alias) that contributed it. When exactly one namespace owns the field, the top-level binding is unambiguously column-bound and we record that `(table, column)` pair on the `ExpressionImpl` so encode-side dispatch (`forColumn`) and the `validateParamRefRefs` pass can find it. The AST stays as `IdentifierRef` to preserve SQL rendering — adapters render top-level
8
- * identifiers without an explicit table qualifier — so this change is metadata-only and produces no SQL drift.
9
- */
10
- function findUniqueNamespaceFor(scope: Scope, fieldName: string): string | undefined {
11
- let found: string | undefined;
12
- for (const [namespace, fields] of Object.entries(scope.namespaces)) {
13
- if (Object.hasOwn(fields, fieldName)) {
14
- if (found !== undefined) return undefined;
15
- found = namespace;
16
- }
17
- }
18
- return found;
19
- }
20
-
21
6
  export function createFieldProxy<S extends Scope>(scope: S): FieldProxy<S> {
22
7
  return new Proxy({} as FieldProxy<S>, {
23
8
  get(_target, prop: string) {
24
9
  if (Object.hasOwn(scope.topLevel, prop)) {
25
10
  const topField = scope.topLevel[prop];
26
11
  if (topField) {
27
- const namespace = findUniqueNamespaceFor(scope, prop);
28
- const refs = namespace ? { table: namespace, column: prop } : undefined;
29
- return new ExpressionImpl(IdentifierRef.of(prop), topField, refs);
12
+ return new ExpressionImpl(IdentifierRef.of(prop), topField, topField.codec);
30
13
  }
31
14
  }
32
15
 
@@ -48,7 +31,7 @@ function createNamespaceProxy(
48
31
  get(_target, prop: string) {
49
32
  if (Object.hasOwn(fields, prop)) {
50
33
  const field = fields[prop];
51
- if (field) return new ExpressionImpl(ColumnRef.of(namespaceName, prop), field);
34
+ if (field) return new ExpressionImpl(ColumnRef.of(namespaceName, prop), field, field.codec);
52
35
  }
53
36
  return undefined;
54
37
  },
@@ -5,6 +5,7 @@ import {
5
5
  type AnyExpression as AstExpression,
6
6
  BinaryExpr,
7
7
  type BinaryOp,
8
+ type CodecRef,
8
9
  ExistsExpr,
9
10
  ListExpression,
10
11
  LiteralExpr,
@@ -12,7 +13,7 @@ import {
12
13
  OrExpr,
13
14
  SubqueryExpr,
14
15
  } from '@prisma-next/sql-relational-core/ast';
15
- import { refsOf, toExpr } from '@prisma-next/sql-relational-core/expression';
16
+ import { codecOf, toExpr } from '@prisma-next/sql-relational-core/expression';
16
17
  import type {
17
18
  AggregateFunctions,
18
19
  AggregateOnlyFunctions,
@@ -38,18 +39,13 @@ const BOOL_FIELD: BooleanCodecType = { codecId: 'pg/bool@1', nullable: false };
38
39
  const resolve = toExpr;
39
40
 
40
41
  /**
41
- * Resolve a binary-comparison operand into an AST expression, threading the column-bound side's `codecId` + `refs` to the raw-value side.
42
+ * Resolve a binary-comparison operand into an AST expression, threading the column-bound side's {@link CodecRef} to the raw-value side.
42
43
  *
43
- * For `fns.eq(f.email, 'alice@example.com')`, `f.email` is the column-bound expression carrying a `ColumnRef` AST and a `returnType.codecId` (`pg/varchar@1`); the raw string operand has no codec context. By deriving the codec context from the column-bound side and forwarding it via `toExpr(value, codecId, refs)`, the resulting `ParamRef` carries the column refs that encode-side `forColumn` dispatch needs (and that the
44
- * validator pass requires for parameterized codec ids like `pg/varchar@1` with a length parameter).
44
+ * For `fns.eq(f.email, 'alice@example.com')`, `f.email` is the column-bound expression carrying a `ColumnRef` AST and a `CodecRef` derived from contract storage; the raw string operand has no codec context. By deriving the codec context from the column-bound side and forwarding it via `toExpr(value, codec)`, the resulting `ParamRef` carries the `CodecRef` that encode-side dispatch needs to materialise the per-instance codec for parameterized codec ids (`vector(1024)` vs. `vector(1536)`).
45
45
  */
46
- function resolveOperand(
47
- operand: ExprOrVal,
48
- otherCodecId?: string,
49
- otherRefs?: { table: string; column: string },
50
- ): AstExpression {
46
+ function resolveOperand(operand: ExprOrVal, otherCodec?: CodecRef): AstExpression {
51
47
  if (isExpressionLike(operand)) return operand.buildAst();
52
- return toExpr(operand, otherCodecId, otherRefs);
48
+ return toExpr(operand, otherCodec);
53
49
  }
54
50
 
55
51
  function isExpressionLike(
@@ -63,15 +59,6 @@ function isExpressionLike(
63
59
  );
64
60
  }
65
61
 
66
- function operandCodecId(operand: ExprOrVal): string | undefined {
67
- if (!isExpressionLike(operand)) return undefined;
68
- return (operand as { returnType?: { codecId: string } }).returnType?.codecId;
69
- }
70
-
71
- function operandRefs(operand: ExprOrVal): { table: string; column: string } | undefined {
72
- return refsOf(operand);
73
- }
74
-
75
62
  /**
76
63
  * Resolves an Expression via `buildAst()`, or wraps a raw value as a `LiteralExpr` — an SQL literal inlined into the query text, not a bound parameter.
77
64
  *
@@ -98,12 +85,10 @@ function binaryWithSharedCodec(
98
85
  b: ExprOrVal,
99
86
  build: (left: AstExpression, right: AstExpression) => AstExpression,
100
87
  ): AstExpression {
101
- const aCodecId = operandCodecId(a);
102
- const bCodecId = operandCodecId(b);
103
- const aRefs = operandRefs(a);
104
- const bRefs = operandRefs(b);
105
- const left = resolveOperand(a, bCodecId, bRefs);
106
- const right = resolveOperand(b, aCodecId, aRefs);
88
+ const aCodec = codecOf(a);
89
+ const bCodec = codecOf(b);
90
+ const left = resolveOperand(a, bCodec);
91
+ const right = resolveOperand(b, aCodec);
107
92
  return build(left, right);
108
93
  }
109
94
 
@@ -129,12 +114,11 @@ function inOrNotIn(
129
114
  op: 'in' | 'notIn',
130
115
  ): ExpressionImpl<BooleanCodecType> {
131
116
  const left = expr.buildAst();
132
- const leftCodecId = expr.returnType.codecId;
133
- const leftRefs = refsOf(expr);
117
+ const leftCodec = codecOf(expr);
134
118
  const binaryFn = op === 'in' ? BinaryExpr.in : BinaryExpr.notIn;
135
119
 
136
120
  if (Array.isArray(valuesOrSubquery)) {
137
- const refs = valuesOrSubquery.map((v) => resolveOperand(v, leftCodecId, leftRefs));
121
+ const refs = valuesOrSubquery.map((v) => resolveOperand(v, leftCodec));
138
122
  return boolExpr(binaryFn(left, ListExpression.of(refs)));
139
123
  }
140
124
  return boolExpr(binaryFn(left, SubqueryExpr.of(valuesOrSubquery.buildAst())));
@@ -24,6 +24,7 @@ import {
24
24
  BuilderBase,
25
25
  type BuilderContext,
26
26
  buildQueryPlan,
27
+ codecRefFor,
27
28
  combineWhereExprs,
28
29
  } from './builder-base';
29
30
  import { createFieldProxy } from './field-proxy';
@@ -41,19 +42,13 @@ function buildParamValues(
41
42
  const params: Record<string, ParamRef> = {};
42
43
  for (const [col, value] of Object.entries(values)) {
43
44
  const column = table.columns[col];
44
- params[col] = ParamRef.of(
45
- value,
46
- column ? { codecId: column.codecId, refs: { table: tableName, column: col } } : undefined,
47
- );
45
+ const codec = column ? codecRefFor(ctx, tableName, col) : undefined;
46
+ params[col] = ParamRef.of(value, codec ? { codec } : undefined);
48
47
  }
49
48
  for (const def of ctx.applyMutationDefaults({ op, table: tableName, values })) {
50
49
  const column = table.columns[def.column];
51
- params[def.column] = ParamRef.of(
52
- def.value,
53
- column
54
- ? { codecId: column.codecId, refs: { table: tableName, column: def.column } }
55
- : undefined,
56
- );
50
+ const codec = column ? codecRefFor(ctx, tableName, def.column) : undefined;
51
+ params[def.column] = ParamRef.of(def.value, codec ? { codec } : undefined);
57
52
  }
58
53
  return params;
59
54
  }
@@ -64,7 +59,7 @@ function buildReturningProjections(
64
59
  rowFields: Record<string, ScopeField>,
65
60
  ): ProjectionItem[] {
66
61
  return columns.map((col) =>
67
- ProjectionItem.of(col, ColumnRef.of(tableName, col), rowFields[col]?.codecId),
62
+ ProjectionItem.of(col, ColumnRef.of(tableName, col), rowFields[col]?.codec),
68
63
  );
69
64
  }
70
65
 
@@ -16,6 +16,7 @@ export function sql<C extends Contract<SqlStorage>>(options: SqlOptions<C>): Db<
16
16
  queryOperationTypes: context.queryOperations.entries(),
17
17
  target: context.contract.target ?? 'unknown',
18
18
  storageHash: context.contract.storage.storageHash ?? 'unknown',
19
+ storage: context.contract.storage,
19
20
  applyMutationDefaults: (options) => context.applyMutationDefaults(options),
20
21
  };
21
22
 
@@ -59,7 +59,7 @@ export class TableProxyImpl<
59
59
  super(ctx);
60
60
  this.#tableName = tableName;
61
61
  this.#table = table;
62
- this.#scope = tableToScope(alias, table);
62
+ this.#scope = tableToScope(alias, table, { storage: ctx.storage, tableName });
63
63
  this.#fromSource = TableSource.named(tableName, alias !== tableName ? alias : undefined);
64
64
  }
65
65