@prisma-next/sql-builder 0.13.0-dev.31 → 0.13.0-dev.33

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.
@@ -1,8 +1,8 @@
1
1
  import { AnyFromSource, SelectAst } from "@prisma-next/sql-relational-core/ast";
2
2
  import { CodecExpression, CodecTypesBase, Expression as Expression$1, RawSqlTag, ScopeField, TraitExpression } from "@prisma-next/sql-relational-core/expression";
3
3
  import { AnnotationValue, OperationKind, ValidAnnotations } from "@prisma-next/framework-components/runtime";
4
- import { ExtractCodecTypes, ExtractFieldInputTypes, ExtractFieldOutputTypes, ExtractQueryOperationTypes, QueryOperationTypesBase, StorageTable, StorageTable as StorageTable$1 } from "@prisma-next/sql-contract/types";
5
- import { Contract, ContractModelDefinitions } from "@prisma-next/contract/types";
4
+ import { ExtractCodecTypes, ExtractFieldInputTypes, ExtractQueryOperationTypes, QueryOperationTypesBase, StorageTable, StorageTable as StorageTable$1 } from "@prisma-next/sql-contract/types";
5
+ import { ComputeColumnJsType } from "@prisma-next/sql-relational-core/types";
6
6
  import { SqlQueryPlan } from "@prisma-next/sql-relational-core/plan";
7
7
 
8
8
  //#region src/scope.d.ts
@@ -302,43 +302,53 @@ interface WithBuild<QC extends QueryContext, RowType extends Record<string, Scop
302
302
  }
303
303
  //#endregion
304
304
  //#region src/types/table-proxy.d.ts
305
- type FindModelForTable<C, TableName extends string> = C extends Contract ? { [M in keyof ContractModelDefinitions<C> & string]: ContractModelDefinitions<C>[M] extends {
305
+ type FindModelForTable<C extends TableProxyContract, NsId extends string, TableName extends string> = C['domain']['namespaces'][NsId]['models'] extends infer Models extends Record<string, unknown> ? { [M in keyof Models & string]: Models[M] extends {
306
306
  readonly storage: {
307
307
  readonly table: TableName;
308
308
  };
309
- } ? M : never }[keyof ContractModelDefinitions<C> & string] : never;
310
- type FindFieldForColumn<C, ModelName extends string, ColumnName extends string> = C extends Contract ? ModelName extends keyof ContractModelDefinitions<C> ? { [F in keyof ContractModelDefinitions<C>[ModelName]['storage']['fields'] & string]: ContractModelDefinitions<C>[ModelName]['storage']['fields'][F] extends {
309
+ } ? M : never }[keyof Models & string] : never;
310
+ type FindFieldForColumn<C extends TableProxyContract, NsId extends string, ModelName extends string, ColumnName extends string> = C['domain']['namespaces'][NsId]['models'] extends infer Models extends Record<string, unknown> ? ModelName extends keyof Models ? Models[ModelName] extends {
311
+ readonly storage: {
312
+ readonly fields: infer Fields extends Record<string, unknown>;
313
+ };
314
+ } ? { [F in keyof Fields & string]: Fields[F] extends {
311
315
  readonly column: ColumnName;
312
- } ? F : never }[keyof ContractModelDefinitions<C>[ModelName]['storage']['fields'] & string] : never : never;
313
- type ResolvedColumnTypes<C, TableName extends string, FieldTypes extends Record<string, Record<string, unknown>>> = string extends keyof FieldTypes ? Record<string, never> : FindModelForTable<C, TableName> extends infer ModelName extends string ? ModelName extends keyof FieldTypes ? C extends TableProxyContract ? UnboundTables<C> extends infer Tables extends Record<string, StorageTable> ? TableName extends keyof Tables ? { [ColName in keyof Tables[TableName]['columns'] & string]: FindFieldForColumn<C, ModelName, ColName> extends infer FieldName extends string ? FieldName extends keyof FieldTypes[ModelName] ? FieldTypes[ModelName][FieldName] : unknown : unknown } : Record<string, never> : Record<string, never> : Record<string, never> : Record<string, never> : Record<string, never>;
314
- type ResolvedInsertValues<C, Table extends StorageTable, TableName extends string, CT extends Record<string, {
316
+ } ? F : never }[keyof Fields & string] : never : never : never;
317
+ type ResolvedColumnTypes<C extends TableProxyContract, NsId extends string, TableName extends string> = NamespaceTable<C, NsId, TableName> extends infer Table extends StorageTable ? { [ColName in keyof Table['columns'] & string]: ComputeColumnJsType<C, NsId, TableName, ColName, ExtractCodecTypes<C>> } : Record<string, never>;
318
+ type ResolvedInsertValues<C extends TableProxyContract, NsId extends string, Table extends StorageTable, TableName extends string, CT extends Record<string, {
315
319
  readonly input: unknown;
316
- }>, FieldInputs extends Record<string, Record<string, unknown>>> = string extends keyof FieldInputs ? InsertValues<Table, CT> : FindModelForTable<C, TableName> extends infer ModelName extends string ? ModelName extends keyof FieldInputs ? { [K in keyof Table['columns']]?: FindFieldForColumn<C, ModelName, K & string> extends infer FieldName extends string ? FieldName extends keyof FieldInputs[ModelName] ? Table['columns'][K]['nullable'] extends true ? NonNullable<FieldInputs[ModelName][FieldName]> | null : NonNullable<FieldInputs[ModelName][FieldName]> : Table['columns'][K]['codecId'] extends keyof CT ? CT[Table['columns'][K]['codecId']]['input'] : unknown : Table['columns'][K]['codecId'] extends keyof CT ? CT[Table['columns'][K]['codecId']]['input'] : unknown } : InsertValues<Table, CT> : InsertValues<Table, CT>;
317
- type ResolvedUpdateValues<C, Table extends StorageTable, TableName extends string, CT extends Record<string, {
320
+ }>, FieldInputs extends Record<string, Record<string, Record<string, unknown>>>> = string extends keyof FieldInputs ? InsertValues<Table, CT> : NsId extends keyof FieldInputs ? FieldInputs[NsId] extends infer NsInputs extends Record<string, Record<string, unknown>> ? FindModelForTable<C, NsId, TableName> extends infer ModelName extends string ? ModelName extends keyof NsInputs ? { [K in keyof Table['columns']]?: FindFieldForColumn<C, NsId, ModelName, K & string> extends infer FieldName extends string ? FieldName extends keyof NsInputs[ModelName] ? Table['columns'][K]['nullable'] extends true ? NonNullable<NsInputs[ModelName][FieldName]> | null : NonNullable<NsInputs[ModelName][FieldName]> : Table['columns'][K]['codecId'] extends keyof CT ? CT[Table['columns'][K]['codecId']]['input'] : unknown : Table['columns'][K]['codecId'] extends keyof CT ? CT[Table['columns'][K]['codecId']]['input'] : unknown } : InsertValues<Table, CT> : InsertValues<Table, CT> : InsertValues<Table, CT> : InsertValues<Table, CT>;
321
+ type ResolvedUpdateValues<C extends TableProxyContract, NsId extends string, Table extends StorageTable, TableName extends string, CT extends Record<string, {
318
322
  readonly input: unknown;
319
- }>, FieldInputs extends Record<string, Record<string, unknown>>> = ResolvedInsertValues<C, Table, TableName, CT, FieldInputs>;
323
+ }>, FieldInputs extends Record<string, Record<string, Record<string, unknown>>>> = ResolvedInsertValues<C, NsId, Table, TableName, CT, FieldInputs>;
320
324
  type ResolvedUpdateExpressions<Table extends StorageTable> = { [K in keyof Table['columns']]?: Expression$1<{
321
325
  codecId: Table['columns'][K]['codecId'];
322
326
  nullable: boolean;
323
327
  }> };
324
- type ContractToQC<C extends TableProxyContract, Name extends string = string> = {
328
+ type ContractToQC<C extends TableProxyContract, NsId extends string = string, Name extends string = string> = {
325
329
  readonly codecTypes: ExtractCodecTypes<C>;
326
330
  readonly capabilities: C['capabilities'];
327
331
  readonly queryOperationTypes: ExtractQueryOperationTypes<C>;
328
- readonly resolvedColumnOutputTypes: ResolvedColumnTypes<C, Name, ExtractFieldOutputTypes<C>>;
332
+ readonly resolvedColumnOutputTypes: ResolvedColumnTypes<C, NsId, Name>;
329
333
  };
330
- interface TableProxy<C extends TableProxyContract, Name extends string & keyof UnboundTables<C>, Alias extends string = Name, AvailableScope extends Scope = DefaultScope<Name, UnboundTables<C>[Name]>, QC extends QueryContext = ContractToQC<C, Name>> extends JoinSource<StorageTableToScopeTable<UnboundTables<C>[Name]>, Alias>, WithSelect<QC, AvailableScope, EmptyRow>, WithJoin<QC, AvailableScope, C['capabilities']> {
331
- as<NewAlias extends string>(newAlias: NewAlias): TableProxy<C, Name, NewAlias, RebindScope<AvailableScope, Alias, NewAlias>, QC>;
332
- insert(rows: ReadonlyArray<ResolvedInsertValues<C, UnboundTables<C>[Name], Name, QC['codecTypes'], ExtractFieldInputTypes<C>>>): InsertQuery<QC, AvailableScope, EmptyRow>;
333
- update(set: ResolvedUpdateValues<C, UnboundTables<C>[Name], Name, QC['codecTypes'], ExtractFieldInputTypes<C>>): UpdateQuery<QC, AvailableScope, EmptyRow>;
334
- update(callback: (fields: FieldProxy<AvailableScope>, fns: Functions<QC>) => ResolvedUpdateExpressions<UnboundTables<C>[Name]>): UpdateQuery<QC, AvailableScope, EmptyRow>;
334
+ interface TableProxy<C extends TableProxyContract, NsId extends string, Name extends string, Alias extends string = Name, AvailableScope extends Scope = DefaultScope<Name, NamespaceTable<C, NsId, Name>>, QC extends QueryContext = ContractToQC<C, NsId, Name>> extends JoinSource<StorageTableToScopeTable<NamespaceTable<C, NsId, Name>>, Alias>, WithSelect<QC, AvailableScope, EmptyRow>, WithJoin<QC, AvailableScope, C['capabilities']> {
335
+ as<NewAlias extends string>(newAlias: NewAlias): TableProxy<C, NsId, Name, NewAlias, RebindScope<AvailableScope, Alias, NewAlias>, QC>;
336
+ insert(rows: ReadonlyArray<ResolvedInsertValues<C, NsId, NamespaceTable<C, NsId, Name>, Name, QC['codecTypes'], ExtractFieldInputTypes<C>>>): InsertQuery<QC, AvailableScope, EmptyRow>;
337
+ update(set: ResolvedUpdateValues<C, NsId, NamespaceTable<C, NsId, Name>, Name, QC['codecTypes'], ExtractFieldInputTypes<C>>): UpdateQuery<QC, AvailableScope, EmptyRow>;
338
+ update(callback: (fields: FieldProxy<AvailableScope>, fns: Functions<QC>) => ResolvedUpdateExpressions<NamespaceTable<C, NsId, Name>>): UpdateQuery<QC, AvailableScope, EmptyRow>;
335
339
  delete(): DeleteQuery<QC, AvailableScope, EmptyRow>;
336
340
  }
337
341
  //#endregion
338
342
  //#region src/types/db.d.ts
339
343
  type CapabilitiesBase = Record<string, Record<string, boolean>>;
340
344
  type NamespaceEntries = Readonly<Record<string, Readonly<Record<string, unknown>>>>;
345
+ type NamespaceDomain = Readonly<Record<string, {
346
+ readonly models: Readonly<Record<string, unknown>>;
347
+ }>>;
341
348
  type TableProxyContract = {
349
+ readonly domain: {
350
+ readonly namespaces: NamespaceDomain;
351
+ };
342
352
  readonly storage: {
343
353
  readonly namespaces: Readonly<Record<string, {
344
354
  readonly entries: NamespaceEntries;
@@ -352,8 +362,9 @@ type TablesInNamespace<NS extends {
352
362
  type UnboundTables<C extends TableProxyContract> = { readonly [Name in TableNamesAcrossNamespaces<C>]: TableInAnyNamespace<C, Name> };
353
363
  type TableNamesAcrossNamespaces<C extends TableProxyContract> = { [NSId in keyof C['storage']['namespaces']]: keyof TablesInNamespace<C['storage']['namespaces'][NSId]> & string }[keyof C['storage']['namespaces']];
354
364
  type TableInAnyNamespace<C extends TableProxyContract, Name extends string> = { [NSId in keyof C['storage']['namespaces']]: Name extends keyof TablesInNamespace<C['storage']['namespaces'][NSId]> ? TablesInNamespace<C['storage']['namespaces'][NSId]>[Name] : never }[keyof C['storage']['namespaces']];
355
- type Namespace<C extends TableProxyContract, NsId extends keyof C['storage']['namespaces']> = { readonly [Name in keyof TablesInNamespace<C['storage']['namespaces'][NsId]> & string]: TableProxy<C, Name> };
356
- type Db<C extends TableProxyContract> = { readonly [Ns in keyof C['storage']['namespaces']]: Namespace<C, Ns> };
365
+ type NamespaceTable<C extends TableProxyContract, NsId extends string, Name extends string> = TablesInNamespace<C['storage']['namespaces'][NsId]>[Name];
366
+ type Namespace<C extends TableProxyContract, NsId extends string & keyof C['storage']['namespaces']> = { readonly [Name in keyof TablesInNamespace<C['storage']['namespaces'][NsId]> & string]: TableProxy<C, NsId, Name> };
367
+ type Db<C extends TableProxyContract> = { readonly [Ns in keyof C['storage']['namespaces'] & string]: Namespace<C, Ns> };
357
368
  //#endregion
358
369
  export { Subquery as C, ScopeField as S, FieldProxy as _, TableProxyContract as a, QueryContext as b, SelectQuery as c, InsertQuery as d, UpdateQuery as f, Expression$1 as g, BooleanCodecType as h, TableNamesAcrossNamespaces as i, GroupedQuery as l, AggregateFunctions as m, Namespace as n, UnboundTables as o, ResolveRow as p, TableInAnyNamespace as r, TableProxy as s, Db as t, DeleteQuery as u, Functions as v, Scope as x, GatedMethod as y };
359
- //# sourceMappingURL=db-Ba99KmSZ.d.mts.map
370
+ //# sourceMappingURL=db-BS_UG1Si.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"db-Ba99KmSZ.d.mts","names":[],"sources":["../src/scope.ts","../src/expression.ts","../src/resolve.ts","../src/types/mutation-query.ts","../src/types/joined-tables.ts","../src/types/grouped-query.ts","../src/types/select-query.ts","../src/types/shared.ts","../src/types/table-proxy.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EK,iBAAA,CAAkB,CAAA,0BAA2B,IAAA,cAAkB,UAAA,CACrF,CAAA,EACA,IAAA;AAAA,KAIQ,EAAA,WAAa,kBAAA,4BACD,CAAA,4BAA6B,SAAA,CAAU,CAAA,EAAG,EAAA"}
1
+ {"version":3,"file":"db-BS_UG1Si.d.mts","names":[],"sources":["../src/scope.ts","../src/expression.ts","../src/resolve.ts","../src/types/mutation-query.ts","../src/types/joined-tables.ts","../src/types/grouped-query.ts","../src/types/select-query.ts","../src/types/shared.ts","../src/types/table-proxy.ts","../src/types/db.ts"],"mappings":";;;;;;;;KASY,WAAA,mCAA8C,YAAA,SAAqB,QAAA,GAC3E,MAAA;AAAA,cAGiB,cAAA;AAAA,cACA,cAAA;AAAA,KAET,MAAA,oBAA0B,CAAA,GAAI,CAAA,CAAE,CAAA;AAAA,KAChC,QAAA,GAAW,MAAM,QAAQ,UAAA;AAAA,KAEzB,UAAA,GAAa,MAAM,SAAS,UAAA;AAAA,KAE5B,KAAA;EACV,QAAA,EAAU,UAAA;EACV,UAAA,EAAY,MAAA,SAAe,UAAA;AAAA;AAAA,KAGjB,UAAA,aAAuB,UAAA;EAAA,UACvB,cAAA;IACR,QAAA,EAAU,GAAA;IACV,UAAA,EAAY,MAAA,CAAO,KAAA,EAAO,GAAA;EAAA;EAG5B,iBAAA,IAAqB,KAAA;EACrB,QAAA,IAAY,aAAA;AAAA;AAAA,KAGF,YAAA,oCAAgD,cAAA;EAC1D,QAAA,EAAU,wBAAA,CAAyB,KAAA;EACnC,UAAA,UACQ,IAAA,GAAO,wBAAA,CAAyB,KAAA;AAAA;AAAA,KAI9B,wBAAA,WAAmC,cAAA,kBACjC,CAAA;EACV,OAAA,EAAS,CAAA,YAAa,CAAA;EACtB,QAAA,EAAU,CAAA,YAAa,CAAA;AAAA;AAAA,KAIf,WAAA,WAAsB,KAAA,YAAiB,KAAA;EACjD,QAAA,EAAU,MAAA,CACR,IAAA,CAAK,CAAA,oBAAqB,CAAA,gBAAiB,IAA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AAA,EAAS,gBAAA;AAAA,KACpD,EAAA,6BAA+B,QAAA,CAAS,MAAA,SAAe,YAAA,KACnD,EAAA,uBACA,QAAA,CAAS,MAAA,SAAe,YAAA;AAAA,KAIlB,aAAA,WAAwB,kBAAA,wBAChB,0BAAA,CAA2B,CAAA,IAAK,mBAAA,CAAoB,CAAA,EAAG,IAAA;AAAA,KAG/D,0BAAA,WAAqC,kBAAA,qBAChC,CAAA,kCAAmC,iBAAA,CAChD,CAAA,0BAA2B,IAAA,oBAGvB,CAAA;AAAA,KAEI,mBAAA,WAA8B,kBAAA,0CACzB,CAAA,4BAA6B,IAAA,eAAmB,iBAAA,CAC7D,CAAA,0BAA2B,IAAA,KAEzB,iBAAA,CAAkB,CAAA,0BAA2B,IAAA,GAAO,IAAA,kBAElD,CAAA;AAAA,KAQI,cAAA,WACA,kBAAA,8CAGR,iBAAA,CAAkB,CAAA,0BAA2B,IAAA,GAAO,IAAA;AAAA,KAO5C,SAAA,WACA,kBAAA,8BACkB,CAAA,uDAEJ,iBAAA,CAAkB,CAAA,0BAA2B,IAAA,cAAkB,UAAA,CACrF,CAAA,EACA,IAAA,EACA,IAAA;AAAA,KAIQ,EAAA,WAAa,kBAAA,4BACD,CAAA,qCAAsC,SAAA,CAAU,CAAA,EAAG,EAAA"}
@@ -1,2 +1,2 @@
1
- import { C as Subquery, S as ScopeField, a as TableProxyContract, b as QueryContext, c as SelectQuery, d as InsertQuery, f as UpdateQuery, g as Expression, h as BooleanCodecType, i as TableNamesAcrossNamespaces, l as GroupedQuery, m as AggregateFunctions, n as Namespace, o as UnboundTables, p as ResolveRow, r as TableInAnyNamespace, s as TableProxy, t as Db, u as DeleteQuery, v as Functions, x as Scope, y as GatedMethod } from "../db-Ba99KmSZ.mjs";
1
+ import { C as Subquery, S as ScopeField, a as TableProxyContract, b as QueryContext, c as SelectQuery, d as InsertQuery, f as UpdateQuery, g as Expression, h as BooleanCodecType, i as TableNamesAcrossNamespaces, l as GroupedQuery, m as AggregateFunctions, n as Namespace, o as UnboundTables, p as ResolveRow, r as TableInAnyNamespace, s as TableProxy, t as Db, u as DeleteQuery, v as Functions, x as Scope, y as GatedMethod } from "../db-BS_UG1Si.mjs";
2
2
  export type { AggregateFunctions, BooleanCodecType, Db, DeleteQuery, Expression, Functions, GatedMethod, GroupedQuery, InsertQuery, Namespace, QueryContext, ResolveRow, Scope, ScopeField, SelectQuery, Subquery, TableInAnyNamespace, TableNamesAcrossNamespaces, TableProxy, TableProxyContract, UnboundTables, UpdateQuery };
package/dist/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { C as Subquery, S as ScopeField, b as QueryContext, c as SelectQuery, d as InsertQuery, f as UpdateQuery, g as Expression, l as GroupedQuery, m as AggregateFunctions, p as ResolveRow, s as TableProxy, t as Db, u as DeleteQuery, v as Functions, x as Scope, y as GatedMethod } from "./db-Ba99KmSZ.mjs";
1
+ import { C as Subquery, S as ScopeField, b as QueryContext, c as SelectQuery, d as InsertQuery, f as UpdateQuery, g as Expression, l as GroupedQuery, m as AggregateFunctions, p as ResolveRow, s as TableProxy, t as Db, u as DeleteQuery, v as Functions, x as Scope, y as GatedMethod } from "./db-BS_UG1Si.mjs";
2
2
  export type { AggregateFunctions, Db, DeleteQuery, Expression, Functions, GatedMethod, GroupedQuery, InsertQuery, QueryContext, ResolveRow, Scope, ScopeField, SelectQuery, Subquery, TableProxy, UpdateQuery };
@@ -1,10 +1,10 @@
1
- import { S as ScopeField, _ as FieldProxy, a as TableProxyContract, b as QueryContext, m as AggregateFunctions, t as Db, v as Functions, x as Scope } from "../db-Ba99KmSZ.mjs";
1
+ import { S as ScopeField, _ as FieldProxy, a as TableProxyContract, b as QueryContext, m as AggregateFunctions, t as Db, v as Functions, x as Scope } from "../db-BS_UG1Si.mjs";
2
2
  import { AnyExpression } from "@prisma-next/sql-relational-core/ast";
3
3
  import { Expression, RawCodecInferer } from "@prisma-next/sql-relational-core/expression";
4
4
  import { SqlStorage } from "@prisma-next/sql-contract/types";
5
- import { Contract } from "@prisma-next/contract/types";
6
5
  import { CodecRef } from "@prisma-next/framework-components/codec";
7
6
  import { SqlOperationEntry } from "@prisma-next/sql-operations";
7
+ import { Contract } from "@prisma-next/contract/types";
8
8
  import { ExecutionContext } from "@prisma-next/sql-relational-core/query-lane-context";
9
9
 
10
10
  //#region src/runtime/expression-impl.d.ts
@@ -166,7 +166,47 @@ function resolveTableInNamespace(storage, namespaceId, tableName) {
166
166
  return tables[tableName];
167
167
  }
168
168
  //#endregion
169
- //#region ../../../1-framework/0-foundation/utils/dist/defined-BB-H4E45.mjs
169
+ //#region ../../../1-framework/0-foundation/utils/dist/casts-DpaahrlC.mjs
170
+ /**
171
+ * **Last-resort escape hatch for unsafe type assertions. Not a sanctioned tool to reach for.**
172
+ *
173
+ * Before reaching for `blindCast`, **rewrite the surrounding code so the cast becomes
174
+ * unnecessary**: tighten an input type, add a runtime check that narrows via a type
175
+ * predicate, restructure a generic so the compiler can see the relationship you're
176
+ * asserting, or use {@link castAs} when the value already satisfies the target type.
177
+ * Only when no rewrite is feasible does `blindCast` become the right answer — and at
178
+ * that point, the `Reason` literal you supply must articulate the compromise in
179
+ * language a reviewer can evaluate.
180
+ *
181
+ * The reviewer **will** validate the `Reason`. If it doesn't hold up under scrutiny,
182
+ * that is not a signal to soften the reason; it is a signal to go back and solve the
183
+ * underlying type-system problem properly. An unconvincing justification is rework,
184
+ * not a free pass.
185
+ *
186
+ * `blindCast` is the auditable form of `as Foo` / `as unknown as Foo`: it bypasses
187
+ * the compiler's checks (the input type is `unknown`, the output type is whatever the
188
+ * caller asks for), but it forces the unsafety to be named at the call site instead of
189
+ * smuggled in via a bare `as`. The `Reason` type parameter exists only at compile
190
+ * time — it is not present in the emitted JavaScript — but it is grep-able and
191
+ * visible to future readers.
192
+ *
193
+ * @example
194
+ * ```typescript
195
+ * const stringValue = blindCast<
196
+ * string,
197
+ * "JSON.parse returns `unknown`; this field is documented to be a string in the API contract"
198
+ * >(parsed[key]);
199
+ * ```
200
+ *
201
+ * @typeParam TargetType - The type the caller is asserting the input has.
202
+ * @typeParam _Reason - A string literal describing why bypassing the type system is necessary here.
203
+ * Only meaningful at compile time. The reviewer evaluates whether it justifies the unsafety.
204
+ */
205
+ function blindCast(input) {
206
+ return input;
207
+ }
208
+ //#endregion
209
+ //#region ../../../1-framework/0-foundation/utils/dist/defined-BQWA85QH.mjs
170
210
  /**
171
211
  * Returns an object with the key/value if value is defined, otherwise an empty object.
172
212
  *
@@ -190,7 +230,7 @@ function resolveTableInNamespace(storage, namespaceId, tableName) {
190
230
  * ```
191
231
  */
192
232
  function ifDefined(key, value) {
193
- return value !== void 0 ? { [key]: value } : {};
233
+ return value !== void 0 ? blindCast({ [key]: value }) : {};
194
234
  }
195
235
  //#endregion
196
236
  //#region src/runtime/builder-base.ts
@@ -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/defined-BB-H4E45.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/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 ? { [key]: value } : {};\n}\n//#endregion\nexport { ifDefined as t };\n\n//# sourceMappingURL=defined-BB-H4E45.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 ...(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({ op, table: tableName, values })) {\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({ op, table: tableName, values: exprs })) {\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 { TableProxyContract, UnboundTables } 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 & keyof UnboundTables<C>,\n Alias extends string,\n AvailableScope extends Scope,\n QC extends QueryContext,\n >\n extends BuilderBase<C['capabilities']>\n implements TableProxy<C, Name, Alias, AvailableScope, QC>\n{\n declare readonly [JoinOuterScope]: JoinSource<\n StorageTableToScopeTable<UnboundTables<C>[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, Name, Alias, AvailableScope, QC>['lateralJoin'];\n\n outerLateralJoin = this._gate(\n { sql: { lateral: true } },\n 'outerLateralJoin',\n <LAlias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: LAlias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<\n AvailableScope,\n NullableScope<{ topLevel: LateralRow; namespaces: Record<LAlias, LateralRow> }>\n >\n > => {\n return this.#toJoined().outerLateralJoin(alias, builder);\n },\n ) as TableProxy<C, Name, Alias, AvailableScope, QC>['outerLateralJoin'];\n\n getJoinOuterScope(): Scope {\n return this.#scope;\n }\n\n buildAst(): AnyFromSource {\n return this.#fromSource;\n }\n\n as<NewAlias extends string>(\n newAlias: NewAlias,\n ): TableProxy<C, Name, NewAlias, RebindScope<AvailableScope, Alias, NewAlias>, QC> {\n return new TableProxyImpl(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 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,OAA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AAiB,iBACrB,eACA,KAAKF,cACL,KAAKD,QACL,KAAKD,YACL,UACA,KAAK,GACP;EACA,OAAO,IAAI,gBAAgB,KAAKG,aAAa,KAAKC,QAAQ,gBAAgB,KAAK,GAAG;CACpF;CAEA,SAAoD;EAClD,OAAO,IAAI,gBAAgB,KAAKD,aAAa,KAAKC,QAAQ,KAAK,GAAG;CACpE;CAEA,YAA8C;EAC5C,OAAO,IAAI,iBAAiB,WAAW,KAAKD,aAAa,KAAKC,MAAM,GAAG,KAAK,GAAG;CACjF;AACF;;;AC3NA,SAAgB,IACd,SACO;CACP,MAAM,EAAE,SAAS,oBAAoB;CACrC,MAAM,MAAsB;EAC1B,cAAc,QAAQ,SAAS;EAC/B,qBAAqB,QAAQ,gBAAgB,QAAQ;EACrD,QAAQ,QAAQ,SAAS,UAAU;EACnC,aAAa,QAAQ,SAAS,QAAQ,eAAe;EACrD,SAAS,QAAQ,SAAS;EAC1B,wBAAwB,YAAY,QAAQ,sBAAsB,OAAO;EACzE;CACF;CAEA,MAAM,EAAE,YAAY,QAAQ;CAE5B,OAAO,IAAI,MAAM,CAAC,GAAY,EAC5B,IAAI,SAAS,MAAuB;EAClC,IAAI,OAAO,SAAS,UAClB;EAEF,IAAI,CAAC,OAAO,OAAO,QAAQ,YAAY,IAAI,GACzC;EAEF,MAAM,cAAc;EACpB,OAAO,IAAI,MACT,CAAC,GACD,EACE,IAAI,cAAc,WAA4B;GAC5C,IAAI,OAAO,cAAc,UACvB;GAEF,MAAM,QAAQ,wBAAwB,SAAS,aAAa,SAAS;GACrE,IAAI,OACF,OAAO,IAAI,eAAe,WAAW,OAAO,WAAW,KAAK,WAAW;EAG3E,EACF,CACF;CACF,EACF,CAAC;AACH"}
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 ...(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({ op, table: tableName, values })) {\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({ op, table: tableName, values: exprs })) {\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,WA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",
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.13.0-dev.31",
10
- "@prisma-next/framework-components": "0.13.0-dev.31",
11
- "@prisma-next/sql-contract": "0.13.0-dev.31",
12
- "@prisma-next/sql-operations": "0.13.0-dev.31",
13
- "@prisma-next/sql-relational-core": "0.13.0-dev.31"
9
+ "@prisma-next/contract": "0.13.0-dev.33",
10
+ "@prisma-next/framework-components": "0.13.0-dev.33",
11
+ "@prisma-next/sql-contract": "0.13.0-dev.33",
12
+ "@prisma-next/sql-operations": "0.13.0-dev.33",
13
+ "@prisma-next/sql-relational-core": "0.13.0-dev.33"
14
14
  },
15
15
  "devDependencies": {
16
- "@prisma-next/adapter-postgres": "0.13.0-dev.31",
17
- "@prisma-next/ids": "0.13.0-dev.31",
18
- "@prisma-next/sql-contract-ts": "0.13.0-dev.31",
19
- "@prisma-next/target-postgres": "0.13.0-dev.31",
20
- "@prisma-next/test-utils": "0.13.0-dev.31",
21
- "@prisma-next/utils": "0.13.0-dev.31",
22
- "@prisma-next/tsconfig": "0.13.0-dev.31",
23
- "@prisma-next/tsdown": "0.13.0-dev.31",
16
+ "@prisma-next/adapter-postgres": "0.13.0-dev.33",
17
+ "@prisma-next/ids": "0.13.0-dev.33",
18
+ "@prisma-next/sql-contract-ts": "0.13.0-dev.33",
19
+ "@prisma-next/target-postgres": "0.13.0-dev.33",
20
+ "@prisma-next/test-utils": "0.13.0-dev.33",
21
+ "@prisma-next/utils": "0.13.0-dev.33",
22
+ "@prisma-next/tsconfig": "0.13.0-dev.33",
23
+ "@prisma-next/tsdown": "0.13.0-dev.33",
24
24
  "tsdown": "0.22.1",
25
25
  "typescript": "5.9.3",
26
26
  "vitest": "4.1.8"
@@ -46,6 +46,9 @@ export function sql<C extends Contract<SqlStorage> & TableProxyContract>(
46
46
  }
47
47
  const table = resolveTableInNamespace(storage, namespaceId, tableName);
48
48
  if (table) {
49
+ // `namespaceId` is a dynamic Proxy key with no static literal here, so the
50
+ // proxy's `NsId` type param lands on its `string` default at this boundary.
51
+ // `TableProxyImpl` still forwards `NsId` through its `as()`/join chain.
49
52
  return new TableProxyImpl(tableName, table, tableName, ctx, namespaceId);
50
53
  }
51
54
  return undefined;
@@ -25,7 +25,7 @@ import type {
25
25
  StorageTableToScopeTable,
26
26
  Subquery,
27
27
  } from '../scope';
28
- import type { TableProxyContract, UnboundTables } from '../types/db';
28
+ import type { NamespaceTable, TableProxyContract } from '../types/db';
29
29
  import type { JoinedTables } from '../types/joined-tables';
30
30
  import type { DeleteQuery, InsertQuery, UpdateQuery } from '../types/mutation-query';
31
31
  import type { SelectQuery } from '../types/select-query';
@@ -47,16 +47,17 @@ import { tableSourceForProxy } from './table-source-for-proxy';
47
47
 
48
48
  export class TableProxyImpl<
49
49
  C extends TableProxyContract,
50
- Name extends string & keyof UnboundTables<C>,
50
+ Name extends string,
51
51
  Alias extends string,
52
52
  AvailableScope extends Scope,
53
53
  QC extends QueryContext,
54
+ NsId extends string = string,
54
55
  >
55
56
  extends BuilderBase<C['capabilities']>
56
- implements TableProxy<C, Name, Alias, AvailableScope, QC>
57
+ implements TableProxy<C, NsId, Name, Alias, AvailableScope, QC>
57
58
  {
58
59
  declare readonly [JoinOuterScope]: JoinSource<
59
- StorageTableToScopeTable<UnboundTables<C>[Name]>,
60
+ StorageTableToScopeTable<NamespaceTable<C, NsId, Name>>,
60
61
  Alias
61
62
  >[typeof JoinOuterScope];
62
63
 
@@ -97,7 +98,7 @@ export class TableProxyImpl<
97
98
  > => {
98
99
  return this.#toJoined().lateralJoin(alias, builder);
99
100
  },
100
- ) as TableProxy<C, Name, Alias, AvailableScope, QC>['lateralJoin'];
101
+ ) as TableProxy<C, NsId, Name, Alias, AvailableScope, QC>['lateralJoin'];
101
102
 
102
103
  outerLateralJoin = this._gate(
103
104
  { sql: { lateral: true } },
@@ -114,7 +115,7 @@ export class TableProxyImpl<
114
115
  > => {
115
116
  return this.#toJoined().outerLateralJoin(alias, builder);
116
117
  },
117
- ) as TableProxy<C, Name, Alias, AvailableScope, QC>['outerLateralJoin'];
118
+ ) as TableProxy<C, NsId, Name, Alias, AvailableScope, QC>['outerLateralJoin'];
118
119
 
119
120
  getJoinOuterScope(): Scope {
120
121
  return this.#scope;
@@ -126,8 +127,15 @@ export class TableProxyImpl<
126
127
 
127
128
  as<NewAlias extends string>(
128
129
  newAlias: NewAlias,
129
- ): TableProxy<C, Name, NewAlias, RebindScope<AvailableScope, Alias, NewAlias>, QC> {
130
- return new TableProxyImpl(this.#tableName, this.#table, newAlias, this.ctx, this.#namespaceId);
130
+ ): TableProxy<C, NsId, Name, NewAlias, RebindScope<AvailableScope, Alias, NewAlias>, QC> {
131
+ return new TableProxyImpl<
132
+ C,
133
+ Name,
134
+ NewAlias,
135
+ RebindScope<AvailableScope, Alias, NewAlias>,
136
+ QC,
137
+ NsId
138
+ >(this.#tableName, this.#table, newAlias, this.ctx, this.#namespaceId);
131
139
  }
132
140
 
133
141
  select<Columns extends (keyof AvailableScope['topLevel'] & string)[]>(
package/src/types/db.ts CHANGED
@@ -5,7 +5,20 @@ export type CapabilitiesBase = Record<string, Record<string, boolean>>;
5
5
 
6
6
  type NamespaceEntries = Readonly<Record<string, Readonly<Record<string, unknown>>>>;
7
7
 
8
+ // The application-domain models the table-proxy helpers read to map a storage
9
+ // table -> model and column -> field within a namespace coordinate. The index
10
+ // signature lets the helpers index `C['domain']['namespaces'][NsId]` by a
11
+ // generic `NsId` directly, so `FindModelForTable` / `FindFieldForColumn` no
12
+ // longer need a `C extends Contract<SqlStorage>` guard to reach the per-namespace
13
+ // models; concrete emitted contracts (whose models are richer) satisfy it.
14
+ type NamespaceDomain = Readonly<
15
+ Record<string, { readonly models: Readonly<Record<string, unknown>> }>
16
+ >;
17
+
8
18
  export type TableProxyContract = {
19
+ readonly domain: {
20
+ readonly namespaces: NamespaceDomain;
21
+ };
9
22
  readonly storage: {
10
23
  readonly namespaces: Readonly<Record<string, { readonly entries: NamespaceEntries }>>;
11
24
  };
@@ -38,19 +51,34 @@ export type TableInAnyNamespace<C extends TableProxyContract, Name extends strin
38
51
  : never;
39
52
  }[keyof C['storage']['namespaces']];
40
53
 
54
+ // The exact storage table at a single namespace coordinate. Resolving through
55
+ // the coordinate (rather than the cross-namespace `UnboundTables` union) keeps
56
+ // a bare table name shared across namespaces resolving to each namespace's own
57
+ // table — no per-namespace column intersection. `TablesInNamespace` narrows the
58
+ // open-dict `entries['table']` (`Record<string, unknown>`) back to the typed
59
+ // `StorageTable` map before indexing by the bare name.
60
+ export type NamespaceTable<
61
+ C extends TableProxyContract,
62
+ NsId extends string,
63
+ Name extends string,
64
+ > = TablesInNamespace<C['storage']['namespaces'][NsId]>[Name];
65
+
41
66
  // The tables of a single storage namespace, keyed by bare table name. Lets
42
67
  // callers reach a table by its namespace coordinate (`db.<ns>.<table>`) when
43
- // the same bare name is declared in more than one namespace.
68
+ // the same bare name is declared in more than one namespace. The `NsId`
69
+ // coordinate is threaded into each `TableProxy` so its column/field resolution
70
+ // is a function of `(NsId, Name)`, not `Name` alone.
44
71
  export type Namespace<
45
72
  C extends TableProxyContract,
46
- NsId extends keyof C['storage']['namespaces'],
73
+ NsId extends string & keyof C['storage']['namespaces'],
47
74
  > = {
48
75
  readonly [Name in keyof TablesInNamespace<C['storage']['namespaces'][NsId]> & string]: TableProxy<
49
76
  C,
77
+ NsId,
50
78
  Name
51
79
  >;
52
80
  };
53
81
 
54
82
  export type Db<C extends TableProxyContract> = {
55
- readonly [Ns in keyof C['storage']['namespaces']]: Namespace<C, Ns>;
83
+ readonly [Ns in keyof C['storage']['namespaces'] & string]: Namespace<C, Ns>;
56
84
  };
@@ -1,11 +1,10 @@
1
- import type { Contract, ContractModelDefinitions } from '@prisma-next/contract/types';
2
1
  import type {
3
2
  ExtractCodecTypes,
4
3
  ExtractFieldInputTypes,
5
- ExtractFieldOutputTypes,
6
4
  ExtractQueryOperationTypes,
7
5
  StorageTable,
8
6
  } from '@prisma-next/sql-contract/types';
7
+ import type { ComputeColumnJsType } from '@prisma-next/sql-relational-core/types';
9
8
  import type { Expression, FieldProxy, Functions } from '../expression';
10
9
  import type {
11
10
  DefaultScope,
@@ -16,98 +15,111 @@ import type {
16
15
  Scope,
17
16
  StorageTableToScopeTable,
18
17
  } from '../scope';
19
- import type { TableProxyContract, UnboundTables } from './db';
18
+ import type { NamespaceTable, TableProxyContract } from './db';
20
19
  import type { DeleteQuery, InsertQuery, InsertValues, UpdateQuery } from './mutation-query';
21
20
  import type { WithJoin, WithSelect } from './shared';
22
21
 
23
- type FindModelForTable<C, TableName extends string> = C extends Contract
22
+ type FindModelForTable<
23
+ C extends TableProxyContract,
24
+ NsId extends string,
25
+ TableName extends string,
26
+ > = C['domain']['namespaces'][NsId]['models'] extends infer Models extends Record<string, unknown>
24
27
  ? {
25
- [M in keyof ContractModelDefinitions<C> & string]: ContractModelDefinitions<C>[M] extends {
28
+ [M in keyof Models & string]: Models[M] extends {
26
29
  readonly storage: { readonly table: TableName };
27
30
  }
28
31
  ? M
29
32
  : never;
30
- }[keyof ContractModelDefinitions<C> & string]
33
+ }[keyof Models & string]
31
34
  : never;
32
35
 
33
- type FindFieldForColumn<C, ModelName extends string, ColumnName extends string> = C extends Contract
34
- ? ModelName extends keyof ContractModelDefinitions<C>
35
- ? {
36
- [F in keyof ContractModelDefinitions<C>[ModelName]['storage']['fields'] &
37
- string]: ContractModelDefinitions<C>[ModelName]['storage']['fields'][F] extends {
38
- readonly column: ColumnName;
39
- }
40
- ? F
41
- : never;
42
- }[keyof ContractModelDefinitions<C>[ModelName]['storage']['fields'] & string]
36
+ type FindFieldForColumn<
37
+ C extends TableProxyContract,
38
+ NsId extends string,
39
+ ModelName extends string,
40
+ ColumnName extends string,
41
+ > = C['domain']['namespaces'][NsId]['models'] extends infer Models extends Record<string, unknown>
42
+ ? ModelName extends keyof Models
43
+ ? Models[ModelName] extends {
44
+ readonly storage: { readonly fields: infer Fields extends Record<string, unknown> };
45
+ }
46
+ ? {
47
+ [F in keyof Fields & string]: Fields[F] extends { readonly column: ColumnName }
48
+ ? F
49
+ : never;
50
+ }[keyof Fields & string]
51
+ : never
43
52
  : never
44
53
  : never;
45
54
 
55
+ // The select-result row's column types for a table at a namespace coordinate.
56
+ // Each column resolves through `ComputeColumnJsType` with the coordinate, so
57
+ // refined per-namespace output types (e.g. `Vector<N>`) are preserved and
58
+ // same-named tables across namespaces resolve to each namespace's own columns.
59
+ // `ComputeColumnJsType`'s constraint is the minimal `ColumnResolutionContract`,
60
+ // which `TableProxyContract` satisfies, so `C` is indexed directly — no
61
+ // `C extends Contract<SqlStorage>` guard.
46
62
  type ResolvedColumnTypes<
47
- C,
63
+ C extends TableProxyContract,
64
+ NsId extends string,
48
65
  TableName extends string,
49
- FieldTypes extends Record<string, Record<string, unknown>>,
50
- > = string extends keyof FieldTypes
51
- ? Record<string, never>
52
- : FindModelForTable<C, TableName> extends infer ModelName extends string
53
- ? ModelName extends keyof FieldTypes
54
- ? C extends TableProxyContract
55
- ? UnboundTables<C> extends infer Tables extends Record<string, StorageTable>
56
- ? TableName extends keyof Tables
57
- ? {
58
- [ColName in keyof Tables[TableName]['columns'] & string]: FindFieldForColumn<
59
- C,
60
- ModelName,
61
- ColName
62
- > extends infer FieldName extends string
63
- ? FieldName extends keyof FieldTypes[ModelName]
64
- ? FieldTypes[ModelName][FieldName]
65
- : unknown
66
- : unknown;
67
- }
68
- : Record<string, never>
69
- : Record<string, never>
70
- : Record<string, never>
71
- : Record<string, never>
66
+ > =
67
+ NamespaceTable<C, NsId, TableName> extends infer Table extends StorageTable
68
+ ? {
69
+ [ColName in keyof Table['columns'] & string]: ComputeColumnJsType<
70
+ C,
71
+ NsId,
72
+ TableName,
73
+ ColName,
74
+ ExtractCodecTypes<C>
75
+ >;
76
+ }
72
77
  : Record<string, never>;
73
78
 
74
79
  type ResolvedInsertValues<
75
- C,
80
+ C extends TableProxyContract,
81
+ NsId extends string,
76
82
  Table extends StorageTable,
77
83
  TableName extends string,
78
84
  CT extends Record<string, { readonly input: unknown }>,
79
- FieldInputs extends Record<string, Record<string, unknown>>,
85
+ FieldInputs extends Record<string, Record<string, Record<string, unknown>>>,
80
86
  > = string extends keyof FieldInputs
81
87
  ? InsertValues<Table, CT>
82
- : FindModelForTable<C, TableName> extends infer ModelName extends string
83
- ? ModelName extends keyof FieldInputs
84
- ? {
85
- [K in keyof Table['columns']]?: FindFieldForColumn<
86
- C,
87
- ModelName,
88
- K & string
89
- > extends infer FieldName extends string
90
- ? FieldName extends keyof FieldInputs[ModelName]
91
- ? Table['columns'][K]['nullable'] extends true
92
- ? NonNullable<FieldInputs[ModelName][FieldName]> | null
93
- : NonNullable<FieldInputs[ModelName][FieldName]>
94
- : Table['columns'][K]['codecId'] extends keyof CT
95
- ? CT[Table['columns'][K]['codecId']]['input']
96
- : unknown
97
- : Table['columns'][K]['codecId'] extends keyof CT
98
- ? CT[Table['columns'][K]['codecId']]['input']
99
- : unknown;
100
- }
88
+ : NsId extends keyof FieldInputs
89
+ ? FieldInputs[NsId] extends infer NsInputs extends Record<string, Record<string, unknown>>
90
+ ? FindModelForTable<C, NsId, TableName> extends infer ModelName extends string
91
+ ? ModelName extends keyof NsInputs
92
+ ? {
93
+ [K in keyof Table['columns']]?: FindFieldForColumn<
94
+ C,
95
+ NsId,
96
+ ModelName,
97
+ K & string
98
+ > extends infer FieldName extends string
99
+ ? FieldName extends keyof NsInputs[ModelName]
100
+ ? Table['columns'][K]['nullable'] extends true
101
+ ? NonNullable<NsInputs[ModelName][FieldName]> | null
102
+ : NonNullable<NsInputs[ModelName][FieldName]>
103
+ : Table['columns'][K]['codecId'] extends keyof CT
104
+ ? CT[Table['columns'][K]['codecId']]['input']
105
+ : unknown
106
+ : Table['columns'][K]['codecId'] extends keyof CT
107
+ ? CT[Table['columns'][K]['codecId']]['input']
108
+ : unknown;
109
+ }
110
+ : InsertValues<Table, CT>
111
+ : InsertValues<Table, CT>
101
112
  : InsertValues<Table, CT>
102
113
  : InsertValues<Table, CT>;
103
114
 
104
115
  type ResolvedUpdateValues<
105
- C,
116
+ C extends TableProxyContract,
117
+ NsId extends string,
106
118
  Table extends StorageTable,
107
119
  TableName extends string,
108
120
  CT extends Record<string, { readonly input: unknown }>,
109
- FieldInputs extends Record<string, Record<string, unknown>>,
110
- > = ResolvedInsertValues<C, Table, TableName, CT, FieldInputs>;
121
+ FieldInputs extends Record<string, Record<string, Record<string, unknown>>>,
122
+ > = ResolvedInsertValues<C, NsId, Table, TableName, CT, FieldInputs>;
111
123
 
112
124
  type ResolvedUpdateExpressions<Table extends StorageTable> = {
113
125
  [K in keyof Table['columns']]?: Expression<{
@@ -116,31 +128,37 @@ type ResolvedUpdateExpressions<Table extends StorageTable> = {
116
128
  }>;
117
129
  };
118
130
 
119
- export type ContractToQC<C extends TableProxyContract, Name extends string = string> = {
131
+ export type ContractToQC<
132
+ C extends TableProxyContract,
133
+ NsId extends string = string,
134
+ Name extends string = string,
135
+ > = {
120
136
  readonly codecTypes: ExtractCodecTypes<C>;
121
137
  readonly capabilities: C['capabilities'];
122
138
  readonly queryOperationTypes: ExtractQueryOperationTypes<C>;
123
- readonly resolvedColumnOutputTypes: ResolvedColumnTypes<C, Name, ExtractFieldOutputTypes<C>>;
139
+ readonly resolvedColumnOutputTypes: ResolvedColumnTypes<C, NsId, Name>;
124
140
  };
125
141
 
126
142
  export interface TableProxy<
127
143
  C extends TableProxyContract,
128
- Name extends string & keyof UnboundTables<C>,
144
+ NsId extends string,
145
+ Name extends string,
129
146
  Alias extends string = Name,
130
- AvailableScope extends Scope = DefaultScope<Name, UnboundTables<C>[Name]>,
131
- QC extends QueryContext = ContractToQC<C, Name>,
132
- > extends JoinSource<StorageTableToScopeTable<UnboundTables<C>[Name]>, Alias>,
147
+ AvailableScope extends Scope = DefaultScope<Name, NamespaceTable<C, NsId, Name>>,
148
+ QC extends QueryContext = ContractToQC<C, NsId, Name>,
149
+ > extends JoinSource<StorageTableToScopeTable<NamespaceTable<C, NsId, Name>>, Alias>,
133
150
  WithSelect<QC, AvailableScope, EmptyRow>,
134
151
  WithJoin<QC, AvailableScope, C['capabilities']> {
135
152
  as<NewAlias extends string>(
136
153
  newAlias: NewAlias,
137
- ): TableProxy<C, Name, NewAlias, RebindScope<AvailableScope, Alias, NewAlias>, QC>;
154
+ ): TableProxy<C, NsId, Name, NewAlias, RebindScope<AvailableScope, Alias, NewAlias>, QC>;
138
155
 
139
156
  insert(
140
157
  rows: ReadonlyArray<
141
158
  ResolvedInsertValues<
142
159
  C,
143
- UnboundTables<C>[Name],
160
+ NsId,
161
+ NamespaceTable<C, NsId, Name>,
144
162
  Name,
145
163
  QC['codecTypes'],
146
164
  ExtractFieldInputTypes<C>
@@ -151,7 +169,8 @@ export interface TableProxy<
151
169
  update(
152
170
  set: ResolvedUpdateValues<
153
171
  C,
154
- UnboundTables<C>[Name],
172
+ NsId,
173
+ NamespaceTable<C, NsId, Name>,
155
174
  Name,
156
175
  QC['codecTypes'],
157
176
  ExtractFieldInputTypes<C>
@@ -162,7 +181,7 @@ export interface TableProxy<
162
181
  callback: (
163
182
  fields: FieldProxy<AvailableScope>,
164
183
  fns: Functions<QC>,
165
- ) => ResolvedUpdateExpressions<UnboundTables<C>[Name]>,
184
+ ) => ResolvedUpdateExpressions<NamespaceTable<C, NsId, Name>>,
166
185
  ): UpdateQuery<QC, AvailableScope, EmptyRow>;
167
186
 
168
187
  delete(): DeleteQuery<QC, AvailableScope, EmptyRow>;