@prisma-next/sql-builder 0.16.0-dev.30 → 0.16.0-dev.31

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.
@@ -233,6 +233,24 @@ function ifDefined(key, value) {
233
233
  return value !== void 0 ? blindCast({ [key]: value }) : {};
234
234
  }
235
235
  //#endregion
236
+ //#region ../../../1-framework/0-foundation/utils/dist/structured-error.mjs
237
+ function structuredError(code, message, options) {
238
+ const error = options?.cause !== void 0 ? new Error(message, { cause: options.cause }) : new Error(message);
239
+ Object.defineProperty(error, "name", {
240
+ value: "StructuredError",
241
+ configurable: true
242
+ });
243
+ return Object.assign(error, {
244
+ code,
245
+ ...ifDefined("why", options?.why),
246
+ ...ifDefined("fix", options?.fix),
247
+ ...ifDefined("where", options?.where),
248
+ ...ifDefined("severity", options?.severity),
249
+ ...ifDefined("meta", options?.meta),
250
+ ...ifDefined("docsUrl", options?.docsUrl)
251
+ });
252
+ }
253
+ //#endregion
236
254
  //#region src/runtime/builder-base.ts
237
255
  var BuilderBase = class {
238
256
  ctx;
@@ -375,7 +393,10 @@ function orderByScopeOf(scope, rowFields) {
375
393
  };
376
394
  }
377
395
  function assertCapability(ctx, required, methodName) {
378
- for (const [ns, keys] of Object.entries(required)) for (const key of Object.keys(keys)) if (!ctx.capabilities[ns]?.[key]) throw new Error(`${methodName}() requires capability ${ns}.${key}`);
396
+ for (const [ns, keys] of Object.entries(required)) for (const key of Object.keys(keys)) if (!ctx.capabilities[ns]?.[key]) throw structuredError("ORM.CAPABILITY_MISSING", `${methodName}() requires capability ${ns}.${key}`, { meta: {
397
+ method: methodName,
398
+ capability: `${ns}.${key}`
399
+ } });
379
400
  }
380
401
  function resolveSelectArgs(args, scope, ctx) {
381
402
  const projections = [];
@@ -387,7 +408,7 @@ function resolveSelectArgs(args, scope, ctx) {
387
408
  if (typeof args[0] === "string" && (args.length === 1 || typeof args[1] !== "function")) {
388
409
  for (const colName of args) {
389
410
  const field = scope.topLevel[colName];
390
- if (!field) throw new Error(`Column "${colName}" not found in scope`);
411
+ if (!field) throw structuredError("ORM.COLUMN_UNKNOWN", `Column "${colName}" not found in scope`, { meta: { column: colName } });
391
412
  projections.push(ProjectionItem.of(colName, IdentifierRef.of(colName), field.codec));
392
413
  newRowFields[colName] = field;
393
414
  }
@@ -423,12 +444,12 @@ function resolveSelectArgs(args, scope, ctx) {
423
444
  newRowFields
424
445
  };
425
446
  }
426
- throw new Error("Invalid .select() arguments");
447
+ throw structuredError("ORM.ARGUMENT_INVALID", "Invalid .select() arguments");
427
448
  }
428
449
  function resolveOrderBy(arg, options, scope, rowFields, ctx, useAggregateFns) {
429
450
  const dir = options?.direction ?? "asc";
430
451
  if (typeof arg === "string") {
431
- if (!(arg in orderByScopeOf(scope, rowFields).topLevel)) throw new Error(`Column "${arg}" not found in scope for orderBy`);
452
+ if (!(arg in orderByScopeOf(scope, rowFields).topLevel)) throw structuredError("ORM.COLUMN_UNKNOWN", `Column "${arg}" not found in scope for orderBy`, { meta: { column: arg } });
432
453
  const expr = IdentifierRef.of(arg);
433
454
  return dir === "asc" ? OrderByItem.asc(expr) : OrderByItem.desc(expr);
434
455
  }
@@ -438,13 +459,13 @@ function resolveOrderBy(arg, options, scope, rowFields, ctx, useAggregateFns) {
438
459
  const result = arg(createFieldProxy(combined), fns);
439
460
  return dir === "asc" ? OrderByItem.asc(result.buildAst()) : OrderByItem.desc(result.buildAst());
440
461
  }
441
- throw new Error("Invalid orderBy argument");
462
+ throw structuredError("ORM.ARGUMENT_INVALID", "Invalid orderBy argument");
442
463
  }
443
464
  function resolveGroupBy(args, scope, rowFields, ctx) {
444
465
  if (typeof args[0] === "string") {
445
466
  const combined = orderByScopeOf(scope, rowFields);
446
467
  return args.map((colName) => {
447
- if (!(colName in combined.topLevel)) throw new Error(`Column "${colName}" not found in scope for groupBy`);
468
+ if (!(colName in combined.topLevel)) throw structuredError("ORM.COLUMN_UNKNOWN", `Column "${colName}" not found in scope for groupBy`, { meta: { column: colName } });
448
469
  return IdentifierRef.of(colName);
449
470
  });
450
471
  }
@@ -453,7 +474,7 @@ function resolveGroupBy(args, scope, rowFields, ctx) {
453
474
  const fns = createFunctions(ctx.queryOperationTypes, ctx.rawCodecInferer);
454
475
  return [args[0](createFieldProxy(combined), fns).buildAst()];
455
476
  }
456
- throw new Error("Invalid groupBy arguments");
477
+ throw structuredError("ORM.ARGUMENT_INVALID", "Invalid groupBy arguments");
457
478
  }
458
479
  function resolveDistinctOn(args, scope, rowFields, ctx) {
459
480
  if (args.length === 1 && typeof args[0] === "function") {
@@ -463,7 +484,7 @@ function resolveDistinctOn(args, scope, rowFields, ctx) {
463
484
  }
464
485
  const combined = orderByScopeOf(scope, rowFields);
465
486
  return args.map((colName) => {
466
- if (!(colName in combined.topLevel)) throw new Error(`Column "${colName}" not found in scope for distinctOn`);
487
+ if (!(colName in combined.topLevel)) throw structuredError("ORM.COLUMN_UNKNOWN", `Column "${colName}" not found in scope for distinctOn`, { meta: { column: colName } });
467
488
  return IdentifierRef.of(colName);
468
489
  });
469
490
  }
@@ -741,7 +762,7 @@ var InsertQueryImpl = class InsertQueryImpl extends BuilderBase {
741
762
  const newRowFields = {};
742
763
  for (const col of columns) {
743
764
  const field = this.#scope.topLevel[col];
744
- if (!field) throw new Error(`Column "${col}" not found in scope`);
765
+ if (!field) throw structuredError("ORM.COLUMN_UNKNOWN", `Column "${col}" not found in scope`, { meta: { column: col } });
745
766
  newRowFields[col] = field;
746
767
  }
747
768
  return new InsertQueryImpl(this.#tableSource, this.#namespaceId, this.#table, this.#scope, this.#rows, this.ctx, columns, newRowFields, this.#annotations);
@@ -757,7 +778,7 @@ var InsertQueryImpl = class InsertQueryImpl extends BuilderBase {
757
778
  return new InsertQueryImpl(this.#tableSource, this.#namespaceId, this.#table, this.#scope, this.#rows, this.ctx, this.#returningColumns, this.#rowFields, mergeWriteAnnotations(this.#annotations, annotations));
758
779
  }
759
780
  build() {
760
- if (this.#rows.length === 0) throw new Error("insert() called with an empty row array — at least one row is required");
781
+ if (this.#rows.length === 0) throw structuredError("ORM.MUTATION_DATA_MISSING", "insert() called with an empty row array — at least one row is required");
761
782
  const paramRows = this.#rows.map((rowValues) => buildParamValues(rowValues, this.#namespaceId, this.#table, this.#tableName, "create", this.ctx));
762
783
  let ast = InsertAst.into(this.#tableSource).withRows(paramRows);
763
784
  if (this.#returningColumns.length > 0) ast = ast.withReturning(buildReturningProjections(this.#tableName, this.#returningColumns, this.#rowFields));
@@ -792,7 +813,7 @@ var UpdateQueryImpl = class UpdateQueryImpl extends BuilderBase {
792
813
  const newRowFields = {};
793
814
  for (const col of columns) {
794
815
  const field = this.#scope.topLevel[col];
795
- if (!field) throw new Error(`Column "${col}" not found in scope`);
816
+ if (!field) throw structuredError("ORM.COLUMN_UNKNOWN", `Column "${col}" not found in scope`, { meta: { column: col } });
796
817
  newRowFields[col] = field;
797
818
  }
798
819
  return new UpdateQueryImpl(this.#tableSource, this.#scope, this.#setExpressions, this.ctx, this.#whereExprs, columns, newRowFields, this.#annotations);
@@ -836,7 +857,7 @@ var DeleteQueryImpl = class DeleteQueryImpl extends BuilderBase {
836
857
  const newRowFields = {};
837
858
  for (const col of columns) {
838
859
  const field = this.#scope.topLevel[col];
839
- if (!field) throw new Error(`Column "${col}" not found in scope`);
860
+ if (!field) throw structuredError("ORM.COLUMN_UNKNOWN", `Column "${col}" not found in scope`, { meta: { column: col } });
840
861
  newRowFields[col] = field;
841
862
  }
842
863
  return new DeleteQueryImpl(this.#tableSource, this.#scope, this.ctx, this.#whereCallbacks, columns, newRowFields, this.#annotations);
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["#state","#buildLateral","#addLateralJoin","#addJoin","#tableSource","#tableName","#namespaceId","#table","#scope","#rows","#returningColumns","#rowFields","#annotations","#setExpressions","#whereExprs","#whereCallbacks","#tableName","#table","#namespaceId","#fromSource","#scope","#toJoined"],"sources":["../../src/runtime/expression-impl.ts","../../src/runtime/field-proxy.ts","../../src/runtime/functions.ts","../../src/runtime/resolve-table.ts","../../../../../1-framework/0-foundation/utils/dist/casts-DpaahrlC.mjs","../../../../../1-framework/0-foundation/utils/dist/defined-BQWA85QH.mjs","../../src/runtime/builder-base.ts","../../src/runtime/query-impl.ts","../../src/runtime/joined-tables-impl.ts","../../src/runtime/mutation-impl.ts","../../src/runtime/table-source-for-proxy.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 type { RawCodecInferer } from '@prisma-next/sql-relational-core/expression';\nimport { codecOf, createRawSql, 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(rawCodecInferer: RawCodecInferer) {\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 raw: createRawSql(rawCodecInferer),\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 rawCodecInferer: RawCodecInferer,\n): Functions<QC> {\n const builtins = createBuiltinFunctions(rawCodecInferer);\n\n return new Proxy({} as Functions<QC>, {\n get(_target, prop: string) {\n if (Object.hasOwn(builtins, prop)) {\n return (builtins as Record<string, unknown>)[prop];\n }\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 rawCodecInferer: RawCodecInferer,\n): AggregateFunctions<QC> {\n const baseFns = createFunctions<QC>(operations, rawCodecInferer);\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 { SqlStorage, StorageTable } from '@prisma-next/sql-contract/types';\n\nexport function resolveTableInNamespace(\n storage: SqlStorage,\n namespaceId: string,\n tableName: string,\n): StorageTable | undefined {\n const namespace = storage.namespaces[namespaceId];\n if (namespace === undefined) return undefined;\n const tables = namespace.entries.table;\n if (tables === undefined || !Object.hasOwn(tables, tableName)) return undefined;\n return tables[tableName];\n}\n","//#region src/casts.ts\n/**\n* **Last-resort escape hatch for unsafe type assertions. Not a sanctioned tool to reach for.**\n*\n* Before reaching for `blindCast`, **rewrite the surrounding code so the cast becomes\n* unnecessary**: tighten an input type, add a runtime check that narrows via a type\n* predicate, restructure a generic so the compiler can see the relationship you're\n* asserting, or use {@link castAs} when the value already satisfies the target type.\n* Only when no rewrite is feasible does `blindCast` become the right answer — and at\n* that point, the `Reason` literal you supply must articulate the compromise in\n* language a reviewer can evaluate.\n*\n* The reviewer **will** validate the `Reason`. If it doesn't hold up under scrutiny,\n* that is not a signal to soften the reason; it is a signal to go back and solve the\n* underlying type-system problem properly. An unconvincing justification is rework,\n* not a free pass.\n*\n* `blindCast` is the auditable form of `as Foo` / `as unknown as Foo`: it bypasses\n* the compiler's checks (the input type is `unknown`, the output type is whatever the\n* caller asks for), but it forces the unsafety to be named at the call site instead of\n* smuggled in via a bare `as`. The `Reason` type parameter exists only at compile\n* time — it is not present in the emitted JavaScript — but it is grep-able and\n* visible to future readers.\n*\n* @example\n* ```typescript\n* const stringValue = blindCast<\n* string,\n* \"JSON.parse returns `unknown`; this field is documented to be a string in the API contract\"\n* >(parsed[key]);\n* ```\n*\n* @typeParam TargetType - The type the caller is asserting the input has.\n* @typeParam _Reason - A string literal describing why bypassing the type system is necessary here.\n* Only meaningful at compile time. The reviewer evaluates whether it justifies the unsafety.\n*/\nfunction blindCast(input) {\n\treturn input;\n}\n/**\n* Type-checked, runtime pass-through alternative to a bare `as Type` cast.\n*\n* Use `castAs` when the value already satisfies the target type but you want to make\n* the type assertion explicit at the call site — for example, when an inferred type is\n* wider than the type you want to publish, or when a literal object should be tagged\n* with its nominal interface. Unlike {@link blindCast}, the compiler still checks that\n* the value is assignable to the target type, so this helper cannot smuggle in an\n* unsafe assertion.\n*\n* `castAs` exists alongside `blindCast` so authors pick the right name at the call\n* site: a `castAs` is type-checked and benign; a `blindCast` is the unsafe escape\n* hatch. The split makes review faster — readers know which casts to scrutinize and\n* which are pure annotations.\n*\n* @example\n* ```typescript\n* interface FancyObject {\n* key: string;\n* keyTwo: {\n* subKey: string;\n* subKeyTwo: number;\n* };\n* }\n*\n* const typedObject = castAs<FancyObject>({\n* key: 'Chookede',\n* keyTwo: {\n* subKey: 'Choookeeeee',\n* subKeyTwo: 2,\n* },\n* });\n* ```\n*\n* @typeParam Type - The type to constrain and tag the value with. The value must be assignable to `Type`.\n*/\nfunction castAs(value) {\n\treturn value;\n}\n//#endregion\nexport { castAs as n, blindCast as t };\n\n//# sourceMappingURL=casts-DpaahrlC.mjs.map","import { t as blindCast } from \"./casts-DpaahrlC.mjs\";\n//#region src/defined.ts\n/**\n* Returns an object with the key/value if value is defined, otherwise an empty object.\n*\n* Use with spread to conditionally include optional properties while satisfying\n* exactOptionalPropertyTypes. This is explicit about which properties are optional\n* and won't inadvertently strip other undefined values.\n*\n* @example\n* ```typescript\n* // Instead of:\n* const obj = {\n* required: 'value',\n* ...(optional ? { optional } : {}),\n* };\n*\n* // Use:\n* const obj = {\n* required: 'value',\n* ...ifDefined('optional', optional),\n* };\n* ```\n*/\nfunction ifDefined(key, value) {\n\treturn value !== void 0 ? blindCast({ [key]: value }) : {};\n}\n//#endregion\nexport { ifDefined as t };\n\n//# sourceMappingURL=defined-BQWA85QH.mjs.map","import type { PlanMeta } from '@prisma-next/contract/types';\nimport type { CodecRef } from '@prisma-next/framework-components/codec';\nimport type { AnnotationValue, OperationKind } from '@prisma-next/framework-components/runtime';\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 type LimitOffsetValue,\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 { RawCodecInferer } from '@prisma-next/sql-relational-core/expression';\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 { ifDefined } from '@prisma-next/utils/defined';\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: LimitOffsetValue | undefined;\n readonly offset: LimitOffsetValue | undefined;\n readonly distinct: true | undefined;\n readonly distinctOn: readonly AstExpression[] | undefined;\n readonly scope: Scope;\n readonly rowFields: Record<string, ScopeField>;\n /**\n * Annotations accumulated through `.annotate(...)` calls. Stored as\n * a `Map<namespace, AnnotationValue>` so duplicate namespaces\n * last-write-win. Empty on a fresh state.\n */\n readonly annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>;\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 * Codec inferer used inside `createBuiltinFunctions` to construct the raw-SQL tag — `fns.raw` dispatches through `inferCodec(value)` for bare-literal interpolations.\n */\n readonly rawCodecInferer: RawCodecInferer;\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 namespaceId: string,\n tableName: string,\n columnName: string,\n): CodecRef | undefined {\n if (!ctx.storage) return undefined;\n return codecRefForStorageColumn(ctx.storage, namespaceId, 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 annotations: new Map(),\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 annotations?: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>,\n): SqlQueryPlan<Row> {\n const paramValues = collectOrderedParamRefs(ast).map((r) =>\n r.kind === 'param-ref' ? r.value : undefined,\n );\n\n // SQL DSL has no framework-reserved namespace keys (e.g. `codecs`) in\n // scope at `.build()` time, so user annotations land verbatim here. The\n // ORM dispatch path — which compiles to plans that may already carry\n // reserved keys — enforces the precedence rule in `mergeAnnotations`\n // (`sql-orm-client/src/query-plan-meta.ts`).\n const annotationsRecord =\n annotations !== undefined && annotations.size > 0\n ? Object.freeze(Object.fromEntries(annotations))\n : undefined;\n const meta: PlanMeta = Object.freeze({\n target: ctx.target,\n storageHash: ctx.storageHash,\n lane: 'dsl',\n ...ifDefined('annotations', annotationsRecord),\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, state.annotations);\n}\n\nexport function tableToScope(\n alias: string,\n table: StorageTable,\n options?: {\n readonly storage?: SqlStorage | undefined;\n readonly namespaceId?: string | undefined;\n readonly tableName?: string | undefined;\n },\n): Scope {\n const storage = options?.storage;\n const lookupName = options?.tableName;\n const namespaceId = options?.namespaceId;\n const fields: ScopeTable = {};\n for (const [colName, col] of Object.entries(table.columns)) {\n const codec =\n storage && lookupName && namespaceId !== undefined\n ? codecRefForStorageColumn(storage, namespaceId, lookupName, colName)\n : undefined;\n fields[colName] = {\n codecId: col.codecId,\n nullable: col.nullable,\n ...(col.many ? { many: true as const } : {}),\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, ctx.rawCodecInferer);\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, ctx.rawCodecInferer);\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, ctx.rawCodecInferer)\n : createFunctions(ctx.queryOperationTypes, ctx.rawCodecInferer);\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, ctx.rawCodecInferer);\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, ctx.rawCodecInferer);\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 type {\n AnnotationValue,\n OperationKind,\n ValidAnnotations,\n} from '@prisma-next/framework-components/runtime';\nimport { assertAnnotationsApplicable } from '@prisma-next/framework-components/runtime';\nimport { DerivedTableSource, type SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport { toExpr } from '@prisma-next/sql-relational-core/expression';\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 type { PaginationValue } from '../types/shared';\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: PaginationValue<QC>): this {\n const limit = typeof count === 'number' ? count : toExpr(count);\n return this.clone(cloneState(this.state, { limit }));\n }\n\n offset(count: PaginationValue<QC>): this {\n const offset = typeof count === 'number' ? count : toExpr(count);\n return this.clone(cloneState(this.state, { offset }));\n }\n\n distinct(): this {\n return this.clone(cloneState(this.state, { distinct: true }));\n }\n\n /**\n * Attach one or more annotations to this query plan.\n *\n * Read builders (`SelectQueryImpl`, `GroupedQueryImpl`) accept\n * annotations whose declared `applicableTo` includes `'read'`.\n * The type-level `As & ValidAnnotations<'read', As>` gate rejects\n * write-only annotations at the call site; the runtime check below\n * fails closed for callers that bypass the type gate (cast / `any`).\n *\n * Multiple `.annotate(...)` calls compose; duplicate namespaces use\n * last-write-wins. The accumulated annotations are merged into\n * `plan.meta.annotations` at `.build()` time, alongside any framework-\n * internal metadata under reserved namespaces (e.g. `codecs`).\n *\n * Chainable in any position (before / after `.where`, `.select`,\n * `.limit`, etc.); the returned builder has the same row type.\n */\n annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(\n ...annotations: As & ValidAnnotations<'read', As>\n ): this {\n assertAnnotationsApplicable(\n annotations as readonly AnnotationValue<unknown, OperationKind>[],\n 'read',\n 'sql-dsl.annotate',\n );\n const next = new Map(this.state.annotations);\n for (const annotation of annotations as readonly AnnotationValue<unknown, OperationKind>[]) {\n next.set(annotation.namespace, annotation);\n }\n return this.clone(cloneState(this.state, { annotations: next }));\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, this.ctx.rawCodecInferer);\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<QC>(\n this.ctx.queryOperationTypes,\n this.ctx.rawCodecInferer,\n );\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, this.ctx.rawCodecInferer);\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 {\n AnnotationValue,\n OperationKind,\n ValidAnnotations,\n} from '@prisma-next/framework-components/runtime';\nimport { assertAnnotationsApplicable } from '@prisma-next/framework-components/runtime';\nimport 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 type 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 { ifDefined } from '@prisma-next/utils/defined';\nimport type { Expression, 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\n/**\n * Validates and merges a variadic annotations call into a builder's\n * accumulated user-annotations map. Used by `.annotate(...)` on each of\n * the three mutation builders (`InsertQueryImpl`, `UpdateQueryImpl`,\n * `DeleteQueryImpl`); the read builders share the same logic via\n * `QueryBase.annotate()` in `./query-impl.ts`.\n *\n * Runs `assertAnnotationsApplicable` at call time (not at `.build()`) so\n * inapplicable annotations forced through casts surface immediately\n * rather than at plan-construction time.\n */\nfunction mergeWriteAnnotations(\n current: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>,\n annotations: readonly AnnotationValue<unknown, OperationKind>[],\n): ReadonlyMap<string, AnnotationValue<unknown, OperationKind>> {\n assertAnnotationsApplicable(annotations, 'write', 'sql-dsl.annotate');\n const next = new Map(current);\n for (const annotation of annotations) {\n next.set(annotation.namespace, annotation);\n }\n return next;\n}\n\ntype WhereCallback = ExpressionBuilder<Scope, QueryContext>;\nexport type UpdateSetCallback = (\n fields: ReturnType<typeof createFieldProxy>,\n fns: ReturnType<typeof createFunctions>,\n) => Record<string, Expression<ScopeField> | undefined>;\n\nexport function buildParamValues(\n values: Record<string, unknown>,\n namespaceId: string,\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, namespaceId, tableName, col) : undefined;\n params[col] = ParamRef.of(value, codec ? { codec } : undefined);\n }\n for (const def of ctx.applyMutationDefaults({\n op,\n namespace: namespaceId,\n table: tableName,\n values,\n })) {\n const column = table.columns[def.column];\n const codec = column ? codecRefFor(ctx, namespaceId, 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 rawCodecInferer: BuilderContext['rawCodecInferer'],\n): AstExpression {\n const fieldProxy = createFieldProxy(scope);\n const fns = createFunctions(queryOperationTypes, rawCodecInferer);\n const result = whereCallback(fieldProxy, fns as never);\n return result.buildAst();\n}\n\nexport function evaluateUpdateCallback(\n callback: UpdateSetCallback,\n scope: Scope,\n queryOperationTypes: BuilderContext['queryOperationTypes'],\n rawCodecInferer: BuilderContext['rawCodecInferer'],\n): Record<string, AstExpression> {\n const fieldProxy = createFieldProxy(scope);\n const fns = createFunctions(queryOperationTypes, rawCodecInferer);\n const result = callback(fieldProxy, fns as never);\n const set: Record<string, AstExpression> = {};\n for (const [col, expr] of Object.entries(result)) {\n if (expr !== undefined) {\n set[col] = expr.buildAst();\n }\n }\n return set;\n}\n\nexport function buildSetExpressions(\n exprs: Record<string, AstExpression>,\n namespaceId: string,\n table: StorageTable,\n tableName: string,\n op: MutationDefaultsOp,\n ctx: BuilderContext,\n): Record<string, AstExpression> {\n const set: Record<string, AstExpression> = { ...exprs };\n for (const def of ctx.applyMutationDefaults({\n op,\n namespace: namespaceId,\n table: tableName,\n values: exprs,\n })) {\n if (!(def.column in set)) {\n const column = table.columns[def.column];\n const codec = column ? codecRefFor(ctx, namespaceId, tableName, def.column) : undefined;\n set[def.column] = ParamRef.of(def.value, ifDefined('codec', codec));\n }\n }\n return set;\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 #tableSource: TableSource;\n readonly #tableName: string;\n readonly #namespaceId: string;\n readonly #table: StorageTable;\n readonly #scope: Scope;\n readonly #rows: ReadonlyArray<Record<string, unknown>>;\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n readonly #annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>;\n\n constructor(\n tableSource: TableSource,\n namespaceId: string,\n table: StorageTable,\n scope: Scope,\n rows: ReadonlyArray<Record<string, unknown>>,\n ctx: BuilderContext,\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>> = new Map(),\n ) {\n super(ctx);\n this.#tableSource = tableSource;\n this.#tableName = tableSource.name;\n this.#namespaceId = namespaceId;\n this.#table = table;\n this.#scope = scope;\n this.#rows = rows;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n this.#annotations = annotations;\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.#tableSource,\n this.#namespaceId,\n this.#table,\n this.#scope,\n this.#rows,\n this.ctx,\n columns,\n newRowFields,\n this.#annotations,\n ) as unknown as InsertQuery<QC, AvailableScope, never>;\n },\n );\n\n /**\n * Attach one or more write-typed annotations to this query plan.\n * The type-level `As & ValidAnnotations<'write', As>` gate rejects\n * read-only annotations at the call site; the runtime check fails\n * closed for callers that bypass the type gate. See `QueryBase.annotate`\n * in `./query-impl.ts` for the read-builder counterpart.\n */\n annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(\n ...annotations: As & ValidAnnotations<'write', As>\n ): InsertQuery<QC, AvailableScope, RowType> {\n return new InsertQueryImpl(\n this.#tableSource,\n this.#namespaceId,\n this.#table,\n this.#scope,\n this.#rows,\n this.ctx,\n this.#returningColumns,\n this.#rowFields,\n mergeWriteAnnotations(\n this.#annotations,\n annotations as readonly AnnotationValue<unknown, OperationKind>[],\n ),\n );\n }\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n if (this.#rows.length === 0) {\n throw new Error('insert() called with an empty row array — at least one row is required');\n }\n\n const paramRows = this.#rows.map((rowValues) =>\n buildParamValues(\n rowValues,\n this.#namespaceId,\n this.#table,\n this.#tableName,\n 'create',\n this.ctx,\n ),\n );\n\n let ast = InsertAst.into(this.#tableSource).withRows(paramRows);\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 this.#annotations,\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 #tableSource: TableSource;\n readonly #tableName: string;\n readonly #scope: Scope;\n readonly #setExpressions: Record<string, AstExpression>;\n readonly #whereExprs: readonly AstExpression[];\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n readonly #annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>;\n\n constructor(\n tableSource: TableSource,\n scope: Scope,\n setExpressions: Record<string, AstExpression>,\n ctx: BuilderContext,\n whereExprs: readonly AstExpression[] = [],\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>> = new Map(),\n ) {\n super(ctx);\n this.#tableSource = tableSource;\n this.#tableName = tableSource.name;\n this.#scope = scope;\n this.#setExpressions = setExpressions;\n this.#whereExprs = whereExprs;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n this.#annotations = annotations;\n }\n\n where(expr: ExpressionBuilder<AvailableScope, QC>): UpdateQuery<QC, AvailableScope, RowType> {\n const fieldProxy = createFieldProxy(this.#scope);\n const fns = createFunctions(this.ctx.queryOperationTypes, this.ctx.rawCodecInferer);\n const result = (expr as ExpressionBuilder<Scope, QueryContext>)(fieldProxy, fns as never);\n return new UpdateQueryImpl(\n this.#tableSource,\n this.#scope,\n this.#setExpressions,\n this.ctx,\n [...this.#whereExprs, result.buildAst()],\n this.#returningColumns,\n this.#rowFields,\n this.#annotations,\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.#tableSource,\n this.#scope,\n this.#setExpressions,\n this.ctx,\n this.#whereExprs,\n columns,\n newRowFields,\n this.#annotations,\n ) as unknown as UpdateQuery<QC, AvailableScope, never>;\n },\n );\n\n /**\n * Attach one or more write-typed annotations to this query plan.\n * See `InsertQueryImpl.annotate` for semantics; the runtime check\n * fails closed for callers that bypass the type-level gate.\n */\n annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(\n ...annotations: As & ValidAnnotations<'write', As>\n ): UpdateQuery<QC, AvailableScope, RowType> {\n return new UpdateQueryImpl(\n this.#tableSource,\n this.#scope,\n this.#setExpressions,\n this.ctx,\n this.#whereExprs,\n this.#returningColumns,\n this.#rowFields,\n mergeWriteAnnotations(\n this.#annotations,\n annotations as readonly AnnotationValue<unknown, OperationKind>[],\n ),\n );\n }\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n let ast = UpdateAst.table(this.#tableSource)\n .withSet(this.#setExpressions)\n .withWhere(combineWhereExprs(this.#whereExprs));\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 this.#annotations,\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 #tableSource: TableSource;\n readonly #tableName: string;\n readonly #scope: Scope;\n readonly #whereCallbacks: readonly WhereCallback[];\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n readonly #annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>;\n\n constructor(\n tableSource: TableSource,\n scope: Scope,\n ctx: BuilderContext,\n whereCallbacks: readonly WhereCallback[] = [],\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>> = new Map(),\n ) {\n super(ctx);\n this.#tableSource = tableSource;\n this.#tableName = tableSource.name;\n this.#scope = scope;\n this.#whereCallbacks = whereCallbacks;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n this.#annotations = annotations;\n }\n\n where(expr: ExpressionBuilder<AvailableScope, QC>): DeleteQuery<QC, AvailableScope, RowType> {\n return new DeleteQueryImpl(\n this.#tableSource,\n this.#scope,\n this.ctx,\n [...this.#whereCallbacks, expr as unknown as WhereCallback],\n this.#returningColumns,\n this.#rowFields,\n this.#annotations,\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.#tableSource,\n this.#scope,\n this.ctx,\n this.#whereCallbacks,\n columns,\n newRowFields,\n this.#annotations,\n ) as unknown as DeleteQuery<QC, AvailableScope, never>;\n },\n );\n\n /**\n * Attach one or more write-typed annotations to this query plan.\n * See `InsertQueryImpl.annotate` for semantics.\n */\n annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(\n ...annotations: As & ValidAnnotations<'write', As>\n ): DeleteQuery<QC, AvailableScope, RowType> {\n return new DeleteQueryImpl(\n this.#tableSource,\n this.#scope,\n this.ctx,\n this.#whereCallbacks,\n this.#returningColumns,\n this.#rowFields,\n mergeWriteAnnotations(\n this.#annotations,\n annotations as readonly AnnotationValue<unknown, OperationKind>[],\n ),\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, this.ctx.rawCodecInferer),\n ),\n );\n\n let ast = DeleteAst.from(this.#tableSource).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 this.#annotations,\n );\n }\n}\n","import { TableSource } from '@prisma-next/sql-relational-core/ast';\n\nexport function tableSourceForProxy(\n tableName: string,\n alias: string,\n namespaceId: string,\n): TableSource {\n return TableSource.named(tableName, alias !== tableName ? alias : undefined, namespaceId);\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 Functions,\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 { NamespaceTable, 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 {\n buildParamValues,\n buildSetExpressions,\n DeleteQueryImpl,\n evaluateUpdateCallback,\n InsertQueryImpl,\n UpdateQueryImpl,\n type UpdateSetCallback,\n} from './mutation-impl';\nimport { SelectQueryImpl } from './query-impl';\nimport { tableSourceForProxy } from './table-source-for-proxy';\n\nexport class TableProxyImpl<\n C extends TableProxyContract,\n Name extends string,\n Alias extends string,\n AvailableScope extends Scope,\n QC extends QueryContext,\n NsId extends string = string,\n >\n extends BuilderBase<C['capabilities']>\n implements TableProxy<C, NsId, Name, Alias, AvailableScope, QC>\n{\n declare readonly [JoinOuterScope]: JoinSource<\n StorageTableToScopeTable<NamespaceTable<C, NsId, Name>>,\n Alias\n >[typeof JoinOuterScope];\n\n readonly #tableName: string;\n readonly #table: StorageTable;\n readonly #namespaceId: string;\n readonly #fromSource: TableSource;\n readonly #scope: Scope;\n\n constructor(\n tableName: string,\n table: StorageTable,\n alias: string,\n ctx: BuilderContext,\n namespaceId: string,\n ) {\n super(ctx);\n this.#tableName = tableName;\n this.#table = table;\n this.#namespaceId = namespaceId;\n this.#scope = tableToScope(alias, table, {\n storage: ctx.storage,\n tableName,\n namespaceId,\n });\n this.#fromSource = tableSourceForProxy(tableName, alias, namespaceId);\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, NsId, 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, NsId, 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, NsId, Name, NewAlias, RebindScope<AvailableScope, Alias, NewAlias>, QC> {\n return new TableProxyImpl<\n C,\n Name,\n NewAlias,\n RebindScope<AvailableScope, Alias, NewAlias>,\n QC,\n NsId\n >(this.#tableName, this.#table, newAlias, this.ctx, this.#namespaceId);\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(rows: ReadonlyArray<Record<string, unknown>>): InsertQuery<QC, AvailableScope, EmptyRow> {\n return new InsertQueryImpl(\n this.#fromSource,\n this.#namespaceId,\n this.#table,\n this.#scope,\n rows,\n this.ctx,\n );\n }\n\n update(\n setOrCallback:\n | Record<string, unknown>\n | ((\n fields: FieldProxy<AvailableScope>,\n fns: Functions<QC>,\n ) => Record<string, Expression<ScopeField> | undefined>),\n ): UpdateQuery<QC, AvailableScope, EmptyRow> {\n if (typeof setOrCallback === 'function') {\n const callbackExprs = evaluateUpdateCallback(\n setOrCallback as UpdateSetCallback,\n this.#scope,\n this.ctx.queryOperationTypes,\n this.ctx.rawCodecInferer,\n );\n const setExpressions = buildSetExpressions(\n callbackExprs,\n this.#namespaceId,\n this.#table,\n this.#tableName,\n 'update',\n this.ctx,\n );\n return new UpdateQueryImpl(this.#fromSource, this.#scope, setExpressions, this.ctx);\n }\n const setExpressions = buildParamValues(\n setOrCallback,\n this.#namespaceId,\n this.#table,\n this.#tableName,\n 'update',\n this.ctx,\n );\n return new UpdateQueryImpl(this.#fromSource, this.#scope, setExpressions, this.ctx);\n }\n\n delete(): DeleteQuery<QC, AvailableScope, EmptyRow> {\n return new DeleteQueryImpl(this.#fromSource, 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 { RawCodecInferer } from '@prisma-next/sql-relational-core/expression';\nimport type { ExecutionContext } from '@prisma-next/sql-relational-core/query-lane-context';\nimport type { Db, TableProxyContract } from '../types/db';\nimport type { BuilderContext } from './builder-base';\nimport { resolveTableInNamespace } from './resolve-table';\nimport { TableProxyImpl } from './table-proxy-impl';\n\nexport interface SqlOptions<C extends Contract<SqlStorage> & TableProxyContract> {\n readonly context: ExecutionContext<C>;\n readonly rawCodecInferer: RawCodecInferer;\n}\n\nexport function sql<C extends Contract<SqlStorage> & TableProxyContract>(\n options: SqlOptions<C>,\n): Db<C> {\n const { context, rawCodecInferer } = 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 rawCodecInferer,\n };\n\n const { storage } = context.contract;\n\n return new Proxy({} as Db<C>, {\n get(_target, prop: string | symbol) {\n if (typeof prop !== 'string') {\n return undefined;\n }\n if (!Object.hasOwn(storage.namespaces, prop)) {\n return undefined;\n }\n const namespaceId = prop;\n return new Proxy(\n {},\n {\n get(_facetTarget, tableName: string | symbol) {\n if (typeof tableName !== 'string') {\n return undefined;\n }\n const table = resolveTableInNamespace(storage, namespaceId, tableName);\n if (table) {\n // `namespaceId` is a dynamic Proxy key with no static literal here, so the\n // proxy's `NsId` type param lands on its `string` default at this boundary.\n // `TableProxyImpl` still forwards `NsId` through its `as()`/join chain.\n return new TableProxyImpl(tableName, table, tableName, ctx, namespaceId);\n }\n return undefined;\n },\n },\n );\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;CACf;CAEA,WAA0B;EACxB,OAAO,KAAK;CACd;AACF;;;ACnBA,SAAgB,iBAAkC,OAAyB;CACzE,OAAO,IAAI,MAAM,CAAC,GAAoB,EACpC,IAAI,SAAS,MAAc;EACzB,IAAI,OAAO,OAAO,MAAM,UAAU,IAAI,GAAG;GACvC,MAAM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#addLateralJoin","#addJoin","#tableSource","#tableName","#namespaceId","#table","#scope","#rows","#returningColumns","#rowFields","#annotations","#setExpressions","#whereExprs","#whereCallbacks","#tableName","#table","#namespaceId","#fromSource","#scope","#toJoined"],"sources":["../../src/runtime/expression-impl.ts","../../src/runtime/field-proxy.ts","../../src/runtime/functions.ts","../../src/runtime/resolve-table.ts","../../../../../1-framework/0-foundation/utils/dist/casts-DpaahrlC.mjs","../../../../../1-framework/0-foundation/utils/dist/defined-BQWA85QH.mjs","../../../../../1-framework/0-foundation/utils/dist/structured-error.mjs","../../src/runtime/builder-base.ts","../../src/runtime/query-impl.ts","../../src/runtime/joined-tables-impl.ts","../../src/runtime/mutation-impl.ts","../../src/runtime/table-source-for-proxy.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 type { RawCodecInferer } from '@prisma-next/sql-relational-core/expression';\nimport { codecOf, createRawSql, 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(rawCodecInferer: RawCodecInferer) {\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 raw: createRawSql(rawCodecInferer),\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 rawCodecInferer: RawCodecInferer,\n): Functions<QC> {\n const builtins = createBuiltinFunctions(rawCodecInferer);\n\n return new Proxy({} as Functions<QC>, {\n get(_target, prop: string) {\n if (Object.hasOwn(builtins, prop)) {\n return (builtins as Record<string, unknown>)[prop];\n }\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 rawCodecInferer: RawCodecInferer,\n): AggregateFunctions<QC> {\n const baseFns = createFunctions<QC>(operations, rawCodecInferer);\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 { SqlStorage, StorageTable } from '@prisma-next/sql-contract/types';\n\nexport function resolveTableInNamespace(\n storage: SqlStorage,\n namespaceId: string,\n tableName: string,\n): StorageTable | undefined {\n const namespace = storage.namespaces[namespaceId];\n if (namespace === undefined) return undefined;\n const tables = namespace.entries.table;\n if (tables === undefined || !Object.hasOwn(tables, tableName)) return undefined;\n return tables[tableName];\n}\n","//#region src/casts.ts\n/**\n* **Last-resort escape hatch for unsafe type assertions. Not a sanctioned tool to reach for.**\n*\n* Before reaching for `blindCast`, **rewrite the surrounding code so the cast becomes\n* unnecessary**: tighten an input type, add a runtime check that narrows via a type\n* predicate, restructure a generic so the compiler can see the relationship you're\n* asserting, or use {@link castAs} when the value already satisfies the target type.\n* Only when no rewrite is feasible does `blindCast` become the right answer — and at\n* that point, the `Reason` literal you supply must articulate the compromise in\n* language a reviewer can evaluate.\n*\n* The reviewer **will** validate the `Reason`. If it doesn't hold up under scrutiny,\n* that is not a signal to soften the reason; it is a signal to go back and solve the\n* underlying type-system problem properly. An unconvincing justification is rework,\n* not a free pass.\n*\n* `blindCast` is the auditable form of `as Foo` / `as unknown as Foo`: it bypasses\n* the compiler's checks (the input type is `unknown`, the output type is whatever the\n* caller asks for), but it forces the unsafety to be named at the call site instead of\n* smuggled in via a bare `as`. The `Reason` type parameter exists only at compile\n* time — it is not present in the emitted JavaScript — but it is grep-able and\n* visible to future readers.\n*\n* @example\n* ```typescript\n* const stringValue = blindCast<\n* string,\n* \"JSON.parse returns `unknown`; this field is documented to be a string in the API contract\"\n* >(parsed[key]);\n* ```\n*\n* @typeParam TargetType - The type the caller is asserting the input has.\n* @typeParam _Reason - A string literal describing why bypassing the type system is necessary here.\n* Only meaningful at compile time. The reviewer evaluates whether it justifies the unsafety.\n*/\nfunction blindCast(input) {\n\treturn input;\n}\n/**\n* Type-checked, runtime pass-through alternative to a bare `as Type` cast.\n*\n* Use `castAs` when the value already satisfies the target type but you want to make\n* the type assertion explicit at the call site — for example, when an inferred type is\n* wider than the type you want to publish, or when a literal object should be tagged\n* with its nominal interface. Unlike {@link blindCast}, the compiler still checks that\n* the value is assignable to the target type, so this helper cannot smuggle in an\n* unsafe assertion.\n*\n* `castAs` exists alongside `blindCast` so authors pick the right name at the call\n* site: a `castAs` is type-checked and benign; a `blindCast` is the unsafe escape\n* hatch. The split makes review faster — readers know which casts to scrutinize and\n* which are pure annotations.\n*\n* @example\n* ```typescript\n* interface FancyObject {\n* key: string;\n* keyTwo: {\n* subKey: string;\n* subKeyTwo: number;\n* };\n* }\n*\n* const typedObject = castAs<FancyObject>({\n* key: 'Chookede',\n* keyTwo: {\n* subKey: 'Choookeeeee',\n* subKeyTwo: 2,\n* },\n* });\n* ```\n*\n* @typeParam Type - The type to constrain and tag the value with. The value must be assignable to `Type`.\n*/\nfunction castAs(value) {\n\treturn value;\n}\n//#endregion\nexport { castAs as n, blindCast as t };\n\n//# sourceMappingURL=casts-DpaahrlC.mjs.map","import { t as blindCast } from \"./casts-DpaahrlC.mjs\";\n//#region src/defined.ts\n/**\n* Returns an object with the key/value if value is defined, otherwise an empty object.\n*\n* Use with spread to conditionally include optional properties while satisfying\n* exactOptionalPropertyTypes. This is explicit about which properties are optional\n* and won't inadvertently strip other undefined values.\n*\n* @example\n* ```typescript\n* // Instead of:\n* const obj = {\n* required: 'value',\n* ...(optional ? { optional } : {}),\n* };\n*\n* // Use:\n* const obj = {\n* required: 'value',\n* ...ifDefined('optional', optional),\n* };\n* ```\n*/\nfunction ifDefined(key, value) {\n\treturn value !== void 0 ? blindCast({ [key]: value }) : {};\n}\n//#endregion\nexport { ifDefined as t };\n\n//# sourceMappingURL=defined-BQWA85QH.mjs.map","import { t as ifDefined } from \"./defined-BQWA85QH.mjs\";\n//#region src/structured-error.ts\nconst STRUCTURED_CODE_RE = /^[A-Z][A-Z0-9]*\\.[A-Z][A-Z0-9_]*$/;\nfunction isStructuredError(e) {\n\treturn typeof e === \"object\" && e !== null && \"code\" in e && typeof e.code === \"string\" && STRUCTURED_CODE_RE.test(e.code) && \"message\" in e && typeof e.message === \"string\";\n}\nfunction structuredError(code, message, options) {\n\tconst error = options?.cause !== void 0 ? new Error(message, { cause: options.cause }) : new Error(message);\n\tObject.defineProperty(error, \"name\", {\n\t\tvalue: \"StructuredError\",\n\t\tconfigurable: true\n\t});\n\treturn Object.assign(error, {\n\t\tcode,\n\t\t...ifDefined(\"why\", options?.why),\n\t\t...ifDefined(\"fix\", options?.fix),\n\t\t...ifDefined(\"where\", options?.where),\n\t\t...ifDefined(\"severity\", options?.severity),\n\t\t...ifDefined(\"meta\", options?.meta),\n\t\t...ifDefined(\"docsUrl\", options?.docsUrl)\n\t});\n}\nconst DOCS_ERRORS_VERSION = \"next\";\nconst DOCS_BASE = `https://docs.prisma.io/docs/orm/${DOCS_ERRORS_VERSION}/reference/error-reference`;\nfunction docsUrlFor(code) {\n\treturn `${DOCS_BASE}#${code}`;\n}\n//#endregion\nexport { DOCS_BASE, DOCS_ERRORS_VERSION, docsUrlFor, isStructuredError, structuredError };\n\n//# sourceMappingURL=structured-error.mjs.map","import type { PlanMeta } from '@prisma-next/contract/types';\nimport type { CodecRef } from '@prisma-next/framework-components/codec';\nimport type { AnnotationValue, OperationKind } from '@prisma-next/framework-components/runtime';\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 type LimitOffsetValue,\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 { RawCodecInferer } from '@prisma-next/sql-relational-core/expression';\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 { ifDefined } from '@prisma-next/utils/defined';\nimport { structuredError } from '@prisma-next/utils/structured-error';\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: LimitOffsetValue | undefined;\n readonly offset: LimitOffsetValue | undefined;\n readonly distinct: true | undefined;\n readonly distinctOn: readonly AstExpression[] | undefined;\n readonly scope: Scope;\n readonly rowFields: Record<string, ScopeField>;\n /**\n * Annotations accumulated through `.annotate(...)` calls. Stored as\n * a `Map<namespace, AnnotationValue>` so duplicate namespaces\n * last-write-win. Empty on a fresh state.\n */\n readonly annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>;\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 * Codec inferer used inside `createBuiltinFunctions` to construct the raw-SQL tag — `fns.raw` dispatches through `inferCodec(value)` for bare-literal interpolations.\n */\n readonly rawCodecInferer: RawCodecInferer;\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 namespaceId: string,\n tableName: string,\n columnName: string,\n): CodecRef | undefined {\n if (!ctx.storage) return undefined;\n return codecRefForStorageColumn(ctx.storage, namespaceId, 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 annotations: new Map(),\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 annotations?: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>,\n): SqlQueryPlan<Row> {\n const paramValues = collectOrderedParamRefs(ast).map((r) =>\n r.kind === 'param-ref' ? r.value : undefined,\n );\n\n // SQL DSL has no framework-reserved namespace keys (e.g. `codecs`) in\n // scope at `.build()` time, so user annotations land verbatim here. The\n // ORM dispatch path — which compiles to plans that may already carry\n // reserved keys — enforces the precedence rule in `mergeAnnotations`\n // (`sql-orm-client/src/query-plan-meta.ts`).\n const annotationsRecord =\n annotations !== undefined && annotations.size > 0\n ? Object.freeze(Object.fromEntries(annotations))\n : undefined;\n const meta: PlanMeta = Object.freeze({\n target: ctx.target,\n storageHash: ctx.storageHash,\n lane: 'dsl',\n ...ifDefined('annotations', annotationsRecord),\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, state.annotations);\n}\n\nexport function tableToScope(\n alias: string,\n table: StorageTable,\n options?: {\n readonly storage?: SqlStorage | undefined;\n readonly namespaceId?: string | undefined;\n readonly tableName?: string | undefined;\n },\n): Scope {\n const storage = options?.storage;\n const lookupName = options?.tableName;\n const namespaceId = options?.namespaceId;\n const fields: ScopeTable = {};\n for (const [colName, col] of Object.entries(table.columns)) {\n const codec =\n storage && lookupName && namespaceId !== undefined\n ? codecRefForStorageColumn(storage, namespaceId, lookupName, colName)\n : undefined;\n fields[colName] = {\n codecId: col.codecId,\n nullable: col.nullable,\n ...(col.many ? { many: true as const } : {}),\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 structuredError(\n 'ORM.CAPABILITY_MISSING',\n `${methodName}() requires capability ${ns}.${key}`,\n { meta: { method: methodName, capability: `${ns}.${key}` } },\n );\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)\n throw structuredError('ORM.COLUMN_UNKNOWN', `Column \"${colName}\" not found in scope`, {\n meta: { column: colName },\n });\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, ctx.rawCodecInferer);\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, ctx.rawCodecInferer);\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 structuredError('ORM.ARGUMENT_INVALID', '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 structuredError(\n 'ORM.COLUMN_UNKNOWN',\n `Column \"${arg}\" not found in scope for orderBy`,\n {\n meta: { column: arg },\n },\n );\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, ctx.rawCodecInferer)\n : createFunctions(ctx.queryOperationTypes, ctx.rawCodecInferer);\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 structuredError('ORM.ARGUMENT_INVALID', '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 structuredError(\n 'ORM.COLUMN_UNKNOWN',\n `Column \"${colName}\" not found in scope for groupBy`,\n { meta: { column: colName } },\n );\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, ctx.rawCodecInferer);\n const result = (args[0] as ExprCallback)(createFieldProxy(combined), fns);\n return [result.buildAst()];\n }\n\n throw structuredError('ORM.ARGUMENT_INVALID', '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, ctx.rawCodecInferer);\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 structuredError(\n 'ORM.COLUMN_UNKNOWN',\n `Column \"${colName}\" not found in scope for distinctOn`,\n { meta: { column: colName } },\n );\n return IdentifierRef.of(colName);\n });\n}\n","import type {\n AnnotationValue,\n OperationKind,\n ValidAnnotations,\n} from '@prisma-next/framework-components/runtime';\nimport { assertAnnotationsApplicable } from '@prisma-next/framework-components/runtime';\nimport { DerivedTableSource, type SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport { toExpr } from '@prisma-next/sql-relational-core/expression';\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 type { PaginationValue } from '../types/shared';\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: PaginationValue<QC>): this {\n const limit = typeof count === 'number' ? count : toExpr(count);\n return this.clone(cloneState(this.state, { limit }));\n }\n\n offset(count: PaginationValue<QC>): this {\n const offset = typeof count === 'number' ? count : toExpr(count);\n return this.clone(cloneState(this.state, { offset }));\n }\n\n distinct(): this {\n return this.clone(cloneState(this.state, { distinct: true }));\n }\n\n /**\n * Attach one or more annotations to this query plan.\n *\n * Read builders (`SelectQueryImpl`, `GroupedQueryImpl`) accept\n * annotations whose declared `applicableTo` includes `'read'`.\n * The type-level `As & ValidAnnotations<'read', As>` gate rejects\n * write-only annotations at the call site; the runtime check below\n * fails closed for callers that bypass the type gate (cast / `any`).\n *\n * Multiple `.annotate(...)` calls compose; duplicate namespaces use\n * last-write-wins. The accumulated annotations are merged into\n * `plan.meta.annotations` at `.build()` time, alongside any framework-\n * internal metadata under reserved namespaces (e.g. `codecs`).\n *\n * Chainable in any position (before / after `.where`, `.select`,\n * `.limit`, etc.); the returned builder has the same row type.\n */\n annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(\n ...annotations: As & ValidAnnotations<'read', As>\n ): this {\n assertAnnotationsApplicable(\n annotations as readonly AnnotationValue<unknown, OperationKind>[],\n 'read',\n 'sql-dsl.annotate',\n );\n const next = new Map(this.state.annotations);\n for (const annotation of annotations as readonly AnnotationValue<unknown, OperationKind>[]) {\n next.set(annotation.namespace, annotation);\n }\n return this.clone(cloneState(this.state, { annotations: next }));\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, this.ctx.rawCodecInferer);\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<QC>(\n this.ctx.queryOperationTypes,\n this.ctx.rawCodecInferer,\n );\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, this.ctx.rawCodecInferer);\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 {\n AnnotationValue,\n OperationKind,\n ValidAnnotations,\n} from '@prisma-next/framework-components/runtime';\nimport { assertAnnotationsApplicable } from '@prisma-next/framework-components/runtime';\nimport 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 type 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 { ifDefined } from '@prisma-next/utils/defined';\nimport { structuredError } from '@prisma-next/utils/structured-error';\nimport type { Expression, 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\n/**\n * Validates and merges a variadic annotations call into a builder's\n * accumulated user-annotations map. Used by `.annotate(...)` on each of\n * the three mutation builders (`InsertQueryImpl`, `UpdateQueryImpl`,\n * `DeleteQueryImpl`); the read builders share the same logic via\n * `QueryBase.annotate()` in `./query-impl.ts`.\n *\n * Runs `assertAnnotationsApplicable` at call time (not at `.build()`) so\n * inapplicable annotations forced through casts surface immediately\n * rather than at plan-construction time.\n */\nfunction mergeWriteAnnotations(\n current: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>,\n annotations: readonly AnnotationValue<unknown, OperationKind>[],\n): ReadonlyMap<string, AnnotationValue<unknown, OperationKind>> {\n assertAnnotationsApplicable(annotations, 'write', 'sql-dsl.annotate');\n const next = new Map(current);\n for (const annotation of annotations) {\n next.set(annotation.namespace, annotation);\n }\n return next;\n}\n\ntype WhereCallback = ExpressionBuilder<Scope, QueryContext>;\nexport type UpdateSetCallback = (\n fields: ReturnType<typeof createFieldProxy>,\n fns: ReturnType<typeof createFunctions>,\n) => Record<string, Expression<ScopeField> | undefined>;\n\nexport function buildParamValues(\n values: Record<string, unknown>,\n namespaceId: string,\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, namespaceId, tableName, col) : undefined;\n params[col] = ParamRef.of(value, codec ? { codec } : undefined);\n }\n for (const def of ctx.applyMutationDefaults({\n op,\n namespace: namespaceId,\n table: tableName,\n values,\n })) {\n const column = table.columns[def.column];\n const codec = column ? codecRefFor(ctx, namespaceId, 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 rawCodecInferer: BuilderContext['rawCodecInferer'],\n): AstExpression {\n const fieldProxy = createFieldProxy(scope);\n const fns = createFunctions(queryOperationTypes, rawCodecInferer);\n const result = whereCallback(fieldProxy, fns as never);\n return result.buildAst();\n}\n\nexport function evaluateUpdateCallback(\n callback: UpdateSetCallback,\n scope: Scope,\n queryOperationTypes: BuilderContext['queryOperationTypes'],\n rawCodecInferer: BuilderContext['rawCodecInferer'],\n): Record<string, AstExpression> {\n const fieldProxy = createFieldProxy(scope);\n const fns = createFunctions(queryOperationTypes, rawCodecInferer);\n const result = callback(fieldProxy, fns as never);\n const set: Record<string, AstExpression> = {};\n for (const [col, expr] of Object.entries(result)) {\n if (expr !== undefined) {\n set[col] = expr.buildAst();\n }\n }\n return set;\n}\n\nexport function buildSetExpressions(\n exprs: Record<string, AstExpression>,\n namespaceId: string,\n table: StorageTable,\n tableName: string,\n op: MutationDefaultsOp,\n ctx: BuilderContext,\n): Record<string, AstExpression> {\n const set: Record<string, AstExpression> = { ...exprs };\n for (const def of ctx.applyMutationDefaults({\n op,\n namespace: namespaceId,\n table: tableName,\n values: exprs,\n })) {\n if (!(def.column in set)) {\n const column = table.columns[def.column];\n const codec = column ? codecRefFor(ctx, namespaceId, tableName, def.column) : undefined;\n set[def.column] = ParamRef.of(def.value, ifDefined('codec', codec));\n }\n }\n return set;\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 #tableSource: TableSource;\n readonly #tableName: string;\n readonly #namespaceId: string;\n readonly #table: StorageTable;\n readonly #scope: Scope;\n readonly #rows: ReadonlyArray<Record<string, unknown>>;\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n readonly #annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>;\n\n constructor(\n tableSource: TableSource,\n namespaceId: string,\n table: StorageTable,\n scope: Scope,\n rows: ReadonlyArray<Record<string, unknown>>,\n ctx: BuilderContext,\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>> = new Map(),\n ) {\n super(ctx);\n this.#tableSource = tableSource;\n this.#tableName = tableSource.name;\n this.#namespaceId = namespaceId;\n this.#table = table;\n this.#scope = scope;\n this.#rows = rows;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n this.#annotations = annotations;\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)\n throw structuredError('ORM.COLUMN_UNKNOWN', `Column \"${col}\" not found in scope`, {\n meta: { column: col },\n });\n newRowFields[col] = field;\n }\n return new InsertQueryImpl(\n this.#tableSource,\n this.#namespaceId,\n this.#table,\n this.#scope,\n this.#rows,\n this.ctx,\n columns,\n newRowFields,\n this.#annotations,\n ) as unknown as InsertQuery<QC, AvailableScope, never>;\n },\n );\n\n /**\n * Attach one or more write-typed annotations to this query plan.\n * The type-level `As & ValidAnnotations<'write', As>` gate rejects\n * read-only annotations at the call site; the runtime check fails\n * closed for callers that bypass the type gate. See `QueryBase.annotate`\n * in `./query-impl.ts` for the read-builder counterpart.\n */\n annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(\n ...annotations: As & ValidAnnotations<'write', As>\n ): InsertQuery<QC, AvailableScope, RowType> {\n return new InsertQueryImpl(\n this.#tableSource,\n this.#namespaceId,\n this.#table,\n this.#scope,\n this.#rows,\n this.ctx,\n this.#returningColumns,\n this.#rowFields,\n mergeWriteAnnotations(\n this.#annotations,\n annotations as readonly AnnotationValue<unknown, OperationKind>[],\n ),\n );\n }\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n if (this.#rows.length === 0) {\n throw structuredError(\n 'ORM.MUTATION_DATA_MISSING',\n 'insert() called with an empty row array — at least one row is required',\n );\n }\n\n const paramRows = this.#rows.map((rowValues) =>\n buildParamValues(\n rowValues,\n this.#namespaceId,\n this.#table,\n this.#tableName,\n 'create',\n this.ctx,\n ),\n );\n\n let ast = InsertAst.into(this.#tableSource).withRows(paramRows);\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 this.#annotations,\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 #tableSource: TableSource;\n readonly #tableName: string;\n readonly #scope: Scope;\n readonly #setExpressions: Record<string, AstExpression>;\n readonly #whereExprs: readonly AstExpression[];\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n readonly #annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>;\n\n constructor(\n tableSource: TableSource,\n scope: Scope,\n setExpressions: Record<string, AstExpression>,\n ctx: BuilderContext,\n whereExprs: readonly AstExpression[] = [],\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>> = new Map(),\n ) {\n super(ctx);\n this.#tableSource = tableSource;\n this.#tableName = tableSource.name;\n this.#scope = scope;\n this.#setExpressions = setExpressions;\n this.#whereExprs = whereExprs;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n this.#annotations = annotations;\n }\n\n where(expr: ExpressionBuilder<AvailableScope, QC>): UpdateQuery<QC, AvailableScope, RowType> {\n const fieldProxy = createFieldProxy(this.#scope);\n const fns = createFunctions(this.ctx.queryOperationTypes, this.ctx.rawCodecInferer);\n const result = (expr as ExpressionBuilder<Scope, QueryContext>)(fieldProxy, fns as never);\n return new UpdateQueryImpl(\n this.#tableSource,\n this.#scope,\n this.#setExpressions,\n this.ctx,\n [...this.#whereExprs, result.buildAst()],\n this.#returningColumns,\n this.#rowFields,\n this.#annotations,\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)\n throw structuredError('ORM.COLUMN_UNKNOWN', `Column \"${col}\" not found in scope`, {\n meta: { column: col },\n });\n newRowFields[col] = field;\n }\n return new UpdateQueryImpl(\n this.#tableSource,\n this.#scope,\n this.#setExpressions,\n this.ctx,\n this.#whereExprs,\n columns,\n newRowFields,\n this.#annotations,\n ) as unknown as UpdateQuery<QC, AvailableScope, never>;\n },\n );\n\n /**\n * Attach one or more write-typed annotations to this query plan.\n * See `InsertQueryImpl.annotate` for semantics; the runtime check\n * fails closed for callers that bypass the type-level gate.\n */\n annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(\n ...annotations: As & ValidAnnotations<'write', As>\n ): UpdateQuery<QC, AvailableScope, RowType> {\n return new UpdateQueryImpl(\n this.#tableSource,\n this.#scope,\n this.#setExpressions,\n this.ctx,\n this.#whereExprs,\n this.#returningColumns,\n this.#rowFields,\n mergeWriteAnnotations(\n this.#annotations,\n annotations as readonly AnnotationValue<unknown, OperationKind>[],\n ),\n );\n }\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n let ast = UpdateAst.table(this.#tableSource)\n .withSet(this.#setExpressions)\n .withWhere(combineWhereExprs(this.#whereExprs));\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 this.#annotations,\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 #tableSource: TableSource;\n readonly #tableName: string;\n readonly #scope: Scope;\n readonly #whereCallbacks: readonly WhereCallback[];\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n readonly #annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>>;\n\n constructor(\n tableSource: TableSource,\n scope: Scope,\n ctx: BuilderContext,\n whereCallbacks: readonly WhereCallback[] = [],\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n annotations: ReadonlyMap<string, AnnotationValue<unknown, OperationKind>> = new Map(),\n ) {\n super(ctx);\n this.#tableSource = tableSource;\n this.#tableName = tableSource.name;\n this.#scope = scope;\n this.#whereCallbacks = whereCallbacks;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n this.#annotations = annotations;\n }\n\n where(expr: ExpressionBuilder<AvailableScope, QC>): DeleteQuery<QC, AvailableScope, RowType> {\n return new DeleteQueryImpl(\n this.#tableSource,\n this.#scope,\n this.ctx,\n [...this.#whereCallbacks, expr as unknown as WhereCallback],\n this.#returningColumns,\n this.#rowFields,\n this.#annotations,\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)\n throw structuredError('ORM.COLUMN_UNKNOWN', `Column \"${col}\" not found in scope`, {\n meta: { column: col },\n });\n newRowFields[col] = field;\n }\n return new DeleteQueryImpl(\n this.#tableSource,\n this.#scope,\n this.ctx,\n this.#whereCallbacks,\n columns,\n newRowFields,\n this.#annotations,\n ) as unknown as DeleteQuery<QC, AvailableScope, never>;\n },\n );\n\n /**\n * Attach one or more write-typed annotations to this query plan.\n * See `InsertQueryImpl.annotate` for semantics.\n */\n annotate<As extends readonly AnnotationValue<unknown, OperationKind>[]>(\n ...annotations: As & ValidAnnotations<'write', As>\n ): DeleteQuery<QC, AvailableScope, RowType> {\n return new DeleteQueryImpl(\n this.#tableSource,\n this.#scope,\n this.ctx,\n this.#whereCallbacks,\n this.#returningColumns,\n this.#rowFields,\n mergeWriteAnnotations(\n this.#annotations,\n annotations as readonly AnnotationValue<unknown, OperationKind>[],\n ),\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, this.ctx.rawCodecInferer),\n ),\n );\n\n let ast = DeleteAst.from(this.#tableSource).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 this.#annotations,\n );\n }\n}\n","import { TableSource } from '@prisma-next/sql-relational-core/ast';\n\nexport function tableSourceForProxy(\n tableName: string,\n alias: string,\n namespaceId: string,\n): TableSource {\n return TableSource.named(tableName, alias !== tableName ? alias : undefined, namespaceId);\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 Functions,\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 { NamespaceTable, 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 {\n buildParamValues,\n buildSetExpressions,\n DeleteQueryImpl,\n evaluateUpdateCallback,\n InsertQueryImpl,\n UpdateQueryImpl,\n type UpdateSetCallback,\n} from './mutation-impl';\nimport { SelectQueryImpl } from './query-impl';\nimport { tableSourceForProxy } from './table-source-for-proxy';\n\nexport class TableProxyImpl<\n C extends TableProxyContract,\n Name extends string,\n Alias extends string,\n AvailableScope extends Scope,\n QC extends QueryContext,\n NsId extends string = string,\n >\n extends BuilderBase<C['capabilities']>\n implements TableProxy<C, NsId, Name, Alias, AvailableScope, QC>\n{\n declare readonly [JoinOuterScope]: JoinSource<\n StorageTableToScopeTable<NamespaceTable<C, NsId, Name>>,\n Alias\n >[typeof JoinOuterScope];\n\n readonly #tableName: string;\n readonly #table: StorageTable;\n readonly #namespaceId: string;\n readonly #fromSource: TableSource;\n readonly #scope: Scope;\n\n constructor(\n tableName: string,\n table: StorageTable,\n alias: string,\n ctx: BuilderContext,\n namespaceId: string,\n ) {\n super(ctx);\n this.#tableName = tableName;\n this.#table = table;\n this.#namespaceId = namespaceId;\n this.#scope = tableToScope(alias, table, {\n storage: ctx.storage,\n tableName,\n namespaceId,\n });\n this.#fromSource = tableSourceForProxy(tableName, alias, namespaceId);\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, NsId, 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, NsId, 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, NsId, Name, NewAlias, RebindScope<AvailableScope, Alias, NewAlias>, QC> {\n return new TableProxyImpl<\n C,\n Name,\n NewAlias,\n RebindScope<AvailableScope, Alias, NewAlias>,\n QC,\n NsId\n >(this.#tableName, this.#table, newAlias, this.ctx, this.#namespaceId);\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(rows: ReadonlyArray<Record<string, unknown>>): InsertQuery<QC, AvailableScope, EmptyRow> {\n return new InsertQueryImpl(\n this.#fromSource,\n this.#namespaceId,\n this.#table,\n this.#scope,\n rows,\n this.ctx,\n );\n }\n\n update(\n setOrCallback:\n | Record<string, unknown>\n | ((\n fields: FieldProxy<AvailableScope>,\n fns: Functions<QC>,\n ) => Record<string, Expression<ScopeField> | undefined>),\n ): UpdateQuery<QC, AvailableScope, EmptyRow> {\n if (typeof setOrCallback === 'function') {\n const callbackExprs = evaluateUpdateCallback(\n setOrCallback as UpdateSetCallback,\n this.#scope,\n this.ctx.queryOperationTypes,\n this.ctx.rawCodecInferer,\n );\n const setExpressions = buildSetExpressions(\n callbackExprs,\n this.#namespaceId,\n this.#table,\n this.#tableName,\n 'update',\n this.ctx,\n );\n return new UpdateQueryImpl(this.#fromSource, this.#scope, setExpressions, this.ctx);\n }\n const setExpressions = buildParamValues(\n setOrCallback,\n this.#namespaceId,\n this.#table,\n this.#tableName,\n 'update',\n this.ctx,\n );\n return new UpdateQueryImpl(this.#fromSource, this.#scope, setExpressions, this.ctx);\n }\n\n delete(): DeleteQuery<QC, AvailableScope, EmptyRow> {\n return new DeleteQueryImpl(this.#fromSource, 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 { RawCodecInferer } from '@prisma-next/sql-relational-core/expression';\nimport type { ExecutionContext } from '@prisma-next/sql-relational-core/query-lane-context';\nimport type { Db, TableProxyContract } from '../types/db';\nimport type { BuilderContext } from './builder-base';\nimport { resolveTableInNamespace } from './resolve-table';\nimport { TableProxyImpl } from './table-proxy-impl';\n\nexport interface SqlOptions<C extends Contract<SqlStorage> & TableProxyContract> {\n readonly context: ExecutionContext<C>;\n readonly rawCodecInferer: RawCodecInferer;\n}\n\nexport function sql<C extends Contract<SqlStorage> & TableProxyContract>(\n options: SqlOptions<C>,\n): Db<C> {\n const { context, rawCodecInferer } = 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 rawCodecInferer,\n };\n\n const { storage } = context.contract;\n\n return new Proxy({} as Db<C>, {\n get(_target, prop: string | symbol) {\n if (typeof prop !== 'string') {\n return undefined;\n }\n if (!Object.hasOwn(storage.namespaces, prop)) {\n return undefined;\n }\n const namespaceId = prop;\n return new Proxy(\n {},\n {\n get(_facetTarget, tableName: string | symbol) {\n if (typeof tableName !== 'string') {\n return undefined;\n }\n const table = resolveTableInNamespace(storage, namespaceId, tableName);\n if (table) {\n // `namespaceId` is a dynamic Proxy key with no static literal here, so the\n // proxy's `NsId` type param lands on its `string` default at this boundary.\n // `TableProxyImpl` still forwards `NsId` through its `as()`/join chain.\n return new TableProxyImpl(tableName, table, tableName, ctx, namespaceId);\n }\n return undefined;\n },\n },\n );\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;CACf;CAEA,WAA0B;EACxB,OAAO,KAAK;CACd;AACF;;;ACnBA,SAAgB,iBAAkC,OAAyB;CACzE,OAAO,IAAI,MAAM,CAAC,GAAoB,EACpC,IAAI,SAAS,MAAc;EACzB,IAAI,OAAO,OAAO,MAAM,UAAU,IAAI,GAAG;GACvC,MAAM,WAAW,MAAM,SAAS;GAChC,IAAI,UACF,OAAO,IAAI,eAAe,cAAc,GAAG,IAAI,GAAG,UAAU,SAAS,KAAK;EAE9E;EAEA,IAAI,OAAO,OAAO,MAAM,YAAY,IAAI,GAAG;GACzC,MAAM,WAAW,MAAM,WAAW;GAClC,IAAI,UAAU,OAAO,qBAAqB,MAAM,QAAQ;EAC1D;CAGF,EACF,CAAC;AACH;AAEA,SAAS,qBACP,eACA,QACgC;CAChC,OAAO,IAAI,MAAM,CAAC,GAAqC,EACrD,IAAI,SAAS,MAAc;EACzB,IAAI,OAAO,OAAO,QAAQ,IAAI,GAAG;GAC/B,MAAM,QAAQ,OAAO;GACrB,IAAI,OAAO,OAAO,IAAI,eAAe,UAAU,GAAG,eAAe,IAAI,GAAG,OAAO,MAAM,KAAK;EAC5F;CAEF,EACF,CAAC;AACH;;;ACDA,MAAM,aAA+B;CAAE,SAAS;CAAa,UAAU;AAAM;AAE7E,MAAM,UAAU;;;;;;AAOhB,SAAS,eAAe,SAAoB,YAAsC;CAChF,IAAI,iBAAiB,OAAO,GAAG,OAAO,QAAQ,SAAS;CACvD,OAAO,OAAO,SAAS,UAAU;AACnC;AAEA,SAAS,iBACP,OAC8E;CAC9E,OACE,OAAO,UAAU,YACjB,UAAU,QACV,cAAc,SACd,OA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KAAK,WAAW;EAG3E,EACF,CACF;CACF,EACF,CAAC;AACH"}
package/package.json CHANGED
@@ -1,26 +1,26 @@
1
1
  {
2
2
  "name": "@prisma-next/sql-builder",
3
- "version": "0.16.0-dev.30",
3
+ "version": "0.16.0-dev.31",
4
4
  "license": "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.16.0-dev.30",
10
- "@prisma-next/framework-components": "0.16.0-dev.30",
11
- "@prisma-next/sql-contract": "0.16.0-dev.30",
12
- "@prisma-next/sql-operations": "0.16.0-dev.30",
13
- "@prisma-next/sql-relational-core": "0.16.0-dev.30"
9
+ "@prisma-next/contract": "0.16.0-dev.31",
10
+ "@prisma-next/framework-components": "0.16.0-dev.31",
11
+ "@prisma-next/sql-contract": "0.16.0-dev.31",
12
+ "@prisma-next/sql-operations": "0.16.0-dev.31",
13
+ "@prisma-next/sql-relational-core": "0.16.0-dev.31"
14
14
  },
15
15
  "devDependencies": {
16
- "@prisma-next/adapter-postgres": "0.16.0-dev.30",
17
- "@prisma-next/ids": "0.16.0-dev.30",
18
- "@prisma-next/sql-contract-ts": "0.16.0-dev.30",
19
- "@prisma-next/target-postgres": "0.16.0-dev.30",
20
- "@prisma-next/test-utils": "0.16.0-dev.30",
21
- "@prisma-next/utils": "0.16.0-dev.30",
22
- "@prisma-next/tsconfig": "0.16.0-dev.30",
23
- "@prisma-next/tsdown": "0.16.0-dev.30",
16
+ "@prisma-next/adapter-postgres": "0.16.0-dev.31",
17
+ "@prisma-next/ids": "0.16.0-dev.31",
18
+ "@prisma-next/sql-contract-ts": "0.16.0-dev.31",
19
+ "@prisma-next/target-postgres": "0.16.0-dev.31",
20
+ "@prisma-next/test-utils": "0.16.0-dev.31",
21
+ "@prisma-next/utils": "0.16.0-dev.31",
22
+ "@prisma-next/tsconfig": "0.16.0-dev.31",
23
+ "@prisma-next/tsdown": "0.16.0-dev.31",
24
24
  "tsdown": "0.22.8",
25
25
  "typescript": "5.9.3",
26
26
  "vitest": "4.1.10"
@@ -22,6 +22,7 @@ import type {
22
22
  MutationDefaultsOptions,
23
23
  } from '@prisma-next/sql-relational-core/query-lane-context';
24
24
  import { ifDefined } from '@prisma-next/utils/defined';
25
+ import { structuredError } from '@prisma-next/utils/structured-error';
25
26
  import type {
26
27
  AggregateFunctions,
27
28
  Expression,
@@ -276,7 +277,11 @@ export function assertCapability(
276
277
  for (const [ns, keys] of Object.entries(required)) {
277
278
  for (const key of Object.keys(keys)) {
278
279
  if (!ctx.capabilities[ns]?.[key]) {
279
- throw new Error(`${methodName}() requires capability ${ns}.${key}`);
280
+ throw structuredError(
281
+ 'ORM.CAPABILITY_MISSING',
282
+ `${methodName}() requires capability ${ns}.${key}`,
283
+ { meta: { method: methodName, capability: `${ns}.${key}` } },
284
+ );
280
285
  }
281
286
  }
282
287
  }
@@ -295,7 +300,10 @@ export function resolveSelectArgs(
295
300
  if (typeof args[0] === 'string' && (args.length === 1 || typeof args[1] !== 'function')) {
296
301
  for (const colName of args as string[]) {
297
302
  const field = scope.topLevel[colName];
298
- if (!field) throw new Error(`Column "${colName}" not found in scope`);
303
+ if (!field)
304
+ throw structuredError('ORM.COLUMN_UNKNOWN', `Column "${colName}" not found in scope`, {
305
+ meta: { column: colName },
306
+ });
299
307
  projections.push(ProjectionItem.of(colName, IdentifierRef.of(colName), field.codec));
300
308
  newRowFields[colName] = field;
301
309
  }
@@ -331,7 +339,7 @@ export function resolveSelectArgs(
331
339
  return { projections, newRowFields };
332
340
  }
333
341
 
334
- throw new Error('Invalid .select() arguments');
342
+ throw structuredError('ORM.ARGUMENT_INVALID', 'Invalid .select() arguments');
335
343
  }
336
344
 
337
345
  export function resolveOrderBy(
@@ -347,7 +355,13 @@ export function resolveOrderBy(
347
355
  if (typeof arg === 'string') {
348
356
  const combined = orderByScopeOf(scope, rowFields);
349
357
  if (!(arg in combined.topLevel))
350
- throw new Error(`Column "${arg}" not found in scope for orderBy`);
358
+ throw structuredError(
359
+ 'ORM.COLUMN_UNKNOWN',
360
+ `Column "${arg}" not found in scope for orderBy`,
361
+ {
362
+ meta: { column: arg },
363
+ },
364
+ );
351
365
  const expr = IdentifierRef.of(arg);
352
366
  return dir === 'asc' ? OrderByItem.asc(expr) : OrderByItem.desc(expr);
353
367
  }
@@ -361,7 +375,7 @@ export function resolveOrderBy(
361
375
  return dir === 'asc' ? OrderByItem.asc(result.buildAst()) : OrderByItem.desc(result.buildAst());
362
376
  }
363
377
 
364
- throw new Error('Invalid orderBy argument');
378
+ throw structuredError('ORM.ARGUMENT_INVALID', 'Invalid orderBy argument');
365
379
  }
366
380
 
367
381
  export function resolveGroupBy(
@@ -374,7 +388,11 @@ export function resolveGroupBy(
374
388
  const combined = orderByScopeOf(scope, rowFields);
375
389
  return (args as string[]).map((colName) => {
376
390
  if (!(colName in combined.topLevel))
377
- throw new Error(`Column "${colName}" not found in scope for groupBy`);
391
+ throw structuredError(
392
+ 'ORM.COLUMN_UNKNOWN',
393
+ `Column "${colName}" not found in scope for groupBy`,
394
+ { meta: { column: colName } },
395
+ );
378
396
  return IdentifierRef.of(colName);
379
397
  });
380
398
  }
@@ -386,7 +404,7 @@ export function resolveGroupBy(
386
404
  return [result.buildAst()];
387
405
  }
388
406
 
389
- throw new Error('Invalid groupBy arguments');
407
+ throw structuredError('ORM.ARGUMENT_INVALID', 'Invalid groupBy arguments');
390
408
  }
391
409
 
392
410
  export function resolveDistinctOn(
@@ -404,7 +422,11 @@ export function resolveDistinctOn(
404
422
  const combined = orderByScopeOf(scope, rowFields);
405
423
  return (args as string[]).map((colName) => {
406
424
  if (!(colName in combined.topLevel))
407
- throw new Error(`Column "${colName}" not found in scope for distinctOn`);
425
+ throw structuredError(
426
+ 'ORM.COLUMN_UNKNOWN',
427
+ `Column "${colName}" not found in scope for distinctOn`,
428
+ { meta: { column: colName } },
429
+ );
408
430
  return IdentifierRef.of(colName);
409
431
  });
410
432
  }
@@ -18,6 +18,7 @@ import {
18
18
  import type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';
19
19
  import type { MutationDefaultsOp } from '@prisma-next/sql-relational-core/query-lane-context';
20
20
  import { ifDefined } from '@prisma-next/utils/defined';
21
+ import { structuredError } from '@prisma-next/utils/structured-error';
21
22
  import type { Expression, ExpressionBuilder } from '../expression';
22
23
  import type { ResolveRow } from '../resolve';
23
24
  import type { QueryContext, Scope, ScopeField } from '../scope';
@@ -205,7 +206,10 @@ export class InsertQueryImpl<
205
206
  const newRowFields: Record<string, ScopeField> = {};
206
207
  for (const col of columns) {
207
208
  const field = this.#scope.topLevel[col];
208
- if (!field) throw new Error(`Column "${col}" not found in scope`);
209
+ if (!field)
210
+ throw structuredError('ORM.COLUMN_UNKNOWN', `Column "${col}" not found in scope`, {
211
+ meta: { column: col },
212
+ });
209
213
  newRowFields[col] = field;
210
214
  }
211
215
  return new InsertQueryImpl(
@@ -250,7 +254,10 @@ export class InsertQueryImpl<
250
254
 
251
255
  build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {
252
256
  if (this.#rows.length === 0) {
253
- throw new Error('insert() called with an empty row array — at least one row is required');
257
+ throw structuredError(
258
+ 'ORM.MUTATION_DATA_MISSING',
259
+ 'insert() called with an empty row array — at least one row is required',
260
+ );
254
261
  }
255
262
 
256
263
  const paramRows = this.#rows.map((rowValues) =>
@@ -341,7 +348,10 @@ export class UpdateQueryImpl<
341
348
  const newRowFields: Record<string, ScopeField> = {};
342
349
  for (const col of columns) {
343
350
  const field = this.#scope.topLevel[col];
344
- if (!field) throw new Error(`Column "${col}" not found in scope`);
351
+ if (!field)
352
+ throw structuredError('ORM.COLUMN_UNKNOWN', `Column "${col}" not found in scope`, {
353
+ meta: { column: col },
354
+ });
345
355
  newRowFields[col] = field;
346
356
  }
347
357
  return new UpdateQueryImpl(
@@ -453,7 +463,10 @@ export class DeleteQueryImpl<
453
463
  const newRowFields: Record<string, ScopeField> = {};
454
464
  for (const col of columns) {
455
465
  const field = this.#scope.topLevel[col];
456
- if (!field) throw new Error(`Column "${col}" not found in scope`);
466
+ if (!field)
467
+ throw structuredError('ORM.COLUMN_UNKNOWN', `Column "${col}" not found in scope`, {
468
+ meta: { column: col },
469
+ });
457
470
  newRowFields[col] = field;
458
471
  }
459
472
  return new DeleteQueryImpl(