@prisma-next/sql-builder 0.5.0-dev.9 → 0.6.0-dev.1
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.
- package/dist/{db-Cggb4WvK.d.mts → db-DkZcNekS.d.mts} +72 -126
- package/dist/db-DkZcNekS.d.mts.map +1 -0
- package/dist/exports/types.d.mts +1 -1
- package/dist/exports/types.mjs +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/runtime/index.d.mts +16 -8
- package/dist/runtime/index.d.mts.map +1 -1
- package/dist/runtime/index.mjs +130 -98
- package/dist/runtime/index.mjs.map +1 -1
- package/package.json +17 -18
- package/src/expression.ts +33 -78
- package/src/runtime/builder-base.ts +26 -40
- package/src/runtime/expression-impl.ts +14 -9
- package/src/runtime/field-proxy.ts +20 -1
- package/src/runtime/functions.ts +87 -49
- package/src/runtime/mutation-impl.ts +28 -10
- package/src/scope.ts +9 -6
- package/dist/db-Cggb4WvK.d.mts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["BOOL_FIELD: BooleanCodecType","projectionTypes: Record<string, string>","codecs: Record<string, string>","uniqueRefs: import('@prisma-next/sql-relational-core/ast').ParamRef[]","meta: PlanMeta","fields: ScopeTable","topLevel: ScopeTable","result: ScopeTable","namespaces: Record<string, ScopeTable>","projections: ProjectionItem[]","newRowFields: Record<string, ScopeField>","combined","#state","#buildLateral","#addLateralJoin","#addJoin","subqueryRowFields: ScopeTable","params: Record<string, ParamRef>","#tableName","#table","#scope","#values","#returningColumns","#rowFields","newRowFields: Record<string, ScopeField>","#setValues","#whereCallbacks","#tableName","#table","#fromSource","#scope","#toJoined","ctx: BuilderContext","options"],"sources":["../../src/runtime/expression-impl.ts","../../src/runtime/field-proxy.ts","../../src/runtime/functions.ts","../../src/runtime/builder-base.ts","../../src/runtime/query-impl.ts","../../src/runtime/joined-tables-impl.ts","../../src/runtime/mutation-impl.ts","../../src/runtime/table-proxy-impl.ts","../../src/runtime/sql.ts"],"sourcesContent":["import type { AnyExpression as AstExpression } from '@prisma-next/sql-relational-core/ast';\nimport type { Expression } from '../expression';\n// biome-ignore lint/correctness/noUnusedImports: used in `declare` property\nimport type { ExpressionType, ScopeField } from '../scope';\n\n/**\n * Runtime wrapper around a relational-core AST expression node.\n * Carries ScopeField metadata (codecId, nullable) for plan generation.\n */\nexport class ExpressionImpl<T extends ScopeField = ScopeField> implements Expression<T> {\n declare readonly [ExpressionType]: T;\n private readonly ast: AstExpression;\n readonly field: T;\n\n constructor(ast: AstExpression, field: T) {\n this.ast = ast;\n this.field = field;\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) return new ExpressionImpl(IdentifierRef.of(prop), topField);\n }\n\n if (Object.hasOwn(scope.namespaces, prop)) {\n const nsFields = scope.namespaces[prop];\n if (nsFields) return createNamespaceProxy(prop, nsFields);\n }\n\n return undefined;\n },\n });\n}\n\nfunction createNamespaceProxy(\n namespaceName: string,\n fields: ScopeTable,\n): Record<string, ExpressionImpl> {\n return new Proxy({} as Record<string, ExpressionImpl>, {\n get(_target, prop: string) {\n if (Object.hasOwn(fields, prop)) {\n const field = fields[prop];\n if (field) return new ExpressionImpl(ColumnRef.of(namespaceName, prop), field);\n }\n return undefined;\n },\n });\n}\n","import type { SqlOperationEntry } from '@prisma-next/sql-operations';\nimport {\n AggregateExpr,\n AndExpr,\n type AnyExpression as AstExpression,\n BinaryExpr,\n type BinaryOp,\n ExistsExpr,\n ListExpression,\n LiteralExpr,\n NullCheckExpr,\n OperationExpr,\n OrExpr,\n ParamRef,\n SubqueryExpr,\n} from '@prisma-next/sql-relational-core/ast';\nimport type {\n AggregateFunctions,\n AggregateOnlyFunctions,\n BooleanCodecType,\n BuiltinFunctions,\n Expression,\n ExpressionOrValue,\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 }>;\ntype ExprOrVal<T extends ScopeField = ScopeField> = ExpressionOrValue<T, CodecTypes>;\n\nconst BOOL_FIELD: BooleanCodecType = { codecId: 'pg/bool@1', nullable: false };\n\nfunction resolve(value: ExprOrVal): AstExpression {\n if (value instanceof ExpressionImpl) return value.buildAst();\n return ParamRef.of(value);\n}\n\nfunction resolveToAst(value: ExprOrVal): AstExpression {\n if (value instanceof ExpressionImpl) return value.buildAst();\n return new LiteralExpr(value);\n}\n\nfunction boolExpr(astNode: AstExpression): ExpressionImpl<BooleanCodecType> {\n return new ExpressionImpl(astNode, BOOL_FIELD);\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(new BinaryExpr('eq', resolve(a), resolve(b)));\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(new BinaryExpr('neq', resolve(a), resolve(b)));\n}\n\nfunction comparison(a: ExprOrVal, b: ExprOrVal, op: BinaryOp): ExpressionImpl<BooleanCodecType> {\n return boolExpr(new BinaryExpr(op, resolve(a), resolve(b)));\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 binaryFn = op === 'in' ? BinaryExpr.in : BinaryExpr.notIn;\n\n if (Array.isArray(valuesOrSubquery)) {\n const refs = valuesOrSubquery.map((v) => resolve(v));\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 as ExpressionImpl).field.codecId,\n nullable: true as const,\n });\n}\n\nfunction createBuiltinFunctions() {\n return {\n eq: (a: ExprOrVal, b: ExprOrVal) => eq(a, b),\n ne: (a: ExprOrVal, b: ExprOrVal) => ne(a, b),\n gt: (a: ExprOrVal, b: ExprOrVal) => comparison(a, b, 'gt'),\n gte: (a: ExprOrVal, b: ExprOrVal) => comparison(a, b, 'gte'),\n lt: (a: ExprOrVal, b: ExprOrVal) => comparison(a, b, 'lt'),\n lte: (a: ExprOrVal, b: ExprOrVal) => comparison(a, b, 'lte'),\n and: (...exprs: ExprOrVal<BooleanCodecType>[]) => boolExpr(AndExpr.of(exprs.map(resolveToAst))),\n or: (...exprs: ExprOrVal<BooleanCodecType>[]) => boolExpr(OrExpr.of(exprs.map(resolveToAst))),\n exists: (subquery: Subquery<Record<string, ScopeField>>) =>\n boolExpr(ExistsExpr.exists(subquery.buildAst())),\n notExists: (subquery: Subquery<Record<string, ScopeField>>) =>\n boolExpr(ExistsExpr.notExists(subquery.buildAst())),\n in: (\n expr: Expression<ScopeField>,\n valuesOrSubquery: Subquery<Record<string, ScopeField>> | ExprOrVal[],\n ) => inOrNotIn(expr, valuesOrSubquery, 'in'),\n notIn: (\n expr: Expression<ScopeField>,\n valuesOrSubquery: Subquery<Record<string, ScopeField>> | ExprOrVal[],\n ) => inOrNotIn(expr, valuesOrSubquery, 'notIn'),\n } satisfies BuiltinFunctions<CodecTypes>;\n}\n\nfunction createAggregateOnlyFunctions() {\n return {\n count: (expr?: Expression<ScopeField>) => {\n const astExpr = expr ? expr.buildAst() : undefined;\n return new ExpressionImpl(AggregateExpr.count(astExpr), {\n codecId: 'pg/int8@1',\n nullable: false,\n });\n },\n sum: (expr: Expression<ScopeField>) => numericAgg('sum', expr),\n avg: (expr: Expression<ScopeField>) => numericAgg('avg', expr),\n min: (expr: Expression<ScopeField>) => numericAgg('min', expr),\n max: (expr: Expression<ScopeField>) => numericAgg('max', expr),\n } satisfies AggregateOnlyFunctions;\n}\n\nfunction createExtensionFunction(\n name: string,\n entry: SqlOperationEntry,\n): (...args: ExprOrVal[]) => ExpressionImpl {\n return (...args: ExprOrVal[]) => {\n const resolvedArgs = args.map((arg, i) => {\n if (arg instanceof ExpressionImpl) return arg.buildAst();\n const codecId = entry.args[i]?.codecId;\n return ParamRef.of(arg, codecId ? { codecId } : undefined);\n });\n const self = resolvedArgs[0] as AstExpression;\n const restArgs = resolvedArgs.slice(1);\n\n return new ExpressionImpl(\n new OperationExpr({\n method: name,\n self,\n args: restArgs.length > 0 ? restArgs : undefined,\n returns: entry.returns,\n lowering: entry.lowering,\n }),\n entry.returns,\n );\n };\n}\n\nexport function createFunctions<QC extends QueryContext>(\n queryOperationTypes: Readonly<Record<string, SqlOperationEntry>>,\n): Functions<QC> {\n const builtins = createBuiltinFunctions();\n\n return new Proxy({} as Functions<QC>, {\n get(_target, prop: string) {\n const builtin = (builtins as Record<string, unknown>)[prop];\n if (builtin) return builtin;\n\n const extOp = queryOperationTypes[prop];\n if (extOp) {\n return createExtensionFunction(prop, extOp);\n }\n return undefined;\n },\n });\n}\n\nexport function createAggregateFunctions<QC extends QueryContext>(\n queryOperationTypes: Readonly<Record<string, SqlOperationEntry>>,\n): AggregateFunctions<QC> {\n const baseFns = createFunctions<QC>(queryOperationTypes);\n const aggregates = createAggregateOnlyFunctions();\n\n return new Proxy({} as AggregateFunctions<QC>, {\n get(_target, prop: string) {\n const agg = (aggregates as Record<string, unknown>)[prop];\n if (agg) return agg;\n\n return (baseFns as Record<string, unknown>)[prop];\n },\n });\n}\n","import type { PlanMeta } from '@prisma-next/contract/types';\nimport type { StorageTable } from '@prisma-next/sql-contract/types';\nimport type { SqlOperationEntry } from '@prisma-next/sql-operations';\nimport {\n AndExpr,\n type AnyExpression as AstExpression,\n IdentifierRef,\n OrderByItem,\n ProjectionItem,\n SelectAst,\n type TableSource,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type {\n AppliedMutationDefault,\n MutationDefaultsOptions,\n} from '@prisma-next/sql-relational-core/query-lane-context';\nimport type {\n AggregateFunctions,\n Expression,\n FieldProxy,\n OrderByOptions,\n OrderByScope,\n} from '../expression';\nimport type {\n GatedMethod,\n MergeScopes,\n NullableScope,\n QueryContext,\n Scope,\n ScopeField,\n ScopeTable,\n} from '../scope';\nimport type { ExpressionImpl } from './expression-impl';\nimport { createFieldProxy } from './field-proxy';\nimport { createAggregateFunctions, createFunctions } from './functions';\n\nexport type ExprCallback = (fields: FieldProxy<Scope>, fns: unknown) => Expression<ScopeField>;\n\nexport class BuilderBase<Capabilities = unknown> {\n protected readonly ctx: BuilderContext;\n\n constructor(ctx: BuilderContext) {\n this.ctx = ctx;\n }\n\n protected _gate<Req extends Record<string, Record<string, boolean>>, Args extends unknown[], R>(\n required: Req,\n methodName: string,\n method: (...args: Args) => R,\n ): GatedMethod<Capabilities, Req, (...args: Args) => R> {\n return ((...args: Args): R => {\n assertCapability(this.ctx, required, methodName);\n return method(...args);\n }) as GatedMethod<Capabilities, Req, (...args: Args) => R>;\n }\n}\n\nexport interface BuilderState {\n readonly from: TableSource;\n readonly joins: readonly import('@prisma-next/sql-relational-core/ast').JoinAst[];\n readonly projections: readonly ProjectionItem[];\n readonly where: readonly AstExpression[];\n readonly orderBy: readonly OrderByItem[];\n readonly groupBy: readonly AstExpression[];\n readonly having: AstExpression | undefined;\n readonly limit: number | undefined;\n readonly offset: number | undefined;\n readonly distinct: true | undefined;\n readonly distinctOn: readonly AstExpression[] | undefined;\n readonly scope: Scope;\n readonly rowFields: Record<string, ScopeField>;\n}\n\nexport interface BuilderContext {\n readonly capabilities: Record<string, Record<string, boolean>>;\n readonly queryOperationTypes: Readonly<Record<string, SqlOperationEntry>>;\n readonly target: string;\n readonly storageHash: string;\n readonly applyMutationDefaults: (\n options: MutationDefaultsOptions,\n ) => ReadonlyArray<AppliedMutationDefault>;\n}\n\nexport function emptyState(from: TableSource, scope: Scope): BuilderState {\n return {\n from,\n joins: [],\n projections: [],\n where: [],\n orderBy: [],\n groupBy: [],\n having: undefined,\n limit: undefined,\n offset: undefined,\n distinct: undefined,\n distinctOn: undefined,\n scope,\n rowFields: {},\n };\n}\n\nexport function cloneState(state: BuilderState, overrides: Partial<BuilderState>): BuilderState {\n return { ...state, ...overrides };\n}\n\nexport function combineWhereExprs(exprs: readonly AstExpression[]): AstExpression | undefined {\n if (exprs.length === 0) return undefined;\n if (exprs.length === 1) return exprs[0];\n return AndExpr.of(exprs);\n}\n\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 rowFields: Record<string, ScopeField>,\n ctx: BuilderContext,\n): SqlQueryPlan<Row> {\n const projectionTypes: Record<string, string> = {};\n const codecs: Record<string, string> = {};\n for (const [alias, field] of Object.entries(rowFields)) {\n projectionTypes[alias] = field.codecId;\n codecs[alias] = field.codecId;\n }\n\n const paramRefs = ast.collectParamRefs();\n const seen = new Set<import('@prisma-next/sql-relational-core/ast').ParamRef>();\n const uniqueRefs: import('@prisma-next/sql-relational-core/ast').ParamRef[] = [];\n for (const ref of paramRefs) {\n if (!seen.has(ref)) {\n seen.add(ref);\n uniqueRefs.push(ref);\n }\n }\n const paramValues = uniqueRefs.map((r) => r.value);\n const paramDescriptors = uniqueRefs.map((ref, i) => ({\n index: i + 1,\n source: 'dsl' as const,\n ...(ref.codecId ? { codecId: ref.codecId } : {}),\n }));\n\n for (const [i, ref] of uniqueRefs.entries()) {\n if (ref.codecId) codecs[`$${i + 1}`] = ref.codecId;\n }\n\n const hasProjectionTypes = Object.keys(projectionTypes).length > 0;\n const hasCodecs = Object.keys(codecs).length > 0;\n\n const meta: PlanMeta = Object.freeze({\n target: ctx.target,\n storageHash: ctx.storageHash,\n lane: 'dsl',\n paramDescriptors,\n ...(hasProjectionTypes ? { projectionTypes } : {}),\n ...(hasCodecs ? { annotations: Object.freeze({ codecs: Object.freeze(codecs) }) } : {}),\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), state.rowFields, ctx);\n}\n\nexport function tableToScope(name: string, table: StorageTable): Scope {\n const fields: ScopeTable = {};\n for (const [colName, col] of Object.entries(table.columns)) {\n fields[colName] = { codecId: col.codecId, nullable: col.nullable };\n }\n return { topLevel: { ...fields }, namespaces: { [name]: fields } };\n}\n\nexport function mergeScopes<A extends Scope, B extends Scope>(a: A, b: B): MergeScopes<A, B> {\n const topLevel: ScopeTable = {};\n for (const [k, v] of Object.entries(a.topLevel)) {\n if (!(k in b.topLevel)) topLevel[k] = v;\n }\n for (const [k, v] of Object.entries(b.topLevel)) {\n if (!(k in a.topLevel)) topLevel[k] = v;\n }\n return {\n topLevel,\n namespaces: { ...a.namespaces, ...b.namespaces },\n } as MergeScopes<A, B>;\n}\n\nexport function nullableScope<S extends Scope>(scope: S): NullableScope<S> {\n const mkNullable = (tbl: ScopeTable): ScopeTable => {\n const result: ScopeTable = {};\n for (const [k, v] of Object.entries(tbl)) {\n result[k] = { codecId: v.codecId, nullable: true };\n }\n return result;\n };\n const namespaces: Record<string, ScopeTable> = {};\n for (const [k, v] of Object.entries(scope.namespaces)) {\n namespaces[k] = mkNullable(v);\n }\n return { topLevel: mkNullable(scope.topLevel), namespaces } as NullableScope<S>;\n}\n\nexport function orderByScopeOf<S extends Scope, R extends Record<string, ScopeField>>(\n scope: S,\n rowFields: R,\n): OrderByScope<S, R> {\n return {\n topLevel: { ...scope.topLevel, ...rowFields },\n namespaces: scope.namespaces,\n };\n}\n\nexport function assertCapability(\n ctx: BuilderContext,\n required: Record<string, Record<string, boolean>>,\n methodName: string,\n): void {\n for (const [ns, keys] of Object.entries(required)) {\n for (const key of Object.keys(keys)) {\n if (!ctx.capabilities[ns]?.[key]) {\n throw new Error(`${methodName}() requires capability ${ns}.${key}`);\n }\n }\n }\n}\n\nexport function resolveSelectArgs(\n args: unknown[],\n scope: Scope,\n ctx: BuilderContext,\n): { projections: ProjectionItem[]; newRowFields: Record<string, ScopeField> } {\n const projections: ProjectionItem[] = [];\n const newRowFields: Record<string, ScopeField> = {};\n\n if (args.length === 0) return { projections, newRowFields };\n\n if (typeof args[0] === 'string' && (args.length === 1 || typeof args[1] !== 'function')) {\n for (const colName of args as string[]) {\n const field = scope.topLevel[colName];\n if (!field) throw new Error(`Column \"${colName}\" not found in scope`);\n projections.push(ProjectionItem.of(colName, IdentifierRef.of(colName)));\n newRowFields[colName] = field;\n }\n return { projections, newRowFields };\n }\n\n if (typeof args[0] === 'string' && typeof args[1] === 'function') {\n const alias = args[0] as string;\n const exprFn = args[1] as (\n f: FieldProxy<Scope>,\n fns: AggregateFunctions<QueryContext>,\n ) => Expression<ScopeField>;\n const fns = createAggregateFunctions(ctx.queryOperationTypes);\n const result = exprFn(createFieldProxy(scope), fns);\n projections.push(ProjectionItem.of(alias, result.buildAst()));\n newRowFields[alias] = (result as ExpressionImpl).field;\n return { projections, newRowFields };\n }\n\n if (typeof args[0] === 'function') {\n const callbackFn = args[0] as (\n f: FieldProxy<Scope>,\n fns: AggregateFunctions<QueryContext>,\n ) => Record<string, Expression<ScopeField>>;\n const fns = createAggregateFunctions(ctx.queryOperationTypes);\n const record = callbackFn(createFieldProxy(scope), fns);\n for (const [key, expr] of Object.entries(record)) {\n projections.push(ProjectionItem.of(key, expr.buildAst()));\n newRowFields[key] = (expr as ExpressionImpl).field;\n }\n return { projections, newRowFields };\n }\n\n throw new Error('Invalid .select() arguments');\n}\n\nexport function resolveOrderBy(\n arg: unknown,\n options: OrderByOptions | undefined,\n scope: Scope,\n rowFields: Record<string, ScopeField>,\n ctx: BuilderContext,\n useAggregateFns: boolean,\n): OrderByItem {\n const dir = options?.direction ?? 'asc';\n\n if (typeof arg === 'string') {\n const combined = orderByScopeOf(scope, rowFields);\n if (!(arg in combined.topLevel))\n throw new Error(`Column \"${arg}\" not found in scope for orderBy`);\n const expr = IdentifierRef.of(arg);\n return dir === 'asc' ? OrderByItem.asc(expr) : OrderByItem.desc(expr);\n }\n\n if (typeof arg === 'function') {\n const combined = orderByScopeOf(scope, rowFields);\n const fns = useAggregateFns\n ? createAggregateFunctions(ctx.queryOperationTypes)\n : createFunctions(ctx.queryOperationTypes);\n const result = (arg as ExprCallback)(createFieldProxy(combined), fns);\n return dir === 'asc' ? OrderByItem.asc(result.buildAst()) : OrderByItem.desc(result.buildAst());\n }\n\n throw new Error('Invalid orderBy argument');\n}\n\nexport function resolveGroupBy(\n args: unknown[],\n scope: Scope,\n rowFields: Record<string, ScopeField>,\n ctx: BuilderContext,\n): AstExpression[] {\n if (typeof args[0] === 'string') {\n const combined = orderByScopeOf(scope, rowFields);\n return (args as string[]).map((colName) => {\n if (!(colName in combined.topLevel))\n throw new Error(`Column \"${colName}\" not found in scope for groupBy`);\n return IdentifierRef.of(colName);\n });\n }\n\n if (typeof args[0] === 'function') {\n const combined = orderByScopeOf(scope, rowFields);\n const fns = createFunctions(ctx.queryOperationTypes);\n const result = (args[0] as ExprCallback)(createFieldProxy(combined), fns);\n return [result.buildAst()];\n }\n\n throw new Error('Invalid groupBy arguments');\n}\n\nexport function resolveDistinctOn(\n args: unknown[],\n scope: Scope,\n rowFields: Record<string, ScopeField>,\n ctx: BuilderContext,\n): AstExpression[] {\n if (args.length === 1 && typeof args[0] === 'function') {\n const combined = orderByScopeOf(scope, rowFields);\n const fns = createFunctions(ctx.queryOperationTypes);\n const result = (args[0] as ExprCallback)(createFieldProxy(combined), fns);\n return [result.buildAst()];\n }\n const combined = orderByScopeOf(scope, rowFields);\n return (args as string[]).map((colName) => {\n if (!(colName in combined.topLevel))\n throw new Error(`Column \"${colName}\" not found in scope for distinctOn`);\n return IdentifierRef.of(colName);\n });\n}\n","import { DerivedTableSource, type SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type {\n AggregateFunctions,\n BooleanCodecType,\n Expression,\n ExpressionBuilder,\n ExtractScopeFields,\n FieldProxy,\n Functions,\n OrderByOptions,\n OrderByScope,\n WithField,\n WithFields,\n} from '../expression';\nimport type { ResolveRow } from '../resolve';\nimport type {\n Expand,\n JoinOuterScope,\n JoinSource,\n QueryContext,\n Scope,\n ScopeField,\n // biome-ignore lint/correctness/noUnusedImports: used in `declare` property\n SubqueryMarker,\n} from '../scope';\nimport type { GroupedQuery } from '../types/grouped-query';\nimport type { SelectQuery } from '../types/select-query';\nimport {\n BuilderBase,\n type BuilderContext,\n type BuilderState,\n buildPlan,\n buildSelectAst,\n cloneState,\n orderByScopeOf,\n resolveDistinctOn,\n resolveGroupBy,\n resolveOrderBy,\n resolveSelectArgs,\n} from './builder-base';\nimport { createFieldProxy } from './field-proxy';\nimport { createAggregateFunctions, createFunctions } from './functions';\n\nabstract class QueryBase<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n> extends BuilderBase<QC['capabilities']> {\n protected readonly state: BuilderState;\n\n constructor(state: BuilderState, ctx: BuilderContext) {\n super(ctx);\n this.state = state;\n }\n\n protected abstract clone(state: BuilderState): this;\n\n distinctOn = this._gate(\n { postgres: { distinctOn: true } },\n 'distinctOn',\n (...args: unknown[]) => {\n const exprs = resolveDistinctOn(args, this.state.scope, this.state.rowFields, this.ctx);\n return this.clone(\n cloneState(this.state, {\n distinctOn: [...(this.state.distinctOn ?? []), ...exprs],\n }),\n );\n },\n );\n\n limit(count: number): this {\n return this.clone(cloneState(this.state, { limit: count }));\n }\n\n offset(count: number): this {\n return this.clone(cloneState(this.state, { offset: count }));\n }\n\n distinct(): this {\n return this.clone(cloneState(this.state, { distinct: true }));\n }\n\n groupBy(\n ...fields: ((keyof RowType | keyof AvailableScope['topLevel']) & string)[]\n ): GroupedQuery<QC, AvailableScope, RowType>;\n groupBy(\n expr: (\n fields: FieldProxy<OrderByScope<AvailableScope, RowType>>,\n fns: Functions<QC>,\n ) => Expression<ScopeField>,\n ): GroupedQuery<QC, AvailableScope, RowType>;\n groupBy(...args: unknown[]): unknown {\n const exprs = resolveGroupBy(args, this.state.scope, this.state.rowFields, this.ctx);\n return new GroupedQueryImpl<QC, AvailableScope, RowType>(\n cloneState(this.state, { groupBy: [...this.state.groupBy, ...exprs] }),\n this.ctx,\n );\n }\n\n as<Alias extends string>(alias: Alias): JoinSource<RowType, Alias> {\n const ast = buildSelectAst(this.state);\n const derivedSource = DerivedTableSource.as(alias, ast);\n const scope = {\n topLevel: this.state.rowFields as RowType,\n namespaces: { [alias]: this.state.rowFields } as Record<Alias, RowType>,\n };\n return {\n getJoinOuterScope: () => scope,\n buildAst: () => derivedSource,\n\n // `as unknown` is necessary, because JoinOuterScope is a phantom type-only property that does not exist at runtime\n } satisfies Omit<JoinSource<RowType, Alias>, typeof JoinOuterScope> as unknown as JoinSource<\n RowType,\n Alias\n >;\n }\n\n getRowFields(): Record<string, ScopeField> {\n return this.state.rowFields;\n }\n\n buildAst(): SelectAst {\n return buildSelectAst(this.state);\n }\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n return buildPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(\n this.state,\n this.ctx,\n );\n }\n}\n\nexport class SelectQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends QueryBase<QC, AvailableScope, RowType>\n implements SelectQuery<QC, AvailableScope, RowType>\n{\n declare readonly [SubqueryMarker]: RowType;\n\n protected clone(state: BuilderState): this {\n return new SelectQueryImpl<QC, AvailableScope, RowType>(state, this.ctx) as this;\n }\n\n select<Columns extends (keyof AvailableScope['topLevel'] & string)[]>(\n ...columns: Columns\n ): SelectQuery<QC, AvailableScope, WithFields<RowType, AvailableScope['topLevel'], Columns>>;\n select<Alias extends string, Field extends ScopeField>(\n alias: Alias,\n expr: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Expression<Field>,\n ): SelectQuery<QC, AvailableScope, WithField<RowType, Field, Alias>>;\n select<Result extends Record<string, Expression<ScopeField>>>(\n callback: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Result,\n ): SelectQuery<QC, AvailableScope, Expand<RowType & ExtractScopeFields<Result>>>;\n select(...args: unknown[]): unknown {\n const { projections, newRowFields } = resolveSelectArgs(args, this.state.scope, this.ctx);\n return new SelectQueryImpl(\n cloneState(this.state, {\n projections: [...this.state.projections, ...projections],\n rowFields: { ...this.state.rowFields, ...newRowFields },\n }),\n this.ctx,\n );\n }\n\n where(expr: ExpressionBuilder<AvailableScope, QC>): SelectQuery<QC, AvailableScope, RowType> {\n const fieldProxy = createFieldProxy(this.state.scope);\n const fns = createFunctions<QC>(this.ctx.queryOperationTypes);\n const result = (expr as ExpressionBuilder<Scope, QueryContext>)(fieldProxy, fns as never);\n return new SelectQueryImpl(\n cloneState(this.state, {\n where: [...this.state.where, result.buildAst()],\n }),\n this.ctx,\n );\n }\n\n orderBy(\n field: (keyof RowType | keyof AvailableScope['topLevel']) & string,\n options?: OrderByOptions,\n ): SelectQuery<QC, AvailableScope, RowType>;\n orderBy(\n expr: (\n fields: FieldProxy<OrderByScope<AvailableScope, RowType>>,\n fns: Functions<QC>,\n ) => Expression<ScopeField>,\n options?: OrderByOptions,\n ): SelectQuery<QC, AvailableScope, RowType>;\n orderBy(arg: unknown, options?: OrderByOptions): unknown {\n const item = resolveOrderBy(\n arg,\n options,\n this.state.scope,\n this.state.rowFields,\n this.ctx,\n false,\n );\n return this.clone(cloneState(this.state, { orderBy: [...this.state.orderBy, item] }));\n }\n}\n\nexport class GroupedQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends QueryBase<QC, AvailableScope, RowType>\n implements GroupedQuery<QC, AvailableScope, RowType>\n{\n declare readonly [SubqueryMarker]: RowType;\n\n protected clone(state: BuilderState): this {\n return new GroupedQueryImpl<QC, AvailableScope, RowType>(state, this.ctx) as this;\n }\n\n having(\n expr: (\n fields: FieldProxy<OrderByScope<AvailableScope, RowType>>,\n fns: AggregateFunctions<QC>,\n ) => Expression<BooleanCodecType>,\n ): GroupedQuery<QC, AvailableScope, RowType> {\n const combined = orderByScopeOf(\n this.state.scope as AvailableScope,\n this.state.rowFields as RowType,\n );\n const fns = createAggregateFunctions(this.ctx.queryOperationTypes);\n const result = expr(createFieldProxy(combined), fns);\n return new GroupedQueryImpl(cloneState(this.state, { having: result.buildAst() }), this.ctx);\n }\n\n orderBy(\n field: (keyof RowType | keyof AvailableScope['topLevel']) & string,\n options?: OrderByOptions,\n ): GroupedQuery<QC, AvailableScope, RowType>;\n orderBy(\n expr: (\n fields: FieldProxy<OrderByScope<AvailableScope, RowType>>,\n fns: AggregateFunctions<QC>,\n ) => Expression<ScopeField>,\n options?: OrderByOptions,\n ): GroupedQuery<QC, AvailableScope, RowType>;\n orderBy(arg: unknown, options?: OrderByOptions): unknown {\n const item = resolveOrderBy(\n arg,\n options,\n this.state.scope,\n this.state.rowFields,\n this.ctx,\n true,\n );\n return this.clone(cloneState(this.state, { orderBy: [...this.state.orderBy, item] }));\n }\n}\n","import {\n AndExpr,\n DerivedTableSource,\n JoinAst,\n type TableSource,\n} from '@prisma-next/sql-relational-core/ast';\nimport type {\n AggregateFunctions,\n Expression,\n ExpressionBuilder,\n ExtractScopeFields,\n FieldProxy,\n WithField,\n WithFields,\n} from '../expression';\nimport type {\n EmptyRow,\n Expand,\n JoinOuterScope,\n JoinSource,\n MergeScopes,\n NullableScope,\n QueryContext,\n Scope,\n ScopeField,\n ScopeTable,\n Subquery,\n} from '../scope';\nimport type { JoinedTables } from '../types/joined-tables';\nimport type { SelectQuery } from '../types/select-query';\nimport type { LateralBuilder } from '../types/shared';\nimport {\n BuilderBase,\n type BuilderContext,\n type BuilderState,\n cloneState,\n emptyState,\n mergeScopes,\n nullableScope,\n resolveSelectArgs,\n} from './builder-base';\nimport { createFieldProxy } from './field-proxy';\nimport { createFunctions } from './functions';\nimport { SelectQueryImpl } from './query-impl';\n\nexport class JoinedTablesImpl<QC extends QueryContext, AvailableScope extends Scope>\n extends BuilderBase<QC['capabilities']>\n implements JoinedTables<QC, AvailableScope>\n{\n readonly #state: BuilderState;\n\n constructor(state: BuilderState, ctx: BuilderContext) {\n super(ctx);\n this.#state = state;\n }\n\n lateralJoin = this._gate(\n { sql: { lateral: true } },\n 'lateralJoin',\n <Alias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: Alias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<AvailableScope, { topLevel: LateralRow; namespaces: Record<Alias, LateralRow> }>\n > => {\n const { derivedSource, lateralScope } = this.#buildLateral(alias, builder);\n const resultScope = mergeScopes(\n this.#state.scope as AvailableScope,\n lateralScope as { topLevel: LateralRow; namespaces: Record<Alias, LateralRow> },\n );\n return this.#addLateralJoin('inner', resultScope, derivedSource);\n },\n ) as JoinedTables<QC, AvailableScope>['lateralJoin'];\n\n outerLateralJoin = this._gate(\n { sql: { lateral: true } },\n 'outerLateralJoin',\n <Alias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: Alias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<\n AvailableScope,\n NullableScope<{ topLevel: LateralRow; namespaces: Record<Alias, LateralRow> }>\n >\n > => {\n const { derivedSource, lateralScope } = this.#buildLateral(alias, builder);\n const resultScope = mergeScopes(\n this.#state.scope as AvailableScope,\n nullableScope(\n lateralScope as { topLevel: LateralRow; namespaces: Record<Alias, LateralRow> },\n ),\n );\n return this.#addLateralJoin('left', resultScope, derivedSource);\n },\n ) as JoinedTables<QC, AvailableScope>['outerLateralJoin'];\n\n select<Columns extends (keyof AvailableScope['topLevel'] & string)[]>(\n ...columns: Columns\n ): SelectQuery<QC, AvailableScope, WithFields<EmptyRow, AvailableScope['topLevel'], Columns>>;\n select<Alias extends string, Field extends ScopeField>(\n alias: Alias,\n expr: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Expression<Field>,\n ): SelectQuery<QC, AvailableScope, WithField<EmptyRow, Field, Alias>>;\n select<Result extends Record<string, Expression<ScopeField>>>(\n callback: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Result,\n ): SelectQuery<QC, AvailableScope, Expand<ExtractScopeFields<Result>>>;\n select(...args: unknown[]): unknown {\n const { projections, newRowFields } = resolveSelectArgs(args, this.#state.scope, this.ctx);\n return new SelectQueryImpl<QC, AvailableScope>(\n cloneState(this.#state, {\n projections: [...this.#state.projections, ...projections],\n rowFields: { ...this.#state.rowFields, ...newRowFields },\n }),\n this.ctx,\n );\n }\n\n innerJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>> {\n const targetScope = mergeScopes(\n this.#state.scope as AvailableScope,\n other.getJoinOuterScope() as Other[typeof JoinOuterScope],\n );\n return this.#addJoin(other, 'inner', targetScope, on);\n }\n\n outerLeftJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<AvailableScope, NullableScope<Other[typeof JoinOuterScope]>>> {\n const targetScope = mergeScopes(\n this.#state.scope as AvailableScope,\n nullableScope(other.getJoinOuterScope() as Other[typeof JoinOuterScope]),\n );\n return this.#addJoin(other, 'left', targetScope, on);\n }\n\n outerRightJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<NullableScope<AvailableScope>, Other[typeof JoinOuterScope]>> {\n const targetScope = mergeScopes(\n nullableScope(this.#state.scope as AvailableScope),\n other.getJoinOuterScope() as Other[typeof JoinOuterScope],\n );\n return this.#addJoin(other, 'right', targetScope, on);\n }\n\n outerFullJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<\n QC,\n MergeScopes<NullableScope<AvailableScope>, NullableScope<Other[typeof JoinOuterScope]>>\n > {\n const targetScope = mergeScopes(\n nullableScope(this.#state.scope as AvailableScope),\n nullableScope(other.getJoinOuterScope() as Other[typeof JoinOuterScope]),\n );\n return this.#addJoin(other, 'full', targetScope, on);\n }\n\n #addJoin<Other extends JoinSource<ScopeTable, string | never>, ResultScope extends Scope>(\n other: Other,\n joinType: 'inner' | 'left' | 'right' | 'full',\n resultScope: ResultScope,\n onExpr: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, ResultScope> {\n const fieldProxy = createFieldProxy(\n mergeScopes(\n this.#state.scope as AvailableScope,\n other.getJoinOuterScope() as Other[typeof JoinOuterScope],\n ),\n ) as FieldProxy<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>>;\n const fns = createFunctions<QC>(this.ctx.queryOperationTypes);\n const onResult = onExpr(fieldProxy, fns);\n const joinAst = new JoinAst(joinType, other.buildAst(), onResult.buildAst());\n\n return new JoinedTablesImpl(\n cloneState(this.#state, {\n joins: [...this.#state.joins, joinAst],\n scope: resultScope,\n }),\n this.ctx,\n );\n }\n\n #buildLateral(\n alias: string,\n builderFn: (\n lateral: LateralBuilder<QC, AvailableScope>,\n ) => Subquery<Record<string, ScopeField>>,\n ) {\n const lateralBuilder: LateralBuilder<QC, AvailableScope> = {\n from: (other) => {\n const otherScope = other.getJoinOuterScope();\n const parentMerged = mergeScopes(this.#state.scope, otherScope);\n return new SelectQueryImpl(\n emptyState(other.buildAst() as TableSource, parentMerged),\n this.ctx,\n ) as unknown as SelectQuery<QC, AvailableScope, EmptyRow>;\n },\n };\n\n const subquery = builderFn(lateralBuilder);\n const subqueryAst = subquery.buildAst();\n const derivedSource = DerivedTableSource.as(alias, subqueryAst);\n const subqueryRowFields: ScopeTable = subquery.getRowFields();\n const lateralScope: Scope = {\n topLevel: subqueryRowFields,\n namespaces: { [alias]: subqueryRowFields },\n };\n\n return { derivedSource, lateralScope };\n }\n\n #addLateralJoin<ResultScope extends Scope>(\n joinType: 'inner' | 'left',\n resultScope: ResultScope,\n derivedSource: DerivedTableSource,\n ): JoinedTables<QC, ResultScope> {\n const onExpr = AndExpr.of([]);\n const joinAst = new JoinAst(joinType, derivedSource, onExpr, true);\n\n return new JoinedTablesImpl(\n cloneState(this.#state, {\n joins: [...this.#state.joins, joinAst],\n scope: resultScope,\n }),\n this.ctx,\n );\n }\n}\n","import type { StorageTable } from '@prisma-next/sql-contract/types';\nimport {\n type AnyExpression as AstExpression,\n ColumnRef,\n DeleteAst,\n InsertAst,\n ParamRef,\n TableSource,\n UpdateAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type { MutationDefaultsOp } from '@prisma-next/sql-relational-core/query-lane-context';\nimport type { ExpressionBuilder } from '../expression';\nimport type { ResolveRow } from '../resolve';\nimport type { QueryContext, Scope, ScopeField } from '../scope';\nimport type {\n DeleteQuery,\n InsertQuery,\n ReturningCapability,\n UpdateQuery,\n} from '../types/mutation-query';\nimport {\n BuilderBase,\n type BuilderContext,\n buildQueryPlan,\n combineWhereExprs,\n} from './builder-base';\nimport { createFieldProxy } from './field-proxy';\nimport { createFunctions } from './functions';\n\ntype WhereCallback = ExpressionBuilder<Scope, QueryContext>;\n\nfunction buildParamValues(\n values: Record<string, unknown>,\n table: StorageTable,\n tableName: string,\n op: MutationDefaultsOp,\n ctx: BuilderContext,\n): Record<string, ParamRef> {\n const params: Record<string, ParamRef> = {};\n for (const [col, value] of Object.entries(values)) {\n const column = table.columns[col];\n params[col] = ParamRef.of(value, column ? { codecId: column.codecId } : undefined);\n }\n for (const def of ctx.applyMutationDefaults({ op, table: tableName, values })) {\n const column = table.columns[def.column];\n params[def.column] = ParamRef.of(def.value, column ? { codecId: column.codecId } : undefined);\n }\n return params;\n}\n\nfunction buildReturningColumnRefs(tableName: string, columns: string[]): ColumnRef[] {\n return columns.map((col) => ColumnRef.of(tableName, col));\n}\n\nfunction evaluateWhere(\n whereCallback: WhereCallback,\n scope: Scope,\n queryOperationTypes: BuilderContext['queryOperationTypes'],\n): AstExpression {\n const fieldProxy = createFieldProxy(scope);\n const fns = createFunctions(queryOperationTypes);\n const result = whereCallback(fieldProxy, fns as never);\n return result.buildAst();\n}\n\nexport class InsertQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends BuilderBase<QC['capabilities']>\n implements InsertQuery<QC, AvailableScope, RowType>\n{\n readonly #tableName: string;\n readonly #table: StorageTable;\n readonly #scope: Scope;\n readonly #values: Record<string, unknown>;\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n\n constructor(\n tableName: string,\n table: StorageTable,\n scope: Scope,\n values: Record<string, unknown>,\n ctx: BuilderContext,\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n ) {\n super(ctx);\n this.#tableName = tableName;\n this.#table = table;\n this.#scope = scope;\n this.#values = values;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n }\n\n returning = this._gate<ReturningCapability, string[], InsertQuery<QC, AvailableScope, never>>(\n { sql: { returning: true } },\n 'returning',\n (...columns: string[]) => {\n const newRowFields: Record<string, ScopeField> = {};\n for (const col of columns) {\n const field = this.#scope.topLevel[col];\n if (!field) throw new Error(`Column \"${col}\" not found in scope`);\n newRowFields[col] = field;\n }\n return new InsertQueryImpl(\n this.#tableName,\n this.#table,\n this.#scope,\n this.#values,\n this.ctx,\n columns,\n newRowFields,\n ) as unknown as InsertQuery<QC, AvailableScope, never>;\n },\n );\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n const paramValues = buildParamValues(\n this.#values,\n this.#table,\n this.#tableName,\n 'create',\n this.ctx,\n );\n\n let ast = InsertAst.into(TableSource.named(this.#tableName)).withValues(paramValues);\n\n if (this.#returningColumns.length > 0) {\n ast = ast.withReturning(buildReturningColumnRefs(this.#tableName, this.#returningColumns));\n }\n\n return buildQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(\n ast,\n this.#rowFields,\n this.ctx,\n );\n }\n}\n\nexport class UpdateQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends BuilderBase<QC['capabilities']>\n implements UpdateQuery<QC, AvailableScope, RowType>\n{\n readonly #tableName: string;\n readonly #table: StorageTable;\n readonly #scope: Scope;\n readonly #setValues: Record<string, unknown>;\n readonly #whereCallbacks: readonly WhereCallback[];\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n\n constructor(\n tableName: string,\n table: StorageTable,\n scope: Scope,\n setValues: Record<string, unknown>,\n ctx: BuilderContext,\n whereCallbacks: readonly WhereCallback[] = [],\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n ) {\n super(ctx);\n this.#tableName = tableName;\n this.#table = table;\n this.#scope = scope;\n this.#setValues = setValues;\n this.#whereCallbacks = whereCallbacks;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n }\n\n where(expr: ExpressionBuilder<AvailableScope, QC>): UpdateQuery<QC, AvailableScope, RowType> {\n return new UpdateQueryImpl(\n this.#tableName,\n this.#table,\n this.#scope,\n this.#setValues,\n this.ctx,\n [...this.#whereCallbacks, expr as unknown as WhereCallback],\n this.#returningColumns,\n this.#rowFields,\n );\n }\n\n returning = this._gate<ReturningCapability, string[], UpdateQuery<QC, AvailableScope, never>>(\n { sql: { returning: true } },\n 'returning',\n (...columns: string[]) => {\n const newRowFields: Record<string, ScopeField> = {};\n for (const col of columns) {\n const field = this.#scope.topLevel[col];\n if (!field) throw new Error(`Column \"${col}\" not found in scope`);\n newRowFields[col] = field;\n }\n return new UpdateQueryImpl(\n this.#tableName,\n this.#table,\n this.#scope,\n this.#setValues,\n this.ctx,\n this.#whereCallbacks,\n columns,\n newRowFields,\n ) as unknown as UpdateQuery<QC, AvailableScope, never>;\n },\n );\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n const setParams = buildParamValues(\n this.#setValues,\n this.#table,\n this.#tableName,\n 'update',\n this.ctx,\n );\n\n const whereExpr = combineWhereExprs(\n this.#whereCallbacks.map((cb) =>\n evaluateWhere(cb, this.#scope, this.ctx.queryOperationTypes),\n ),\n );\n\n let ast = UpdateAst.table(TableSource.named(this.#tableName))\n .withSet(setParams)\n .withWhere(whereExpr);\n\n if (this.#returningColumns.length > 0) {\n ast = ast.withReturning(buildReturningColumnRefs(this.#tableName, this.#returningColumns));\n }\n\n return buildQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(\n ast,\n this.#rowFields,\n this.ctx,\n );\n }\n}\n\nexport class DeleteQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends BuilderBase<QC['capabilities']>\n implements DeleteQuery<QC, AvailableScope, RowType>\n{\n readonly #tableName: string;\n readonly #scope: Scope;\n readonly #whereCallbacks: readonly WhereCallback[];\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n\n constructor(\n tableName: string,\n scope: Scope,\n ctx: BuilderContext,\n whereCallbacks: readonly WhereCallback[] = [],\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n ) {\n super(ctx);\n this.#tableName = tableName;\n this.#scope = scope;\n this.#whereCallbacks = whereCallbacks;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n }\n\n where(expr: ExpressionBuilder<AvailableScope, QC>): DeleteQuery<QC, AvailableScope, RowType> {\n return new DeleteQueryImpl(\n this.#tableName,\n this.#scope,\n this.ctx,\n [...this.#whereCallbacks, expr as unknown as WhereCallback],\n this.#returningColumns,\n this.#rowFields,\n );\n }\n\n returning = this._gate<ReturningCapability, string[], DeleteQuery<QC, AvailableScope, never>>(\n { sql: { returning: true } },\n 'returning',\n (...columns: string[]) => {\n const newRowFields: Record<string, ScopeField> = {};\n for (const col of columns) {\n const field = this.#scope.topLevel[col];\n if (!field) throw new Error(`Column \"${col}\" not found in scope`);\n newRowFields[col] = field;\n }\n return new DeleteQueryImpl(\n this.#tableName,\n this.#scope,\n this.ctx,\n this.#whereCallbacks,\n columns,\n newRowFields,\n ) as unknown as DeleteQuery<QC, AvailableScope, never>;\n },\n );\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n const whereExpr = combineWhereExprs(\n this.#whereCallbacks.map((cb) =>\n evaluateWhere(cb, this.#scope, this.ctx.queryOperationTypes),\n ),\n );\n\n let ast = DeleteAst.from(TableSource.named(this.#tableName)).withWhere(whereExpr);\n\n if (this.#returningColumns.length > 0) {\n ast = ast.withReturning(buildReturningColumnRefs(this.#tableName, this.#returningColumns));\n }\n\n return buildQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(\n ast,\n this.#rowFields,\n this.ctx,\n );\n }\n}\n","import type { StorageTable } from '@prisma-next/sql-contract/types';\nimport { type AnyFromSource, TableSource } from '@prisma-next/sql-relational-core/ast';\nimport type {\n AggregateFunctions,\n Expression,\n ExpressionBuilder,\n ExtractScopeFields,\n FieldProxy,\n WithField,\n WithFields,\n} from '../expression';\nimport type {\n EmptyRow,\n Expand,\n JoinOuterScope,\n JoinSource,\n MergeScopes,\n NullableScope,\n QueryContext,\n RebindScope,\n Scope,\n ScopeField,\n ScopeTable,\n StorageTableToScopeTable,\n Subquery,\n} from '../scope';\nimport type { TableProxyContract } from '../types/db';\nimport type { JoinedTables } from '../types/joined-tables';\nimport type { DeleteQuery, InsertQuery, UpdateQuery } from '../types/mutation-query';\nimport type { SelectQuery } from '../types/select-query';\nimport type { LateralBuilder } from '../types/shared';\nimport type { TableProxy } from '../types/table-proxy';\nimport { BuilderBase, type BuilderContext, emptyState, tableToScope } from './builder-base';\nimport { JoinedTablesImpl } from './joined-tables-impl';\nimport { DeleteQueryImpl, InsertQueryImpl, UpdateQueryImpl } from './mutation-impl';\nimport { SelectQueryImpl } from './query-impl';\n\nexport class TableProxyImpl<\n C extends TableProxyContract,\n Name extends string & keyof C['storage']['tables'],\n Alias extends string,\n AvailableScope extends Scope,\n QC extends QueryContext,\n >\n extends BuilderBase<C['capabilities']>\n implements TableProxy<C, Name, Alias, AvailableScope, QC>\n{\n declare readonly [JoinOuterScope]: JoinSource<\n StorageTableToScopeTable<C['storage']['tables'][Name]>,\n Alias\n >[typeof JoinOuterScope];\n\n readonly #tableName: string;\n readonly #table: StorageTable;\n readonly #fromSource: TableSource;\n readonly #scope: Scope;\n\n constructor(tableName: string, table: StorageTable, alias: string, ctx: BuilderContext) {\n super(ctx);\n this.#tableName = tableName;\n this.#table = table;\n this.#scope = tableToScope(alias, table);\n this.#fromSource = TableSource.named(tableName, alias !== tableName ? alias : undefined);\n }\n\n lateralJoin = this._gate(\n { sql: { lateral: true } },\n 'lateralJoin',\n <LAlias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: LAlias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<AvailableScope, { topLevel: LateralRow; namespaces: Record<LAlias, LateralRow> }>\n > => {\n return this.#toJoined().lateralJoin(alias, builder);\n },\n ) as TableProxy<C, Name, Alias, AvailableScope, QC>['lateralJoin'];\n\n outerLateralJoin = this._gate(\n { sql: { lateral: true } },\n 'outerLateralJoin',\n <LAlias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: LAlias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<\n AvailableScope,\n NullableScope<{ topLevel: LateralRow; namespaces: Record<LAlias, LateralRow> }>\n >\n > => {\n return this.#toJoined().outerLateralJoin(alias, builder);\n },\n ) as TableProxy<C, Name, Alias, AvailableScope, QC>['outerLateralJoin'];\n\n getJoinOuterScope(): Scope {\n return this.#scope;\n }\n\n buildAst(): AnyFromSource {\n return this.#fromSource;\n }\n\n as<NewAlias extends string>(\n newAlias: NewAlias,\n ): TableProxy<C, Name, NewAlias, RebindScope<AvailableScope, Alias, NewAlias>> {\n return new TableProxyImpl(this.#tableName, this.#table, newAlias, this.ctx);\n }\n\n select<Columns extends (keyof AvailableScope['topLevel'] & string)[]>(\n ...columns: Columns\n ): SelectQuery<QC, AvailableScope, WithFields<EmptyRow, AvailableScope['topLevel'], Columns>>;\n select<LAlias extends string, Field extends ScopeField>(\n alias: LAlias,\n expr: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Expression<Field>,\n ): SelectQuery<QC, AvailableScope, WithField<EmptyRow, Field, LAlias>>;\n select<Result extends Record<string, Expression<ScopeField>>>(\n callback: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Result,\n ): SelectQuery<QC, AvailableScope, Expand<ExtractScopeFields<Result>>>;\n select(...args: unknown[]): unknown {\n return new SelectQueryImpl(emptyState(this.#fromSource, this.#scope), this.ctx).select(\n ...(args as string[]),\n );\n }\n\n innerJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>> {\n return this.#toJoined().innerJoin(other, on);\n }\n\n outerLeftJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<AvailableScope, NullableScope<Other[typeof JoinOuterScope]>>> {\n return this.#toJoined().outerLeftJoin(other, on);\n }\n\n outerRightJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<NullableScope<AvailableScope>, Other[typeof JoinOuterScope]>> {\n return this.#toJoined().outerRightJoin(other, on);\n }\n\n outerFullJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<\n QC,\n MergeScopes<NullableScope<AvailableScope>, NullableScope<Other[typeof JoinOuterScope]>>\n > {\n return this.#toJoined().outerFullJoin(other, on);\n }\n\n insert(values: Record<string, unknown>): InsertQuery<QC, AvailableScope, EmptyRow> {\n return new InsertQueryImpl(this.#tableName, this.#table, this.#scope, values, this.ctx);\n }\n\n update(set: Record<string, unknown>): UpdateQuery<QC, AvailableScope, EmptyRow> {\n return new UpdateQueryImpl(this.#tableName, this.#table, this.#scope, set, this.ctx);\n }\n\n delete(): DeleteQuery<QC, AvailableScope, EmptyRow> {\n return new DeleteQueryImpl(this.#tableName, this.#scope, this.ctx);\n }\n\n #toJoined(): JoinedTables<QC, AvailableScope> {\n return new JoinedTablesImpl(emptyState(this.#fromSource, this.#scope), this.ctx);\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { ExecutionContext } from '@prisma-next/sql-relational-core/query-lane-context';\nimport type { Db } from '../types/db';\nimport type { BuilderContext } from './builder-base';\nimport { TableProxyImpl } from './table-proxy-impl';\n\nexport interface SqlOptions<C extends Contract<SqlStorage>> {\n readonly context: ExecutionContext<C>;\n}\n\nexport function sql<C extends Contract<SqlStorage>>(options: SqlOptions<C>): Db<C> {\n const { context } = options;\n const ctx: BuilderContext = {\n capabilities: context.contract.capabilities,\n queryOperationTypes: context.queryOperations.entries(),\n target: context.contract.target ?? 'unknown',\n storageHash: context.contract.storage.storageHash ?? 'unknown',\n applyMutationDefaults: (options) => context.applyMutationDefaults(options),\n };\n\n return new Proxy({} as Db<C>, {\n get(_target, prop: string) {\n const tables = context.contract.storage.tables;\n const table = Object.hasOwn(tables, prop) ? tables[prop] : undefined;\n if (table) {\n return new TableProxyImpl(prop, table, pr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K,GAAG,OAAO,QAAQ;AAC3D,MAAI,MACF,QAAO,IAAI,eAAe,MAAM,OAAO,MAAM,IAAI;IAItD,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["findUniqueNamespaceFor","#state","#buildLateral","#addLateralJoin","#addJoin","#tableName","#table","#scope","#values","#returningColumns","#rowFields","#setValues","#whereCallbacks","#tableName","#table","#fromSource","#scope","#toJoined"],"sources":["../../src/runtime/expression-impl.ts","../../src/runtime/field-proxy.ts","../../src/runtime/functions.ts","../../src/runtime/builder-base.ts","../../src/runtime/query-impl.ts","../../src/runtime/joined-tables-impl.ts","../../src/runtime/mutation-impl.ts","../../src/runtime/table-proxy-impl.ts","../../src/runtime/sql.ts"],"sourcesContent":["import type { AnyExpression as AstExpression } from '@prisma-next/sql-relational-core/ast';\nimport type { Expression } from '@prisma-next/sql-relational-core/expression';\nimport type { ScopeField } from '../scope';\n\n/**\n * Runtime wrapper around a relational-core AST expression node. Carries ScopeField metadata (codecId, nullable) so aggregate-like combinators can propagate the input codec onto their result.\n *\n * `refs` records the column-bound binding (`{ table, column }`) when known — the field-proxy populates it for both the namespaced form (`f.user.email` → `ColumnRef`) and the top-level shortcut (`f.email` → `IdentifierRef` + refs metadata). Encode-side dispatch and the `validateParamRefRefs` pass read it via `refsOf(expression)`.\n */\nexport class ExpressionImpl<T extends ScopeField = ScopeField> implements Expression<T> {\n private readonly ast: AstExpression;\n readonly returnType: T;\n readonly refs: { readonly table: string; readonly column: string } | undefined;\n\n constructor(\n ast: AstExpression,\n returnType: T,\n refs?: { readonly table: string; readonly column: string },\n ) {\n this.ast = ast;\n this.returnType = returnType;\n this.refs = refs;\n }\n\n buildAst(): AstExpression {\n return this.ast;\n }\n}\n","import { ColumnRef, IdentifierRef } from '@prisma-next/sql-relational-core/ast';\nimport type { FieldProxy } from '../expression';\nimport type { Scope, ScopeTable } from '../scope';\nimport { ExpressionImpl } from './expression-impl';\n\n/**\n * For a top-level field name, find the namespace (table alias) that contributed it. When exactly one namespace owns the field, the top-level binding is unambiguously column-bound and we record that `(table, column)` pair on the `ExpressionImpl` so encode-side dispatch (`forColumn`) and the `validateParamRefRefs` pass can find it. The AST stays as `IdentifierRef` to preserve SQL rendering — adapters render top-level\n * identifiers without an explicit table qualifier — so this change is metadata-only and produces no SQL drift.\n */\nfunction findUniqueNamespaceFor(scope: Scope, fieldName: string): string | undefined {\n let found: string | undefined;\n for (const [namespace, fields] of Object.entries(scope.namespaces)) {\n if (Object.hasOwn(fields, fieldName)) {\n if (found !== undefined) return undefined;\n found = namespace;\n }\n }\n return found;\n}\n\nexport function createFieldProxy<S extends Scope>(scope: S): FieldProxy<S> {\n return new Proxy({} as FieldProxy<S>, {\n get(_target, prop: string) {\n if (Object.hasOwn(scope.topLevel, prop)) {\n const topField = scope.topLevel[prop];\n if (topField) {\n const namespace = findUniqueNamespaceFor(scope, prop);\n const refs = namespace ? { table: namespace, column: prop } : undefined;\n return new ExpressionImpl(IdentifierRef.of(prop), topField, refs);\n }\n }\n\n if (Object.hasOwn(scope.namespaces, prop)) {\n const nsFields = scope.namespaces[prop];\n if (nsFields) return createNamespaceProxy(prop, nsFields);\n }\n\n return undefined;\n },\n });\n}\n\nfunction createNamespaceProxy(\n namespaceName: string,\n fields: ScopeTable,\n): Record<string, ExpressionImpl> {\n return new Proxy({} as Record<string, ExpressionImpl>, {\n get(_target, prop: string) {\n if (Object.hasOwn(fields, prop)) {\n const field = fields[prop];\n if (field) return new ExpressionImpl(ColumnRef.of(namespaceName, prop), field);\n }\n return undefined;\n },\n });\n}\n","import type { SqlOperationEntry } from '@prisma-next/sql-operations';\nimport {\n AggregateExpr,\n AndExpr,\n type AnyExpression as AstExpression,\n BinaryExpr,\n type BinaryOp,\n ExistsExpr,\n ListExpression,\n LiteralExpr,\n NullCheckExpr,\n OrExpr,\n SubqueryExpr,\n} from '@prisma-next/sql-relational-core/ast';\nimport { refsOf, toExpr } from '@prisma-next/sql-relational-core/expression';\nimport type {\n AggregateFunctions,\n AggregateOnlyFunctions,\n BooleanCodecType,\n BuiltinFunctions,\n CodecExpression,\n Expression,\n Functions,\n} from '../expression';\nimport type { QueryContext, ScopeField, Subquery } from '../scope';\nimport { ExpressionImpl } from './expression-impl';\n\ntype CodecTypes = Record<string, { readonly input: unknown }>;\n// Runtime-level ExprOrVal — accepts any codec, any nullability. Concrete codec typing lives on the public BuiltinFunctions surface in `../expression`.\ntype ExprOrVal<CodecId extends string = string, N extends boolean = boolean> = CodecExpression<\n CodecId,\n N,\n CodecTypes\n>;\n\nconst BOOL_FIELD: BooleanCodecType = { codecId: 'pg/bool@1', nullable: false };\n\nconst resolve = toExpr;\n\n/**\n * Resolve a binary-comparison operand into an AST expression, threading the column-bound side's `codecId` + `refs` to the raw-value side.\n *\n * For `fns.eq(f.email, 'alice@example.com')`, `f.email` is the column-bound expression carrying a `ColumnRef` AST and a `returnType.codecId` (`pg/varchar@1`); the raw string operand has no codec context. By deriving the codec context from the column-bound side and forwarding it via `toExpr(value, codecId, refs)`, the resulting `ParamRef` carries the column refs that encode-side `forColumn` dispatch needs (and that the\n * validator pass requires for parameterized codec ids like `pg/varchar@1` with a length parameter).\n */\nfunction resolveOperand(\n operand: ExprOrVal,\n otherCodecId?: string,\n otherRefs?: { table: string; column: string },\n): AstExpression {\n if (isExpressionLike(operand)) return operand.buildAst();\n return toExpr(operand, otherCodecId, otherRefs);\n}\n\nfunction isExpressionLike(\n value: unknown,\n): value is { buildAst: () => AstExpression; returnType?: { codecId: string } } {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'buildAst' in value &&\n typeof (value as { buildAst: unknown }).buildAst === 'function'\n );\n}\n\nfunction operandCodecId(operand: ExprOrVal): string | undefined {\n if (!isExpressionLike(operand)) return undefined;\n return (operand as { returnType?: { codecId: string } }).returnType?.codecId;\n}\n\nfunction operandRefs(operand: ExprOrVal): { table: string; column: string } | undefined {\n return refsOf(operand);\n}\n\n/**\n * Resolves an Expression via `buildAst()`, or wraps a raw value as a `LiteralExpr` — an SQL literal inlined into the query text, not a bound parameter.\n *\n * Used for `and` / `or` operands. The usual operand is an `Expression<bool>` (e.g. the result of `fns.eq`), which this function passes through by calling `buildAst()`. The only time the raw-value branch fires is when the caller writes `fns.and(true, x)` or similar — inlining `TRUE`/`FALSE` literals lets the SQL planner statically simplify `TRUE AND x` to `x`, which it cannot do for an opaque `ParamRef`.\n */\nfunction toLiteralExpr(value: unknown): AstExpression {\n if (\n typeof value === 'object' &&\n value !== null &&\n 'buildAst' in value &&\n typeof (value as { buildAst: unknown }).buildAst === 'function'\n ) {\n return (value as { buildAst(): AstExpression }).buildAst();\n }\n return new LiteralExpr(value);\n}\n\nfunction boolExpr(astNode: AstExpression): ExpressionImpl<BooleanCodecType> {\n return new ExpressionImpl(astNode, BOOL_FIELD);\n}\n\nfunction binaryWithSharedCodec(\n a: ExprOrVal,\n b: ExprOrVal,\n build: (left: AstExpression, right: AstExpression) => AstExpression,\n): AstExpression {\n const aCodecId = operandCodecId(a);\n const bCodecId = operandCodecId(b);\n const aRefs = operandRefs(a);\n const bRefs = operandRefs(b);\n const left = resolveOperand(a, bCodecId, bRefs);\n const right = resolveOperand(b, aCodecId, aRefs);\n return build(left, right);\n}\n\nfunction eq(a: ExprOrVal, b: ExprOrVal): ExpressionImpl<BooleanCodecType> {\n if (b === null) return boolExpr(NullCheckExpr.isNull(resolve(a)));\n if (a === null) return boolExpr(NullCheckExpr.isNull(resolve(b)));\n return boolExpr(binaryWithSharedCodec(a, b, (l, r) => new BinaryExpr('eq', l, r)));\n}\n\nfunction ne(a: ExprOrVal, b: ExprOrVal): ExpressionImpl<BooleanCodecType> {\n if (b === null) return boolExpr(NullCheckExpr.isNotNull(resolve(a)));\n if (a === null) return boolExpr(NullCheckExpr.isNotNull(resolve(b)));\n return boolExpr(binaryWithSharedCodec(a, b, (l, r) => new BinaryExpr('neq', l, r)));\n}\n\nfunction comparison(a: ExprOrVal, b: ExprOrVal, op: BinaryOp): ExpressionImpl<BooleanCodecType> {\n return boolExpr(binaryWithSharedCodec(a, b, (l, r) => new BinaryExpr(op, l, r)));\n}\n\nfunction inOrNotIn(\n expr: Expression<ScopeField>,\n valuesOrSubquery: Subquery<Record<string, ScopeField>> | ExprOrVal[],\n op: 'in' | 'notIn',\n): ExpressionImpl<BooleanCodecType> {\n const left = expr.buildAst();\n const leftCodecId = expr.returnType.codecId;\n const leftRefs = refsOf(expr);\n const binaryFn = op === 'in' ? BinaryExpr.in : BinaryExpr.notIn;\n\n if (Array.isArray(valuesOrSubquery)) {\n const refs = valuesOrSubquery.map((v) => resolveOperand(v, leftCodecId, leftRefs));\n return boolExpr(binaryFn(left, ListExpression.of(refs)));\n }\n return boolExpr(binaryFn(left, SubqueryExpr.of(valuesOrSubquery.buildAst())));\n}\n\nfunction numericAgg(\n fn: 'sum' | 'avg' | 'min' | 'max',\n expr: Expression<ScopeField>,\n): ExpressionImpl<{ codecId: string; nullable: true }> {\n return new ExpressionImpl(AggregateExpr[fn](expr.buildAst()), {\n codecId: expr.returnType.codecId,\n nullable: true as const,\n });\n}\n\nfunction createBuiltinFunctions() {\n return {\n eq: (a: ExprOrVal, b: ExprOrVal) => eq(a, b),\n ne: (a: ExprOrVal, b: ExprOrVal) => ne(a, b),\n gt: (a: ExprOrVal, b: ExprOrVal) => comparison(a, b, 'gt'),\n gte: (a: ExprOrVal, b: ExprOrVal) => comparison(a, b, 'gte'),\n lt: (a: ExprOrVal, b: ExprOrVal) => comparison(a, b, 'lt'),\n lte: (a: ExprOrVal, b: ExprOrVal) => comparison(a, b, 'lte'),\n and: (...exprs: ExprOrVal<'pg/bool@1', boolean>[]) =>\n boolExpr(AndExpr.of(exprs.map(toLiteralExpr))),\n or: (...exprs: ExprOrVal<'pg/bool@1', boolean>[]) =>\n boolExpr(OrExpr.of(exprs.map(toLiteralExpr))),\n exists: (subquery: Subquery<Record<string, ScopeField>>) =>\n boolExpr(ExistsExpr.exists(subquery.buildAst())),\n notExists: (subquery: Subquery<Record<string, ScopeField>>) =>\n boolExpr(ExistsExpr.notExists(subquery.buildAst())),\n in: (\n expr: Expression<ScopeField>,\n valuesOrSubquery: Subquery<Record<string, ScopeField>> | ExprOrVal[],\n ) => inOrNotIn(expr, valuesOrSubquery, 'in'),\n notIn: (\n expr: Expression<ScopeField>,\n valuesOrSubquery: Subquery<Record<string, ScopeField>> | ExprOrVal[],\n ) => inOrNotIn(expr, valuesOrSubquery, 'notIn'),\n } satisfies BuiltinFunctions<CodecTypes>;\n}\n\nfunction createAggregateOnlyFunctions() {\n return {\n count: (expr?: Expression<ScopeField>) => {\n const astExpr = expr ? expr.buildAst() : undefined;\n return new ExpressionImpl(AggregateExpr.count(astExpr), {\n codecId: 'pg/int8@1',\n nullable: false,\n });\n },\n sum: (expr: Expression<ScopeField>) => numericAgg('sum', expr),\n avg: (expr: Expression<ScopeField>) => numericAgg('avg', expr),\n min: (expr: Expression<ScopeField>) => numericAgg('min', expr),\n max: (expr: Expression<ScopeField>) => numericAgg('max', expr),\n } satisfies AggregateOnlyFunctions;\n}\n\nexport function createFunctions<QC extends QueryContext>(\n operations: Readonly<Record<string, SqlOperationEntry>>,\n): Functions<QC> {\n const builtins = createBuiltinFunctions();\n\n return new Proxy({} as Functions<QC>, {\n get(_target, prop: string) {\n const builtin = (builtins as Record<string, unknown>)[prop];\n if (builtin) return builtin;\n\n const op = operations[prop];\n if (op) return op.impl;\n return undefined;\n },\n });\n}\n\nexport function createAggregateFunctions<QC extends QueryContext>(\n operations: Readonly<Record<string, SqlOperationEntry>>,\n): AggregateFunctions<QC> {\n const baseFns = createFunctions<QC>(operations);\n const aggregates = createAggregateOnlyFunctions();\n\n return new Proxy({} as AggregateFunctions<QC>, {\n get(_target, prop: string) {\n const agg = (aggregates as Record<string, unknown>)[prop];\n if (agg) return agg;\n\n return (baseFns as Record<string, unknown>)[prop];\n },\n });\n}\n","import type { PlanMeta } from '@prisma-next/contract/types';\nimport type { StorageTable } from '@prisma-next/sql-contract/types';\nimport type { SqlOperationEntry } from '@prisma-next/sql-operations';\nimport {\n AndExpr,\n type AnyExpression as AstExpression,\n collectOrderedParamRefs,\n IdentifierRef,\n OrderByItem,\n ProjectionItem,\n SelectAst,\n type TableSource,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type {\n AppliedMutationDefault,\n MutationDefaultsOptions,\n} from '@prisma-next/sql-relational-core/query-lane-context';\nimport type {\n AggregateFunctions,\n Expression,\n FieldProxy,\n OrderByOptions,\n OrderByScope,\n} from '../expression';\nimport type {\n GatedMethod,\n MergeScopes,\n NullableScope,\n QueryContext,\n Scope,\n ScopeField,\n ScopeTable,\n} from '../scope';\nimport { createFieldProxy } from './field-proxy';\nimport { createAggregateFunctions, createFunctions } from './functions';\n\nexport type ExprCallback = (fields: FieldProxy<Scope>, fns: unknown) => Expression<ScopeField>;\n\nexport class BuilderBase<Capabilities = unknown> {\n protected readonly ctx: BuilderContext;\n\n constructor(ctx: BuilderContext) {\n this.ctx = ctx;\n }\n\n protected _gate<Req extends Record<string, Record<string, boolean>>, Args extends unknown[], R>(\n required: Req,\n methodName: string,\n method: (...args: Args) => R,\n ): GatedMethod<Capabilities, Req, (...args: Args) => R> {\n return ((...args: Args): R => {\n assertCapability(this.ctx, required, methodName);\n return method(...args);\n }) as GatedMethod<Capabilities, Req, (...args: Args) => R>;\n }\n}\n\nexport interface BuilderState {\n readonly from: TableSource;\n readonly joins: readonly import('@prisma-next/sql-relational-core/ast').JoinAst[];\n readonly projections: readonly ProjectionItem[];\n readonly where: readonly AstExpression[];\n readonly orderBy: readonly OrderByItem[];\n readonly groupBy: readonly AstExpression[];\n readonly having: AstExpression | undefined;\n readonly limit: number | undefined;\n readonly offset: number | undefined;\n readonly distinct: true | undefined;\n readonly distinctOn: readonly AstExpression[] | undefined;\n readonly scope: Scope;\n readonly rowFields: Record<string, ScopeField>;\n}\n\nexport interface BuilderContext {\n readonly capabilities: Record<string, Record<string, boolean>>;\n readonly queryOperationTypes: Readonly<Record<string, SqlOperationEntry>>;\n readonly target: string;\n readonly storageHash: string;\n readonly applyMutationDefaults: (\n options: MutationDefaultsOptions,\n ) => ReadonlyArray<AppliedMutationDefault>;\n}\n\nexport function emptyState(from: TableSource, scope: Scope): BuilderState {\n return {\n from,\n joins: [],\n projections: [],\n where: [],\n orderBy: [],\n groupBy: [],\n having: undefined,\n limit: undefined,\n offset: undefined,\n distinct: undefined,\n distinctOn: undefined,\n scope,\n rowFields: {},\n };\n}\n\nexport function cloneState(state: BuilderState, overrides: Partial<BuilderState>): BuilderState {\n return { ...state, ...overrides };\n}\n\nexport function combineWhereExprs(exprs: readonly AstExpression[]): AstExpression | undefined {\n if (exprs.length === 0) return undefined;\n if (exprs.length === 1) return exprs[0];\n return AndExpr.of(exprs);\n}\n\n/**\n * Same uniqueness rule as the field-proxy's `findUniqueNamespaceFor`: when exactly one namespace owns a top-level field, the binding is unambiguous. Used by `select('col', ...)` to attach `refs` metadata to the resulting `ProjectionItem` while keeping the AST as `IdentifierRef` (so SQL renders unchanged).\n */\nfunction findUniqueNamespaceFor(scope: Scope, fieldName: string): string | undefined {\n let found: string | undefined;\n for (const [namespace, fields] of Object.entries(scope.namespaces)) {\n if (Object.hasOwn(fields, fieldName)) {\n if (found !== undefined) return undefined;\n found = namespace;\n }\n }\n return found;\n}\n\nexport function buildSelectAst(state: BuilderState): SelectAst {\n const where = combineWhereExprs(state.where);\n return new SelectAst({\n from: state.from,\n joins: state.joins.length > 0 ? state.joins : undefined,\n projection: state.projections,\n where,\n orderBy: state.orderBy.length > 0 ? state.orderBy : undefined,\n distinct: state.distinct,\n distinctOn: state.distinctOn && state.distinctOn.length > 0 ? state.distinctOn : undefined,\n groupBy: state.groupBy.length > 0 ? state.groupBy : undefined,\n having: state.having,\n limit: state.limit,\n offset: state.offset,\n selectAllIntent: undefined,\n });\n}\n\nexport function buildQueryPlan<Row = unknown>(\n ast: import('@prisma-next/sql-relational-core/ast').AnyQueryAst,\n ctx: BuilderContext,\n): SqlQueryPlan<Row> {\n const paramValues = collectOrderedParamRefs(ast).map((r) => r.value);\n\n const meta: PlanMeta = Object.freeze({\n target: ctx.target,\n storageHash: ctx.storageHash,\n lane: 'dsl',\n });\n\n return Object.freeze({ ast, params: paramValues, meta });\n}\n\nexport function buildPlan<Row = unknown>(\n state: BuilderState,\n ctx: BuilderContext,\n): SqlQueryPlan<Row> {\n return buildQueryPlan<Row>(buildSelectAst(state), ctx);\n}\n\nexport function tableToScope(name: string, table: StorageTable): Scope {\n const fields: ScopeTable = {};\n for (const [colName, col] of Object.entries(table.columns)) {\n fields[colName] = { codecId: col.codecId, nullable: col.nullable };\n }\n return { topLevel: { ...fields }, namespaces: { [name]: fields } };\n}\n\nexport function mergeScopes<A extends Scope, B extends Scope>(a: A, b: B): MergeScopes<A, B> {\n const topLevel: ScopeTable = {};\n for (const [k, v] of Object.entries(a.topLevel)) {\n if (!(k in b.topLevel)) topLevel[k] = v;\n }\n for (const [k, v] of Object.entries(b.topLevel)) {\n if (!(k in a.topLevel)) topLevel[k] = v;\n }\n return {\n topLevel,\n namespaces: { ...a.namespaces, ...b.namespaces },\n } as MergeScopes<A, B>;\n}\n\nexport function nullableScope<S extends Scope>(scope: S): NullableScope<S> {\n const mkNullable = (tbl: ScopeTable): ScopeTable => {\n const result: ScopeTable = {};\n for (const [k, v] of Object.entries(tbl)) {\n result[k] = { codecId: v.codecId, nullable: true };\n }\n return result;\n };\n const namespaces: Record<string, ScopeTable> = {};\n for (const [k, v] of Object.entries(scope.namespaces)) {\n namespaces[k] = mkNullable(v);\n }\n return { topLevel: mkNullable(scope.topLevel), namespaces } as NullableScope<S>;\n}\n\nexport function orderByScopeOf<S extends Scope, R extends Record<string, ScopeField>>(\n scope: S,\n rowFields: R,\n): OrderByScope<S, R> {\n return {\n topLevel: { ...scope.topLevel, ...rowFields },\n namespaces: scope.namespaces,\n };\n}\n\nexport function assertCapability(\n ctx: BuilderContext,\n required: Record<string, Record<string, boolean>>,\n methodName: string,\n): void {\n for (const [ns, keys] of Object.entries(required)) {\n for (const key of Object.keys(keys)) {\n if (!ctx.capabilities[ns]?.[key]) {\n throw new Error(`${methodName}() requires capability ${ns}.${key}`);\n }\n }\n }\n}\n\nexport function resolveSelectArgs(\n args: unknown[],\n scope: Scope,\n ctx: BuilderContext,\n): { projections: ProjectionItem[]; newRowFields: Record<string, ScopeField> } {\n const projections: ProjectionItem[] = [];\n const newRowFields: Record<string, ScopeField> = {};\n\n if (args.length === 0) return { projections, newRowFields };\n\n if (typeof args[0] === 'string' && (args.length === 1 || typeof args[1] !== 'function')) {\n for (const colName of args as string[]) {\n const field = scope.topLevel[colName];\n if (!field) throw new Error(`Column \"${colName}\" not found in scope`);\n const namespace = findUniqueNamespaceFor(scope, colName);\n const refs = namespace ? { table: namespace, column: colName } : undefined;\n projections.push(ProjectionItem.of(colName, IdentifierRef.of(colName), field.codecId, refs));\n newRowFields[colName] = field;\n }\n return { projections, newRowFields };\n }\n\n if (typeof args[0] === 'string' && typeof args[1] === 'function') {\n const alias = args[0] as string;\n const exprFn = args[1] as (\n f: FieldProxy<Scope>,\n fns: AggregateFunctions<QueryContext>,\n ) => Expression<ScopeField>;\n const fns = createAggregateFunctions(ctx.queryOperationTypes);\n const result = exprFn(createFieldProxy(scope), fns);\n const field = result.returnType;\n projections.push(ProjectionItem.of(alias, result.buildAst(), field.codecId));\n newRowFields[alias] = field;\n return { projections, newRowFields };\n }\n\n if (typeof args[0] === 'function') {\n const callbackFn = args[0] as (\n f: FieldProxy<Scope>,\n fns: AggregateFunctions<QueryContext>,\n ) => Record<string, Expression<ScopeField>>;\n const fns = createAggregateFunctions(ctx.queryOperationTypes);\n const record = callbackFn(createFieldProxy(scope), fns);\n for (const [key, expr] of Object.entries(record)) {\n const field = expr.returnType;\n projections.push(ProjectionItem.of(key, expr.buildAst(), field.codecId));\n newRowFields[key] = field;\n }\n return { projections, newRowFields };\n }\n\n throw new Error('Invalid .select() arguments');\n}\n\nexport function resolveOrderBy(\n arg: unknown,\n options: OrderByOptions | undefined,\n scope: Scope,\n rowFields: Record<string, ScopeField>,\n ctx: BuilderContext,\n useAggregateFns: boolean,\n): OrderByItem {\n const dir = options?.direction ?? 'asc';\n\n if (typeof arg === 'string') {\n const combined = orderByScopeOf(scope, rowFields);\n if (!(arg in combined.topLevel))\n throw new Error(`Column \"${arg}\" not found in scope for orderBy`);\n const expr = IdentifierRef.of(arg);\n return dir === 'asc' ? OrderByItem.asc(expr) : OrderByItem.desc(expr);\n }\n\n if (typeof arg === 'function') {\n const combined = orderByScopeOf(scope, rowFields);\n const fns = useAggregateFns\n ? createAggregateFunctions(ctx.queryOperationTypes)\n : createFunctions(ctx.queryOperationTypes);\n const result = (arg as ExprCallback)(createFieldProxy(combined), fns);\n return dir === 'asc' ? OrderByItem.asc(result.buildAst()) : OrderByItem.desc(result.buildAst());\n }\n\n throw new Error('Invalid orderBy argument');\n}\n\nexport function resolveGroupBy(\n args: unknown[],\n scope: Scope,\n rowFields: Record<string, ScopeField>,\n ctx: BuilderContext,\n): AstExpression[] {\n if (typeof args[0] === 'string') {\n const combined = orderByScopeOf(scope, rowFields);\n return (args as string[]).map((colName) => {\n if (!(colName in combined.topLevel))\n throw new Error(`Column \"${colName}\" not found in scope for groupBy`);\n return IdentifierRef.of(colName);\n });\n }\n\n if (typeof args[0] === 'function') {\n const combined = orderByScopeOf(scope, rowFields);\n const fns = createFunctions(ctx.queryOperationTypes);\n const result = (args[0] as ExprCallback)(createFieldProxy(combined), fns);\n return [result.buildAst()];\n }\n\n throw new Error('Invalid groupBy arguments');\n}\n\nexport function resolveDistinctOn(\n args: unknown[],\n scope: Scope,\n rowFields: Record<string, ScopeField>,\n ctx: BuilderContext,\n): AstExpression[] {\n if (args.length === 1 && typeof args[0] === 'function') {\n const combined = orderByScopeOf(scope, rowFields);\n const fns = createFunctions(ctx.queryOperationTypes);\n const result = (args[0] as ExprCallback)(createFieldProxy(combined), fns);\n return [result.buildAst()];\n }\n const combined = orderByScopeOf(scope, rowFields);\n return (args as string[]).map((colName) => {\n if (!(colName in combined.topLevel))\n throw new Error(`Column \"${colName}\" not found in scope for distinctOn`);\n return IdentifierRef.of(colName);\n });\n}\n","import { DerivedTableSource, type SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type {\n AggregateFunctions,\n BooleanCodecType,\n Expression,\n ExpressionBuilder,\n ExtractScopeFields,\n FieldProxy,\n Functions,\n OrderByOptions,\n OrderByScope,\n WithField,\n WithFields,\n} from '../expression';\nimport type { ResolveRow } from '../resolve';\nimport type {\n Expand,\n JoinOuterScope,\n JoinSource,\n QueryContext,\n Scope,\n ScopeField,\n // biome-ignore lint/correctness/noUnusedImports: used in `declare` property\n SubqueryMarker,\n} from '../scope';\nimport type { GroupedQuery } from '../types/grouped-query';\nimport type { SelectQuery } from '../types/select-query';\nimport {\n BuilderBase,\n type BuilderContext,\n type BuilderState,\n buildPlan,\n buildSelectAst,\n cloneState,\n orderByScopeOf,\n resolveDistinctOn,\n resolveGroupBy,\n resolveOrderBy,\n resolveSelectArgs,\n} from './builder-base';\nimport { createFieldProxy } from './field-proxy';\nimport { createAggregateFunctions, createFunctions } from './functions';\n\nabstract class QueryBase<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n> extends BuilderBase<QC['capabilities']> {\n protected readonly state: BuilderState;\n\n constructor(state: BuilderState, ctx: BuilderContext) {\n super(ctx);\n this.state = state;\n }\n\n protected abstract clone(state: BuilderState): this;\n\n distinctOn = this._gate(\n { postgres: { distinctOn: true } },\n 'distinctOn',\n (...args: unknown[]) => {\n const exprs = resolveDistinctOn(args, this.state.scope, this.state.rowFields, this.ctx);\n return this.clone(\n cloneState(this.state, {\n distinctOn: [...(this.state.distinctOn ?? []), ...exprs],\n }),\n );\n },\n );\n\n limit(count: number): this {\n return this.clone(cloneState(this.state, { limit: count }));\n }\n\n offset(count: number): this {\n return this.clone(cloneState(this.state, { offset: count }));\n }\n\n distinct(): this {\n return this.clone(cloneState(this.state, { distinct: true }));\n }\n\n groupBy(\n ...fields: ((keyof RowType | keyof AvailableScope['topLevel']) & string)[]\n ): GroupedQuery<QC, AvailableScope, RowType>;\n groupBy(\n expr: (\n fields: FieldProxy<OrderByScope<AvailableScope, RowType>>,\n fns: Functions<QC>,\n ) => Expression<ScopeField>,\n ): GroupedQuery<QC, AvailableScope, RowType>;\n groupBy(...args: unknown[]): unknown {\n const exprs = resolveGroupBy(args, this.state.scope, this.state.rowFields, this.ctx);\n return new GroupedQueryImpl<QC, AvailableScope, RowType>(\n cloneState(this.state, { groupBy: [...this.state.groupBy, ...exprs] }),\n this.ctx,\n );\n }\n\n as<Alias extends string>(alias: Alias): JoinSource<RowType, Alias> {\n const ast = buildSelectAst(this.state);\n const derivedSource = DerivedTableSource.as(alias, ast);\n const scope = {\n topLevel: this.state.rowFields as RowType,\n namespaces: { [alias]: this.state.rowFields } as Record<Alias, RowType>,\n };\n return {\n getJoinOuterScope: () => scope,\n buildAst: () => derivedSource,\n\n // `as unknown` is necessary, because JoinOuterScope is a phantom type-only property that does not exist at runtime\n } satisfies Omit<JoinSource<RowType, Alias>, typeof JoinOuterScope> as unknown as JoinSource<\n RowType,\n Alias\n >;\n }\n\n getRowFields(): Record<string, ScopeField> {\n return this.state.rowFields;\n }\n\n buildAst(): SelectAst {\n return buildSelectAst(this.state);\n }\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n return buildPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(\n this.state,\n this.ctx,\n );\n }\n}\n\nexport class SelectQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends QueryBase<QC, AvailableScope, RowType>\n implements SelectQuery<QC, AvailableScope, RowType>\n{\n declare readonly [SubqueryMarker]: RowType;\n\n protected clone(state: BuilderState): this {\n return new SelectQueryImpl<QC, AvailableScope, RowType>(state, this.ctx) as this;\n }\n\n select<Columns extends (keyof AvailableScope['topLevel'] & string)[]>(\n ...columns: Columns\n ): SelectQuery<QC, AvailableScope, WithFields<RowType, AvailableScope['topLevel'], Columns>>;\n select<Alias extends string, Field extends ScopeField>(\n alias: Alias,\n expr: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Expression<Field>,\n ): SelectQuery<QC, AvailableScope, WithField<RowType, Field, Alias>>;\n select<Result extends Record<string, Expression<ScopeField>>>(\n callback: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Result,\n ): SelectQuery<QC, AvailableScope, Expand<RowType & ExtractScopeFields<Result>>>;\n select(...args: unknown[]): unknown {\n const { projections, newRowFields } = resolveSelectArgs(args, this.state.scope, this.ctx);\n return new SelectQueryImpl(\n cloneState(this.state, {\n projections: [...this.state.projections, ...projections],\n rowFields: { ...this.state.rowFields, ...newRowFields },\n }),\n this.ctx,\n );\n }\n\n where(expr: ExpressionBuilder<AvailableScope, QC>): SelectQuery<QC, AvailableScope, RowType> {\n const fieldProxy = createFieldProxy(this.state.scope);\n const fns = createFunctions<QC>(this.ctx.queryOperationTypes);\n const result = (expr as ExpressionBuilder<Scope, QueryContext>)(fieldProxy, fns as never);\n return new SelectQueryImpl(\n cloneState(this.state, {\n where: [...this.state.where, result.buildAst()],\n }),\n this.ctx,\n );\n }\n\n orderBy(\n field: (keyof RowType | keyof AvailableScope['topLevel']) & string,\n options?: OrderByOptions,\n ): SelectQuery<QC, AvailableScope, RowType>;\n orderBy(\n expr: (\n fields: FieldProxy<OrderByScope<AvailableScope, RowType>>,\n fns: Functions<QC>,\n ) => Expression<ScopeField>,\n options?: OrderByOptions,\n ): SelectQuery<QC, AvailableScope, RowType>;\n orderBy(arg: unknown, options?: OrderByOptions): unknown {\n const item = resolveOrderBy(\n arg,\n options,\n this.state.scope,\n this.state.rowFields,\n this.ctx,\n false,\n );\n return this.clone(cloneState(this.state, { orderBy: [...this.state.orderBy, item] }));\n }\n}\n\nexport class GroupedQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends QueryBase<QC, AvailableScope, RowType>\n implements GroupedQuery<QC, AvailableScope, RowType>\n{\n declare readonly [SubqueryMarker]: RowType;\n\n protected clone(state: BuilderState): this {\n return new GroupedQueryImpl<QC, AvailableScope, RowType>(state, this.ctx) as this;\n }\n\n having(\n expr: (\n fields: FieldProxy<OrderByScope<AvailableScope, RowType>>,\n fns: AggregateFunctions<QC>,\n ) => Expression<BooleanCodecType>,\n ): GroupedQuery<QC, AvailableScope, RowType> {\n const combined = orderByScopeOf(\n this.state.scope as AvailableScope,\n this.state.rowFields as RowType,\n );\n const fns = createAggregateFunctions(this.ctx.queryOperationTypes);\n const result = expr(createFieldProxy(combined), fns);\n return new GroupedQueryImpl(cloneState(this.state, { having: result.buildAst() }), this.ctx);\n }\n\n orderBy(\n field: (keyof RowType | keyof AvailableScope['topLevel']) & string,\n options?: OrderByOptions,\n ): GroupedQuery<QC, AvailableScope, RowType>;\n orderBy(\n expr: (\n fields: FieldProxy<OrderByScope<AvailableScope, RowType>>,\n fns: AggregateFunctions<QC>,\n ) => Expression<ScopeField>,\n options?: OrderByOptions,\n ): GroupedQuery<QC, AvailableScope, RowType>;\n orderBy(arg: unknown, options?: OrderByOptions): unknown {\n const item = resolveOrderBy(\n arg,\n options,\n this.state.scope,\n this.state.rowFields,\n this.ctx,\n true,\n );\n return this.clone(cloneState(this.state, { orderBy: [...this.state.orderBy, item] }));\n }\n}\n","import {\n AndExpr,\n DerivedTableSource,\n JoinAst,\n type TableSource,\n} from '@prisma-next/sql-relational-core/ast';\nimport type {\n AggregateFunctions,\n Expression,\n ExpressionBuilder,\n ExtractScopeFields,\n FieldProxy,\n WithField,\n WithFields,\n} from '../expression';\nimport type {\n EmptyRow,\n Expand,\n JoinOuterScope,\n JoinSource,\n MergeScopes,\n NullableScope,\n QueryContext,\n Scope,\n ScopeField,\n ScopeTable,\n Subquery,\n} from '../scope';\nimport type { JoinedTables } from '../types/joined-tables';\nimport type { SelectQuery } from '../types/select-query';\nimport type { LateralBuilder } from '../types/shared';\nimport {\n BuilderBase,\n type BuilderContext,\n type BuilderState,\n cloneState,\n emptyState,\n mergeScopes,\n nullableScope,\n resolveSelectArgs,\n} from './builder-base';\nimport { createFieldProxy } from './field-proxy';\nimport { createFunctions } from './functions';\nimport { SelectQueryImpl } from './query-impl';\n\nexport class JoinedTablesImpl<QC extends QueryContext, AvailableScope extends Scope>\n extends BuilderBase<QC['capabilities']>\n implements JoinedTables<QC, AvailableScope>\n{\n readonly #state: BuilderState;\n\n constructor(state: BuilderState, ctx: BuilderContext) {\n super(ctx);\n this.#state = state;\n }\n\n lateralJoin = this._gate(\n { sql: { lateral: true } },\n 'lateralJoin',\n <Alias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: Alias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<AvailableScope, { topLevel: LateralRow; namespaces: Record<Alias, LateralRow> }>\n > => {\n const { derivedSource, lateralScope } = this.#buildLateral(alias, builder);\n const resultScope = mergeScopes(\n this.#state.scope as AvailableScope,\n lateralScope as { topLevel: LateralRow; namespaces: Record<Alias, LateralRow> },\n );\n return this.#addLateralJoin('inner', resultScope, derivedSource);\n },\n ) as JoinedTables<QC, AvailableScope>['lateralJoin'];\n\n outerLateralJoin = this._gate(\n { sql: { lateral: true } },\n 'outerLateralJoin',\n <Alias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: Alias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<\n AvailableScope,\n NullableScope<{ topLevel: LateralRow; namespaces: Record<Alias, LateralRow> }>\n >\n > => {\n const { derivedSource, lateralScope } = this.#buildLateral(alias, builder);\n const resultScope = mergeScopes(\n this.#state.scope as AvailableScope,\n nullableScope(\n lateralScope as { topLevel: LateralRow; namespaces: Record<Alias, LateralRow> },\n ),\n );\n return this.#addLateralJoin('left', resultScope, derivedSource);\n },\n ) as JoinedTables<QC, AvailableScope>['outerLateralJoin'];\n\n select<Columns extends (keyof AvailableScope['topLevel'] & string)[]>(\n ...columns: Columns\n ): SelectQuery<QC, AvailableScope, WithFields<EmptyRow, AvailableScope['topLevel'], Columns>>;\n select<Alias extends string, Field extends ScopeField>(\n alias: Alias,\n expr: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Expression<Field>,\n ): SelectQuery<QC, AvailableScope, WithField<EmptyRow, Field, Alias>>;\n select<Result extends Record<string, Expression<ScopeField>>>(\n callback: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Result,\n ): SelectQuery<QC, AvailableScope, Expand<ExtractScopeFields<Result>>>;\n select(...args: unknown[]): unknown {\n const { projections, newRowFields } = resolveSelectArgs(args, this.#state.scope, this.ctx);\n return new SelectQueryImpl<QC, AvailableScope>(\n cloneState(this.#state, {\n projections: [...this.#state.projections, ...projections],\n rowFields: { ...this.#state.rowFields, ...newRowFields },\n }),\n this.ctx,\n );\n }\n\n innerJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>> {\n const targetScope = mergeScopes(\n this.#state.scope as AvailableScope,\n other.getJoinOuterScope() as Other[typeof JoinOuterScope],\n );\n return this.#addJoin(other, 'inner', targetScope, on);\n }\n\n outerLeftJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<AvailableScope, NullableScope<Other[typeof JoinOuterScope]>>> {\n const targetScope = mergeScopes(\n this.#state.scope as AvailableScope,\n nullableScope(other.getJoinOuterScope() as Other[typeof JoinOuterScope]),\n );\n return this.#addJoin(other, 'left', targetScope, on);\n }\n\n outerRightJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<NullableScope<AvailableScope>, Other[typeof JoinOuterScope]>> {\n const targetScope = mergeScopes(\n nullableScope(this.#state.scope as AvailableScope),\n other.getJoinOuterScope() as Other[typeof JoinOuterScope],\n );\n return this.#addJoin(other, 'right', targetScope, on);\n }\n\n outerFullJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<\n QC,\n MergeScopes<NullableScope<AvailableScope>, NullableScope<Other[typeof JoinOuterScope]>>\n > {\n const targetScope = mergeScopes(\n nullableScope(this.#state.scope as AvailableScope),\n nullableScope(other.getJoinOuterScope() as Other[typeof JoinOuterScope]),\n );\n return this.#addJoin(other, 'full', targetScope, on);\n }\n\n #addJoin<Other extends JoinSource<ScopeTable, string | never>, ResultScope extends Scope>(\n other: Other,\n joinType: 'inner' | 'left' | 'right' | 'full',\n resultScope: ResultScope,\n onExpr: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, ResultScope> {\n const fieldProxy = createFieldProxy(\n mergeScopes(\n this.#state.scope as AvailableScope,\n other.getJoinOuterScope() as Other[typeof JoinOuterScope],\n ),\n ) as FieldProxy<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>>;\n const fns = createFunctions<QC>(this.ctx.queryOperationTypes);\n const onResult = onExpr(fieldProxy, fns);\n const joinAst = new JoinAst(joinType, other.buildAst(), onResult.buildAst());\n\n return new JoinedTablesImpl(\n cloneState(this.#state, {\n joins: [...this.#state.joins, joinAst],\n scope: resultScope,\n }),\n this.ctx,\n );\n }\n\n #buildLateral(\n alias: string,\n builderFn: (\n lateral: LateralBuilder<QC, AvailableScope>,\n ) => Subquery<Record<string, ScopeField>>,\n ) {\n const lateralBuilder: LateralBuilder<QC, AvailableScope> = {\n from: (other) => {\n const otherScope = other.getJoinOuterScope();\n const parentMerged = mergeScopes(this.#state.scope, otherScope);\n return new SelectQueryImpl(\n emptyState(other.buildAst() as TableSource, parentMerged),\n this.ctx,\n ) as unknown as SelectQuery<QC, AvailableScope, EmptyRow>;\n },\n };\n\n const subquery = builderFn(lateralBuilder);\n const subqueryAst = subquery.buildAst();\n const derivedSource = DerivedTableSource.as(alias, subqueryAst);\n const subqueryRowFields: ScopeTable = subquery.getRowFields();\n const lateralScope: Scope = {\n topLevel: subqueryRowFields,\n namespaces: { [alias]: subqueryRowFields },\n };\n\n return { derivedSource, lateralScope };\n }\n\n #addLateralJoin<ResultScope extends Scope>(\n joinType: 'inner' | 'left',\n resultScope: ResultScope,\n derivedSource: DerivedTableSource,\n ): JoinedTables<QC, ResultScope> {\n const onExpr = AndExpr.of([]);\n const joinAst = new JoinAst(joinType, derivedSource, onExpr, true);\n\n return new JoinedTablesImpl(\n cloneState(this.#state, {\n joins: [...this.#state.joins, joinAst],\n scope: resultScope,\n }),\n this.ctx,\n );\n }\n}\n","import type { StorageTable } from '@prisma-next/sql-contract/types';\nimport {\n type AnyExpression as AstExpression,\n ColumnRef,\n DeleteAst,\n InsertAst,\n ParamRef,\n ProjectionItem,\n TableSource,\n UpdateAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type { MutationDefaultsOp } from '@prisma-next/sql-relational-core/query-lane-context';\nimport type { ExpressionBuilder } from '../expression';\nimport type { ResolveRow } from '../resolve';\nimport type { QueryContext, Scope, ScopeField } from '../scope';\nimport type {\n DeleteQuery,\n InsertQuery,\n ReturningCapability,\n UpdateQuery,\n} from '../types/mutation-query';\nimport {\n BuilderBase,\n type BuilderContext,\n buildQueryPlan,\n combineWhereExprs,\n} from './builder-base';\nimport { createFieldProxy } from './field-proxy';\nimport { createFunctions } from './functions';\n\ntype WhereCallback = ExpressionBuilder<Scope, QueryContext>;\n\nfunction buildParamValues(\n values: Record<string, unknown>,\n table: StorageTable,\n tableName: string,\n op: MutationDefaultsOp,\n ctx: BuilderContext,\n): Record<string, ParamRef> {\n const params: Record<string, ParamRef> = {};\n for (const [col, value] of Object.entries(values)) {\n const column = table.columns[col];\n params[col] = ParamRef.of(\n value,\n column ? { codecId: column.codecId, refs: { table: tableName, column: col } } : undefined,\n );\n }\n for (const def of ctx.applyMutationDefaults({ op, table: tableName, values })) {\n const column = table.columns[def.column];\n params[def.column] = ParamRef.of(\n def.value,\n column\n ? { codecId: column.codecId, refs: { table: tableName, column: def.column } }\n : undefined,\n );\n }\n return params;\n}\n\nfunction buildReturningProjections(\n tableName: string,\n columns: string[],\n rowFields: Record<string, ScopeField>,\n): ProjectionItem[] {\n return columns.map((col) =>\n ProjectionItem.of(col, ColumnRef.of(tableName, col), rowFields[col]?.codecId),\n );\n}\n\nfunction evaluateWhere(\n whereCallback: WhereCallback,\n scope: Scope,\n queryOperationTypes: BuilderContext['queryOperationTypes'],\n): AstExpression {\n const fieldProxy = createFieldProxy(scope);\n const fns = createFunctions(queryOperationTypes);\n const result = whereCallback(fieldProxy, fns as never);\n return result.buildAst();\n}\n\nexport class InsertQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends BuilderBase<QC['capabilities']>\n implements InsertQuery<QC, AvailableScope, RowType>\n{\n readonly #tableName: string;\n readonly #table: StorageTable;\n readonly #scope: Scope;\n readonly #values: Record<string, unknown>;\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n\n constructor(\n tableName: string,\n table: StorageTable,\n scope: Scope,\n values: Record<string, unknown>,\n ctx: BuilderContext,\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n ) {\n super(ctx);\n this.#tableName = tableName;\n this.#table = table;\n this.#scope = scope;\n this.#values = values;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n }\n\n returning = this._gate<ReturningCapability, string[], InsertQuery<QC, AvailableScope, never>>(\n { sql: { returning: true } },\n 'returning',\n (...columns: string[]) => {\n const newRowFields: Record<string, ScopeField> = {};\n for (const col of columns) {\n const field = this.#scope.topLevel[col];\n if (!field) throw new Error(`Column \"${col}\" not found in scope`);\n newRowFields[col] = field;\n }\n return new InsertQueryImpl(\n this.#tableName,\n this.#table,\n this.#scope,\n this.#values,\n this.ctx,\n columns,\n newRowFields,\n ) as unknown as InsertQuery<QC, AvailableScope, never>;\n },\n );\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n const paramValues = buildParamValues(\n this.#values,\n this.#table,\n this.#tableName,\n 'create',\n this.ctx,\n );\n\n let ast = InsertAst.into(TableSource.named(this.#tableName)).withValues(paramValues);\n\n if (this.#returningColumns.length > 0) {\n ast = ast.withReturning(\n buildReturningProjections(this.#tableName, this.#returningColumns, this.#rowFields),\n );\n }\n\n return buildQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(\n ast,\n this.ctx,\n );\n }\n}\n\nexport class UpdateQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends BuilderBase<QC['capabilities']>\n implements UpdateQuery<QC, AvailableScope, RowType>\n{\n readonly #tableName: string;\n readonly #table: StorageTable;\n readonly #scope: Scope;\n readonly #setValues: Record<string, unknown>;\n readonly #whereCallbacks: readonly WhereCallback[];\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n\n constructor(\n tableName: string,\n table: StorageTable,\n scope: Scope,\n setValues: Record<string, unknown>,\n ctx: BuilderContext,\n whereCallbacks: readonly WhereCallback[] = [],\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n ) {\n super(ctx);\n this.#tableName = tableName;\n this.#table = table;\n this.#scope = scope;\n this.#setValues = setValues;\n this.#whereCallbacks = whereCallbacks;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n }\n\n where(expr: ExpressionBuilder<AvailableScope, QC>): UpdateQuery<QC, AvailableScope, RowType> {\n return new UpdateQueryImpl(\n this.#tableName,\n this.#table,\n this.#scope,\n this.#setValues,\n this.ctx,\n [...this.#whereCallbacks, expr as unknown as WhereCallback],\n this.#returningColumns,\n this.#rowFields,\n );\n }\n\n returning = this._gate<ReturningCapability, string[], UpdateQuery<QC, AvailableScope, never>>(\n { sql: { returning: true } },\n 'returning',\n (...columns: string[]) => {\n const newRowFields: Record<string, ScopeField> = {};\n for (const col of columns) {\n const field = this.#scope.topLevel[col];\n if (!field) throw new Error(`Column \"${col}\" not found in scope`);\n newRowFields[col] = field;\n }\n return new UpdateQueryImpl(\n this.#tableName,\n this.#table,\n this.#scope,\n this.#setValues,\n this.ctx,\n this.#whereCallbacks,\n columns,\n newRowFields,\n ) as unknown as UpdateQuery<QC, AvailableScope, never>;\n },\n );\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n const setParams = buildParamValues(\n this.#setValues,\n this.#table,\n this.#tableName,\n 'update',\n this.ctx,\n );\n\n const whereExpr = combineWhereExprs(\n this.#whereCallbacks.map((cb) =>\n evaluateWhere(cb, this.#scope, this.ctx.queryOperationTypes),\n ),\n );\n\n let ast = UpdateAst.table(TableSource.named(this.#tableName))\n .withSet(setParams)\n .withWhere(whereExpr);\n\n if (this.#returningColumns.length > 0) {\n ast = ast.withReturning(\n buildReturningProjections(this.#tableName, this.#returningColumns, this.#rowFields),\n );\n }\n\n return buildQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(\n ast,\n this.ctx,\n );\n }\n}\n\nexport class DeleteQueryImpl<\n QC extends QueryContext = QueryContext,\n AvailableScope extends Scope = Scope,\n RowType extends Record<string, ScopeField> = Record<string, ScopeField>,\n >\n extends BuilderBase<QC['capabilities']>\n implements DeleteQuery<QC, AvailableScope, RowType>\n{\n readonly #tableName: string;\n readonly #scope: Scope;\n readonly #whereCallbacks: readonly WhereCallback[];\n readonly #returningColumns: string[];\n readonly #rowFields: Record<string, ScopeField>;\n\n constructor(\n tableName: string,\n scope: Scope,\n ctx: BuilderContext,\n whereCallbacks: readonly WhereCallback[] = [],\n returningColumns: string[] = [],\n rowFields: Record<string, ScopeField> = {},\n ) {\n super(ctx);\n this.#tableName = tableName;\n this.#scope = scope;\n this.#whereCallbacks = whereCallbacks;\n this.#returningColumns = returningColumns;\n this.#rowFields = rowFields;\n }\n\n where(expr: ExpressionBuilder<AvailableScope, QC>): DeleteQuery<QC, AvailableScope, RowType> {\n return new DeleteQueryImpl(\n this.#tableName,\n this.#scope,\n this.ctx,\n [...this.#whereCallbacks, expr as unknown as WhereCallback],\n this.#returningColumns,\n this.#rowFields,\n );\n }\n\n returning = this._gate<ReturningCapability, string[], DeleteQuery<QC, AvailableScope, never>>(\n { sql: { returning: true } },\n 'returning',\n (...columns: string[]) => {\n const newRowFields: Record<string, ScopeField> = {};\n for (const col of columns) {\n const field = this.#scope.topLevel[col];\n if (!field) throw new Error(`Column \"${col}\" not found in scope`);\n newRowFields[col] = field;\n }\n return new DeleteQueryImpl(\n this.#tableName,\n this.#scope,\n this.ctx,\n this.#whereCallbacks,\n columns,\n newRowFields,\n ) as unknown as DeleteQuery<QC, AvailableScope, never>;\n },\n );\n\n build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {\n const whereExpr = combineWhereExprs(\n this.#whereCallbacks.map((cb) =>\n evaluateWhere(cb, this.#scope, this.ctx.queryOperationTypes),\n ),\n );\n\n let ast = DeleteAst.from(TableSource.named(this.#tableName)).withWhere(whereExpr);\n\n if (this.#returningColumns.length > 0) {\n ast = ast.withReturning(\n buildReturningProjections(this.#tableName, this.#returningColumns, this.#rowFields),\n );\n }\n\n return buildQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(\n ast,\n this.ctx,\n );\n }\n}\n","import type { StorageTable } from '@prisma-next/sql-contract/types';\nimport { type AnyFromSource, TableSource } from '@prisma-next/sql-relational-core/ast';\nimport type {\n AggregateFunctions,\n Expression,\n ExpressionBuilder,\n ExtractScopeFields,\n FieldProxy,\n WithField,\n WithFields,\n} from '../expression';\nimport type {\n EmptyRow,\n Expand,\n JoinOuterScope,\n JoinSource,\n MergeScopes,\n NullableScope,\n QueryContext,\n RebindScope,\n Scope,\n ScopeField,\n ScopeTable,\n StorageTableToScopeTable,\n Subquery,\n} from '../scope';\nimport type { TableProxyContract } from '../types/db';\nimport type { JoinedTables } from '../types/joined-tables';\nimport type { DeleteQuery, InsertQuery, UpdateQuery } from '../types/mutation-query';\nimport type { SelectQuery } from '../types/select-query';\nimport type { LateralBuilder } from '../types/shared';\nimport type { TableProxy } from '../types/table-proxy';\nimport { BuilderBase, type BuilderContext, emptyState, tableToScope } from './builder-base';\nimport { JoinedTablesImpl } from './joined-tables-impl';\nimport { DeleteQueryImpl, InsertQueryImpl, UpdateQueryImpl } from './mutation-impl';\nimport { SelectQueryImpl } from './query-impl';\n\nexport class TableProxyImpl<\n C extends TableProxyContract,\n Name extends string & keyof C['storage']['tables'],\n Alias extends string,\n AvailableScope extends Scope,\n QC extends QueryContext,\n >\n extends BuilderBase<C['capabilities']>\n implements TableProxy<C, Name, Alias, AvailableScope, QC>\n{\n declare readonly [JoinOuterScope]: JoinSource<\n StorageTableToScopeTable<C['storage']['tables'][Name]>,\n Alias\n >[typeof JoinOuterScope];\n\n readonly #tableName: string;\n readonly #table: StorageTable;\n readonly #fromSource: TableSource;\n readonly #scope: Scope;\n\n constructor(tableName: string, table: StorageTable, alias: string, ctx: BuilderContext) {\n super(ctx);\n this.#tableName = tableName;\n this.#table = table;\n this.#scope = tableToScope(alias, table);\n this.#fromSource = TableSource.named(tableName, alias !== tableName ? alias : undefined);\n }\n\n lateralJoin = this._gate(\n { sql: { lateral: true } },\n 'lateralJoin',\n <LAlias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: LAlias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<AvailableScope, { topLevel: LateralRow; namespaces: Record<LAlias, LateralRow> }>\n > => {\n return this.#toJoined().lateralJoin(alias, builder);\n },\n ) as TableProxy<C, Name, Alias, AvailableScope, QC>['lateralJoin'];\n\n outerLateralJoin = this._gate(\n { sql: { lateral: true } },\n 'outerLateralJoin',\n <LAlias extends string, LateralRow extends Record<string, ScopeField>>(\n alias: LAlias,\n builder: (lateral: LateralBuilder<QC, AvailableScope>) => Subquery<LateralRow>,\n ): JoinedTables<\n QC,\n MergeScopes<\n AvailableScope,\n NullableScope<{ topLevel: LateralRow; namespaces: Record<LAlias, LateralRow> }>\n >\n > => {\n return this.#toJoined().outerLateralJoin(alias, builder);\n },\n ) as TableProxy<C, Name, Alias, AvailableScope, QC>['outerLateralJoin'];\n\n getJoinOuterScope(): Scope {\n return this.#scope;\n }\n\n buildAst(): AnyFromSource {\n return this.#fromSource;\n }\n\n as<NewAlias extends string>(\n newAlias: NewAlias,\n ): TableProxy<C, Name, NewAlias, RebindScope<AvailableScope, Alias, NewAlias>> {\n return new TableProxyImpl(this.#tableName, this.#table, newAlias, this.ctx);\n }\n\n select<Columns extends (keyof AvailableScope['topLevel'] & string)[]>(\n ...columns: Columns\n ): SelectQuery<QC, AvailableScope, WithFields<EmptyRow, AvailableScope['topLevel'], Columns>>;\n select<LAlias extends string, Field extends ScopeField>(\n alias: LAlias,\n expr: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Expression<Field>,\n ): SelectQuery<QC, AvailableScope, WithField<EmptyRow, Field, LAlias>>;\n select<Result extends Record<string, Expression<ScopeField>>>(\n callback: (fields: FieldProxy<AvailableScope>, fns: AggregateFunctions<QC>) => Result,\n ): SelectQuery<QC, AvailableScope, Expand<ExtractScopeFields<Result>>>;\n select(...args: unknown[]): unknown {\n return new SelectQueryImpl(emptyState(this.#fromSource, this.#scope), this.ctx).select(\n ...(args as string[]),\n );\n }\n\n innerJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>> {\n return this.#toJoined().innerJoin(other, on);\n }\n\n outerLeftJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<AvailableScope, NullableScope<Other[typeof JoinOuterScope]>>> {\n return this.#toJoined().outerLeftJoin(other, on);\n }\n\n outerRightJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<QC, MergeScopes<NullableScope<AvailableScope>, Other[typeof JoinOuterScope]>> {\n return this.#toJoined().outerRightJoin(other, on);\n }\n\n outerFullJoin<Other extends JoinSource<ScopeTable, string | never>>(\n other: Other,\n on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,\n ): JoinedTables<\n QC,\n MergeScopes<NullableScope<AvailableScope>, NullableScope<Other[typeof JoinOuterScope]>>\n > {\n return this.#toJoined().outerFullJoin(other, on);\n }\n\n insert(values: Record<string, unknown>): InsertQuery<QC, AvailableScope, EmptyRow> {\n return new InsertQueryImpl(this.#tableName, this.#table, this.#scope, values, this.ctx);\n }\n\n update(set: Record<string, unknown>): UpdateQuery<QC, AvailableScope, EmptyRow> {\n return new UpdateQueryImpl(this.#tableName, this.#table, this.#scope, set, this.ctx);\n }\n\n delete(): DeleteQuery<QC, AvailableScope, EmptyRow> {\n return new DeleteQueryImpl(this.#tableName, this.#scope, this.ctx);\n }\n\n #toJoined(): JoinedTables<QC, AvailableScope> {\n return new JoinedTablesImpl(emptyState(this.#fromSource, this.#scope), this.ctx);\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { ExecutionContext } from '@prisma-next/sql-relational-core/query-lane-context';\nimport type { Db } from '../types/db';\nimport type { BuilderContext } from './builder-base';\nimport { TableProxyImpl } from './table-proxy-impl';\n\nexport interface SqlOptions<C extends Contract<SqlStorage>> {\n readonly context: ExecutionContext<C>;\n}\n\nexport function sql<C extends Contract<SqlStorage>>(options: SqlOptions<C>): Db<C> {\n const { context } = options;\n const ctx: BuilderContext = {\n capabilities: context.contract.capabilities,\n queryOperationTypes: context.queryOperations.entries(),\n target: context.contract.target ?? 'unknown',\n storageHash: context.contract.storage.storageHash ?? 'unknown',\n applyMutationDefaults: (options) => context.applyMutationDefaults(options),\n };\n\n return new Proxy({} as Db<C>, {\n get(_target, prop: string) {\n const tables = context.contract.storage.tables;\n const table = Object.hasOwn(tables, prop) ? tables[prop] : undefined;\n if (table) {\n return new TableProxyImpl(prop, table, prop, ctx);\n }\n return undefined;\n },\n });\n}\n"],"mappings":";;;;;;;;AASA,IAAa,iBAAb,MAAwF;CACtF;CACA;CACA;CAEA,YACE,KACA,YACA,MACA;EACA,KAAK,MAAM;EACX,KAAK,aAAa;EAClB,KAAK,OAAO;;CAGd,WAA0B;EACxB,OAAO,KAAK;;;;;;;;;AChBhB,SAASA,yBAAuB,OAAc,WAAuC;CACnF,IAAI;CACJ,KAAK,MAAM,CAAC,WAAW,WAAW,OAAO,QAAQ,MAAM,WAAW,EAChE,IAAI,OAAO,OAAO,QAAQ,UAAU,EAAE;EACpC,IAAI,UAAU,KAAA,G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sideEffects": false,
|
|
6
7
|
"description": "SQL builder lane for Prisma Next",
|
|
7
8
|
"dependencies": {
|
|
8
|
-
"@prisma-next/
|
|
9
|
-
"@prisma-next/
|
|
10
|
-
"@prisma-next/
|
|
9
|
+
"@prisma-next/contract": "0.6.0-dev.1",
|
|
10
|
+
"@prisma-next/sql-contract": "0.6.0-dev.1",
|
|
11
|
+
"@prisma-next/framework-components": "0.6.0-dev.1",
|
|
12
|
+
"@prisma-next/sql-operations": "0.6.0-dev.1",
|
|
13
|
+
"@prisma-next/sql-relational-core": "0.6.0-dev.1"
|
|
11
14
|
},
|
|
12
15
|
"devDependencies": {
|
|
13
|
-
"tsdown": "0.
|
|
16
|
+
"tsdown": "0.22.0",
|
|
14
17
|
"typescript": "5.9.3",
|
|
15
|
-
"vitest": "4.
|
|
16
|
-
"@prisma-next/adapter-postgres": "0.
|
|
17
|
-
"@prisma-next/
|
|
18
|
-
"@prisma-next/contract": "0.
|
|
19
|
-
"@prisma-next/
|
|
20
|
-
"@prisma-next/sql-contract": "0.5.0-dev.9",
|
|
21
|
-
"@prisma-next/sql-contract-ts": "0.5.0-dev.9",
|
|
18
|
+
"vitest": "4.1.5",
|
|
19
|
+
"@prisma-next/adapter-postgres": "0.6.0-dev.1",
|
|
20
|
+
"@prisma-next/ids": "0.6.0-dev.1",
|
|
21
|
+
"@prisma-next/sql-contract-ts": "0.6.0-dev.1",
|
|
22
|
+
"@prisma-next/target-postgres": "0.6.0-dev.1",
|
|
22
23
|
"@prisma-next/test-utils": "0.0.1",
|
|
23
|
-
"@prisma-next/
|
|
24
|
-
"@prisma-next/
|
|
25
|
-
"@prisma-next/
|
|
26
|
-
"@prisma-next/
|
|
24
|
+
"@prisma-next/extension-pgvector": "0.6.0-dev.1",
|
|
25
|
+
"@prisma-next/tsconfig": "0.0.0",
|
|
26
|
+
"@prisma-next/utils": "0.6.0-dev.1",
|
|
27
|
+
"@prisma-next/tsdown": "0.0.0"
|
|
27
28
|
},
|
|
28
29
|
"files": [
|
|
29
30
|
"dist",
|
|
@@ -38,8 +39,6 @@
|
|
|
38
39
|
"./runtime": "./dist/runtime/index.mjs",
|
|
39
40
|
"./package.json": "./package.json"
|
|
40
41
|
},
|
|
41
|
-
"main": "./dist/index.mjs",
|
|
42
|
-
"module": "./dist/index.mjs",
|
|
43
42
|
"types": "./dist/index.d.mts",
|
|
44
43
|
"repository": {
|
|
45
44
|
"type": "git",
|
package/src/expression.ts
CHANGED
|
@@ -1,19 +1,14 @@
|
|
|
1
1
|
import type { QueryOperationTypesBase } from '@prisma-next/sql-contract/types';
|
|
2
2
|
import type {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
export type Expression<T extends FieldSpec> = {
|
|
14
|
-
[ExpressionType]: T;
|
|
15
|
-
buildAst(): import('@prisma-next/sql-relational-core/ast').AnyExpression;
|
|
16
|
-
};
|
|
3
|
+
CodecExpression,
|
|
4
|
+
Expression,
|
|
5
|
+
TraitExpression,
|
|
6
|
+
} from '@prisma-next/sql-relational-core/expression';
|
|
7
|
+
import type { Expand, QueryContext, Scope, ScopeField, ScopeTable, Subquery } from './scope';
|
|
8
|
+
|
|
9
|
+
export type { CodecExpression, Expression, TraitExpression };
|
|
10
|
+
|
|
11
|
+
export type BooleanCodecType = { codecId: 'pg/bool@1'; nullable: boolean };
|
|
17
12
|
|
|
18
13
|
export type WithField<Source, Field extends ScopeField, Alias extends string> = Expand<
|
|
19
14
|
Source & { [K in Alias]: Field }
|
|
@@ -39,13 +34,6 @@ export type FieldProxy<AvailableScope extends Scope> = {
|
|
|
39
34
|
};
|
|
40
35
|
};
|
|
41
36
|
|
|
42
|
-
export type ExpressionOrValue<
|
|
43
|
-
T extends ScopeField,
|
|
44
|
-
CT extends Record<string, { readonly input: unknown }>,
|
|
45
|
-
> = Expression<T> | (T['codecId'] extends keyof CT ? CT[T['codecId']]['input'] : never);
|
|
46
|
-
|
|
47
|
-
export type BooleanCodecType = { codecId: 'pg/bool@1'; nullable: boolean };
|
|
48
|
-
|
|
49
37
|
export type ExpressionBuilder<AvailableScope extends Scope, QC extends QueryContext> = (
|
|
50
38
|
fields: FieldProxy<AvailableScope>,
|
|
51
39
|
fns: Functions<QC>,
|
|
@@ -67,70 +55,37 @@ export type OrderByScope<
|
|
|
67
55
|
namespaces: AvailableScope['namespaces'];
|
|
68
56
|
};
|
|
69
57
|
|
|
70
|
-
type
|
|
71
|
-
|
|
72
|
-
RequiredTraits extends readonly string[],
|
|
73
|
-
> = {
|
|
74
|
-
[K in keyof CT & string]: CT[K] extends { readonly traits: infer T }
|
|
75
|
-
? [RequiredTraits[number]] extends [T]
|
|
76
|
-
? K
|
|
77
|
-
: never
|
|
78
|
-
: never;
|
|
79
|
-
}[keyof CT & string];
|
|
80
|
-
|
|
81
|
-
type ResolveExtArg<Arg, CT extends Record<string, { readonly input: unknown }>> = Arg extends {
|
|
82
|
-
readonly codecId: infer CId extends string;
|
|
83
|
-
readonly nullable: infer N extends boolean;
|
|
84
|
-
}
|
|
85
|
-
? ExpressionOrValue<{ codecId: CId; nullable: N }, CT>
|
|
86
|
-
: Arg extends {
|
|
87
|
-
readonly traits: infer T extends readonly string[];
|
|
88
|
-
readonly nullable: infer N extends boolean;
|
|
89
|
-
}
|
|
90
|
-
? ExpressionOrValue<{ codecId: CodecIdsWithTrait<CT, T>; nullable: N }, CT>
|
|
91
|
-
: never;
|
|
92
|
-
|
|
93
|
-
type ExtensionFunctionArgs<
|
|
94
|
-
Args extends readonly unknown[],
|
|
95
|
-
CT extends Record<string, { readonly input: unknown }>,
|
|
96
|
-
> = { [I in keyof Args]: ResolveExtArg<Args[I], CT> };
|
|
97
|
-
|
|
98
|
-
type DeriveExtFunctions<
|
|
99
|
-
OT extends QueryOperationTypesBase,
|
|
100
|
-
CT extends Record<string, { readonly input: unknown }>,
|
|
101
|
-
> = {
|
|
102
|
-
[K in keyof OT]: (
|
|
103
|
-
...args: ExtensionFunctionArgs<OT[K]['args'], CT>
|
|
104
|
-
) => Expression<OT[K]['returns']>;
|
|
58
|
+
type DeriveExtFunctions<OT extends QueryOperationTypesBase> = {
|
|
59
|
+
[K in keyof OT]: OT[K]['impl'];
|
|
105
60
|
};
|
|
106
61
|
|
|
107
62
|
export type BuiltinFunctions<CT extends Record<string, { readonly input: unknown }>> = {
|
|
108
63
|
eq: <CodecId extends string>(
|
|
109
|
-
a:
|
|
110
|
-
b:
|
|
64
|
+
a: CodecExpression<CodecId, boolean, CT> | null,
|
|
65
|
+
b: CodecExpression<CodecId, boolean, CT> | null,
|
|
111
66
|
) => Expression<BooleanCodecType>;
|
|
112
|
-
ne: <
|
|
113
|
-
a:
|
|
114
|
-
b:
|
|
67
|
+
ne: <CodecId extends string, N extends boolean>(
|
|
68
|
+
a: CodecExpression<CodecId, N, CT> | null,
|
|
69
|
+
b: CodecExpression<CodecId, N, CT> | null,
|
|
115
70
|
) => Expression<BooleanCodecType>;
|
|
116
|
-
gt: <
|
|
117
|
-
a:
|
|
118
|
-
b:
|
|
71
|
+
gt: <CodecId extends string, N extends boolean>(
|
|
72
|
+
a: CodecExpression<CodecId, N, CT>,
|
|
73
|
+
b: CodecExpression<CodecId, N, CT>,
|
|
119
74
|
) => Expression<BooleanCodecType>;
|
|
120
|
-
gte: <
|
|
121
|
-
a:
|
|
122
|
-
b:
|
|
75
|
+
gte: <CodecId extends string, N extends boolean>(
|
|
76
|
+
a: CodecExpression<CodecId, N, CT>,
|
|
77
|
+
b: CodecExpression<CodecId, N, CT>,
|
|
123
78
|
) => Expression<BooleanCodecType>;
|
|
124
|
-
lt: <
|
|
125
|
-
a:
|
|
126
|
-
b:
|
|
79
|
+
lt: <CodecId extends string, N extends boolean>(
|
|
80
|
+
a: CodecExpression<CodecId, N, CT>,
|
|
81
|
+
b: CodecExpression<CodecId, N, CT>,
|
|
127
82
|
) => Expression<BooleanCodecType>;
|
|
128
|
-
lte: <
|
|
129
|
-
a:
|
|
130
|
-
b:
|
|
83
|
+
lte: <CodecId extends string, N extends boolean>(
|
|
84
|
+
a: CodecExpression<CodecId, N, CT>,
|
|
85
|
+
b: CodecExpression<CodecId, N, CT>,
|
|
131
86
|
) => Expression<BooleanCodecType>;
|
|
132
|
-
and: (...ands:
|
|
133
|
-
or: (...ors:
|
|
87
|
+
and: (...ands: CodecExpression<'pg/bool@1', boolean, CT>[]) => Expression<BooleanCodecType>;
|
|
88
|
+
or: (...ors: CodecExpression<'pg/bool@1', boolean, CT>[]) => Expression<BooleanCodecType>;
|
|
134
89
|
|
|
135
90
|
exists: (subquery: Subquery<Record<string, ScopeField>>) => Expression<BooleanCodecType>;
|
|
136
91
|
notExists: (subquery: Subquery<Record<string, ScopeField>>) => Expression<BooleanCodecType>;
|
|
@@ -142,7 +97,7 @@ export type BuiltinFunctions<CT extends Record<string, { readonly input: unknown
|
|
|
142
97
|
): Expression<BooleanCodecType>;
|
|
143
98
|
<CodecId extends string>(
|
|
144
99
|
expr: Expression<{ codecId: CodecId; nullable: boolean }>,
|
|
145
|
-
values: Array<
|
|
100
|
+
values: Array<CodecExpression<CodecId, boolean, CT>>,
|
|
146
101
|
): Expression<BooleanCodecType>;
|
|
147
102
|
};
|
|
148
103
|
|
|
@@ -153,13 +108,13 @@ export type BuiltinFunctions<CT extends Record<string, { readonly input: unknown
|
|
|
153
108
|
): Expression<BooleanCodecType>;
|
|
154
109
|
<CodecId extends string>(
|
|
155
110
|
expr: Expression<{ codecId: CodecId; nullable: boolean }>,
|
|
156
|
-
values: Array<
|
|
111
|
+
values: Array<CodecExpression<CodecId, boolean, CT>>,
|
|
157
112
|
): Expression<BooleanCodecType>;
|
|
158
113
|
};
|
|
159
114
|
};
|
|
160
115
|
|
|
161
116
|
export type Functions<QC extends QueryContext> = BuiltinFunctions<QC['codecTypes']> &
|
|
162
|
-
DeriveExtFunctions<QC['queryOperationTypes']
|
|
117
|
+
DeriveExtFunctions<QC['queryOperationTypes']>;
|
|
163
118
|
|
|
164
119
|
export type CountField = { codecId: 'pg/int8@1'; nullable: false };
|
|
165
120
|
|