@prisma-next/sql-builder 0.0.1 → 0.3.0-dev.162
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/LICENSE +201 -0
- package/dist/db-C7A7Y4tB.d.mts +348 -0
- package/dist/db-C7A7Y4tB.d.mts.map +1 -0
- package/dist/exports/types.d.mts +2 -0
- package/dist/exports/types.mjs +1 -0
- package/dist/index.d.mts +2 -0
- package/dist/index.mjs +1 -0
- package/dist/runtime/index.d.mts +35 -0
- package/dist/runtime/index.d.mts.map +1 -0
- package/dist/runtime/index.mjs +765 -0
- package/dist/runtime/index.mjs.map +1 -0
- package/package.json +30 -36
- package/src/exports/types.ts +1 -1
- package/src/resolve.ts +17 -7
- package/src/runtime/builder-base.ts +2 -2
- package/src/runtime/functions.ts +5 -6
- package/src/runtime/index.ts +1 -0
- package/src/runtime/mutation-impl.ts +18 -6
- package/src/runtime/query-impl.ts +5 -2
- package/src/runtime/sql.ts +5 -4
- package/src/scope.ts +1 -0
- package/src/types/mutation-query.ts +3 -3
- package/src/types/shared.ts +1 -1
- package/src/types/table-proxy.ts +114 -11
|
@@ -0,0 +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, prop, ctx);\n }\n return undefined;\n },\n });\n}\n"],"mappings":";;;;;;;AASA,IAAa,iBAAb,MAAwF;CAEtF,AAAiB;CACjB,AAAS;CAET,YAAY,KAAoB,OAAU;AACxC,OAAK,MAAM;AACX,OAAK,QAAQ;;CAGf,WAA0B;AACxB,SAAO,KAAK;;;;;;ACfhB,SAAgB,iBAAkC,OAAyB;AACzE,QAAO,IAAI,MAAM,EAAE,EAAmB,EACpC,IAAI,SAAS,MAAc;AACzB,MAAI,OAAO,OAAO,MAAM,UAAU,KAAK,EAAE;GACvC,MAAM,WAAW,MAAM,SAAS;AAChC,OAAI,SAAU,QAAO,IAAI,eAAe,cAAc,GAAG,KAAK,EAAE,SAAS;;AAG3E,MAAI,OAAO,OAAO,MAAM,YAAY,KAAK,EAAE;GACzC,MAAM,WAAW,MAAM,WAAW;AAClC,OAAI,SAAU,QAAO,qBAAqB,MAAM,SAAS;;IAK9D,CAAC;;AAGJ,SAAS,qBACP,eACA,QACgC;AAChC,QAAO,IAAI,MAAM,EAAE,EAAoC,EACrD,IAAI,SAAS,MAAc;AACzB,MAAI,OAAO,OAAO,QAAQ,KAAK,EAAE;GAC/B,MAAM,QAAQ,OAAO;AACrB,OAAI,MAAO,QAAO,IAAI,eAAe,UAAU,GAAG,eAAe,KAAK,EAAE,MAAM;;IAInF,CAAC;;;;;ACJJ,MAAMA,aAA+B;CAAE,SAAS;CAAa,UAAU;CAAO;AAE9E,SAAS,QAAQ,OAAiC;AAChD,KAAI,iBAAiB,eAAgB,QAAO,MAAM,UAAU;AAC5D,QAAO,SAAS,GAAG,MAAM;;AAG3B,SAAS,aAAa,OAAiC;AACrD,KAAI,iBAAiB,eAAgB,QAAO,MAAM,UAAU;AAC5D,QAAO,IAAI,YAAY,MAAM;;AAG/B,SAAS,SAAS,SAA0D;AAC1E,QAAO,IAAI,eAAe,SAAS,WAAW;;AA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MAAM,SAAS,QAAQ,SAAS,QAAQ;EACxC,MAAM,QAAQ,OAAO,OAAO,QAAQ,KAAK,GAAG,OAAO,QAAQ;AAC3D,MAAI,MACF,QAAO,IAAI,eAAe,MAAM,OAAO,MAAM,IAAI;IAItD,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,46 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/sql-builder",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.3.0-dev.162",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"description": "SQL builder lane for Prisma Next",
|
|
7
|
-
"scripts": {
|
|
8
|
-
"build": "tsdown",
|
|
9
|
-
"preemit": "pnpm --filter @prisma-next/cli... build",
|
|
10
|
-
"emit": "node ../../../1-framework/3-tooling/cli/dist/cli.js contract emit --config test/fixtures/prisma-next.config.ts",
|
|
11
|
-
"emit:check": "pnpm emit && git diff --exit-code test/fixtures/generated/",
|
|
12
|
-
"test": "vitest run --passWithNoTests",
|
|
13
|
-
"~test:coverage": "vitest run --coverage --passWithNoTests",
|
|
14
|
-
"typecheck": "tsc --noEmit",
|
|
15
|
-
"lint": "biome check . --error-on-warnings",
|
|
16
|
-
"lint:fix": "biome check --write .",
|
|
17
|
-
"lint:fix:unsafe": "biome check --write --unsafe .",
|
|
18
|
-
"clean": "rm -rf dist dist-tsc dist-tsc-prod coverage .tmp-output"
|
|
19
|
-
},
|
|
20
7
|
"dependencies": {
|
|
21
|
-
"@prisma-next/
|
|
8
|
+
"@prisma-next/framework-components": "0.3.0-dev.162",
|
|
9
|
+
"@prisma-next/sql-operations": "0.3.0-dev.162",
|
|
10
|
+
"@prisma-next/sql-relational-core": "0.3.0-dev.162"
|
|
22
11
|
},
|
|
23
12
|
"devDependencies": {
|
|
24
|
-
"
|
|
25
|
-
"
|
|
26
|
-
"
|
|
27
|
-
"@prisma-next/
|
|
28
|
-
"@prisma-next/
|
|
29
|
-
"@prisma-next/extension-pgvector": "
|
|
30
|
-
"@prisma-next/
|
|
31
|
-
"@prisma-next/
|
|
32
|
-
"@prisma-next/sql-contract": "
|
|
33
|
-
"@prisma-next/
|
|
34
|
-
"@prisma-next/
|
|
35
|
-
"@prisma-next/
|
|
36
|
-
"@prisma-next/
|
|
37
|
-
"@prisma-next/tsconfig": "workspace:*",
|
|
38
|
-
"@prisma-next/tsdown": "workspace:*",
|
|
39
|
-
"@types/pg": "catalog:",
|
|
40
|
-
"pg": "catalog:",
|
|
41
|
-
"tsdown": "catalog:",
|
|
42
|
-
"typescript": "catalog:",
|
|
43
|
-
"vitest": "catalog:"
|
|
13
|
+
"tsdown": "0.18.4",
|
|
14
|
+
"typescript": "5.9.3",
|
|
15
|
+
"vitest": "4.0.17",
|
|
16
|
+
"@prisma-next/adapter-postgres": "0.3.0-dev.162",
|
|
17
|
+
"@prisma-next/contract": "0.3.0-dev.162",
|
|
18
|
+
"@prisma-next/extension-pgvector": "0.3.0-dev.162",
|
|
19
|
+
"@prisma-next/ids": "0.3.0-dev.162",
|
|
20
|
+
"@prisma-next/sql-contract": "0.3.0-dev.162",
|
|
21
|
+
"@prisma-next/sql-contract-ts": "0.3.0-dev.162",
|
|
22
|
+
"@prisma-next/test-utils": "0.0.1",
|
|
23
|
+
"@prisma-next/utils": "0.3.0-dev.162",
|
|
24
|
+
"@prisma-next/tsconfig": "0.0.0",
|
|
25
|
+
"@prisma-next/tsdown": "0.0.0"
|
|
44
26
|
},
|
|
45
27
|
"files": [
|
|
46
28
|
"dist",
|
|
@@ -62,5 +44,17 @@
|
|
|
62
44
|
"type": "git",
|
|
63
45
|
"url": "https://github.com/prisma/prisma-next.git",
|
|
64
46
|
"directory": "packages/2-sql/4-lanes/sql-builder"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "tsdown",
|
|
50
|
+
"emit": "cd ../../../../test/integration && node ../../packages/1-framework/3-tooling/cli/dist/cli.js contract emit --config test/sql-builder/fixtures/prisma-next.config.ts && cp test/sql-builder/fixtures/generated/contract.json test/sql-builder/fixtures/generated/contract.d.ts ../../packages/2-sql/4-lanes/sql-builder/test/fixtures/generated/",
|
|
51
|
+
"emit:check": "pnpm emit && git diff --exit-code test/fixtures/generated/",
|
|
52
|
+
"test": "vitest run --passWithNoTests",
|
|
53
|
+
"~test:coverage": "vitest run --coverage --passWithNoTests",
|
|
54
|
+
"typecheck": "tsc --noEmit",
|
|
55
|
+
"lint": "biome check . --error-on-warnings",
|
|
56
|
+
"lint:fix": "biome check --write .",
|
|
57
|
+
"lint:fix:unsafe": "biome check --write --unsafe .",
|
|
58
|
+
"clean": "rm -rf dist dist-tsc dist-tsc-prod coverage .tmp-output"
|
|
65
59
|
}
|
|
66
|
-
}
|
|
60
|
+
}
|
package/src/exports/types.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export type { AggregateFunctions, Expression, Functions } from '../expression';
|
|
2
2
|
export type { ResolveRow } from '../resolve';
|
|
3
3
|
export type { GatedMethod, QueryContext, Scope, ScopeField, Subquery } from '../scope';
|
|
4
|
-
export type { Db } from '../types/db';
|
|
4
|
+
export type { Db, TableProxyContract } from '../types/db';
|
|
5
5
|
export type { GroupedQuery } from '../types/grouped-query';
|
|
6
6
|
export type { DeleteQuery, InsertQuery, UpdateQuery } from '../types/mutation-query';
|
|
7
7
|
export type { SelectQuery } from '../types/select-query';
|
package/src/resolve.ts
CHANGED
|
@@ -1,14 +1,24 @@
|
|
|
1
1
|
import type { Expand, ScopeField } from './scope';
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
type ResolveField<
|
|
4
|
+
F extends ScopeField,
|
|
5
|
+
CodecTypes extends Record<string, { readonly output: unknown }>,
|
|
6
|
+
> = F['codecId'] extends keyof CodecTypes
|
|
7
|
+
? F['nullable'] extends true
|
|
8
|
+
? CodecTypes[F['codecId']]['output'] | null
|
|
9
|
+
: CodecTypes[F['codecId']]['output']
|
|
10
|
+
: unknown;
|
|
11
|
+
|
|
12
|
+
type ApplyNullable<T, F extends ScopeField> = F['nullable'] extends true ? T | null : T;
|
|
13
|
+
|
|
5
14
|
export type ResolveRow<
|
|
6
15
|
Row extends Record<string, ScopeField>,
|
|
7
16
|
CodecTypes extends Record<string, { readonly output: unknown }>,
|
|
17
|
+
PreResolved extends Record<string, unknown> = Record<string, never>,
|
|
8
18
|
> = Expand<{
|
|
9
|
-
-readonly [K in keyof Row]:
|
|
10
|
-
? Row[K]
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
19
|
+
-readonly [K in keyof Row]: string extends keyof PreResolved
|
|
20
|
+
? ResolveField<Row[K], CodecTypes>
|
|
21
|
+
: K extends keyof PreResolved
|
|
22
|
+
? ApplyNullable<NonNullable<PreResolved[K & keyof PreResolved]>, Row[K]>
|
|
23
|
+
: ResolveField<Row[K], CodecTypes>;
|
|
14
24
|
}>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { PlanMeta } from '@prisma-next/contract/types';
|
|
2
2
|
import type { StorageTable } from '@prisma-next/sql-contract/types';
|
|
3
|
+
import type { SqlOperationEntry } from '@prisma-next/sql-operations';
|
|
3
4
|
import {
|
|
4
5
|
AndExpr,
|
|
5
6
|
type AnyExpression as AstExpression,
|
|
@@ -14,7 +15,6 @@ import type {
|
|
|
14
15
|
AppliedMutationDefault,
|
|
15
16
|
MutationDefaultsOptions,
|
|
16
17
|
} from '@prisma-next/sql-relational-core/query-lane-context';
|
|
17
|
-
import type { QueryOperationEntry } from '@prisma-next/sql-relational-core/query-operations';
|
|
18
18
|
import type {
|
|
19
19
|
AggregateFunctions,
|
|
20
20
|
Expression,
|
|
@@ -74,7 +74,7 @@ export interface BuilderState {
|
|
|
74
74
|
|
|
75
75
|
export interface BuilderContext {
|
|
76
76
|
readonly capabilities: Record<string, Record<string, boolean>>;
|
|
77
|
-
readonly queryOperationTypes: Readonly<Record<string,
|
|
77
|
+
readonly queryOperationTypes: Readonly<Record<string, SqlOperationEntry>>;
|
|
78
78
|
readonly target: string;
|
|
79
79
|
readonly storageHash: string;
|
|
80
80
|
readonly applyMutationDefaults: (
|
package/src/runtime/functions.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { SqlOperationEntry } from '@prisma-next/sql-operations';
|
|
1
2
|
import {
|
|
2
3
|
AggregateExpr,
|
|
3
4
|
AndExpr,
|
|
@@ -13,7 +14,6 @@ import {
|
|
|
13
14
|
ParamRef,
|
|
14
15
|
SubqueryExpr,
|
|
15
16
|
} from '@prisma-next/sql-relational-core/ast';
|
|
16
|
-
import type { QueryOperationEntry } from '@prisma-next/sql-relational-core/query-operations';
|
|
17
17
|
import type {
|
|
18
18
|
AggregateFunctions,
|
|
19
19
|
AggregateOnlyFunctions,
|
|
@@ -129,7 +129,7 @@ function createAggregateOnlyFunctions() {
|
|
|
129
129
|
|
|
130
130
|
function createExtensionFunction(
|
|
131
131
|
name: string,
|
|
132
|
-
entry:
|
|
132
|
+
entry: SqlOperationEntry,
|
|
133
133
|
): (...args: ExprOrVal[]) => ExpressionImpl {
|
|
134
134
|
return (...args: ExprOrVal[]) => {
|
|
135
135
|
const resolvedArgs = args.map((arg, i) => {
|
|
@@ -143,10 +143,9 @@ function createExtensionFunction(
|
|
|
143
143
|
return new ExpressionImpl(
|
|
144
144
|
new OperationExpr({
|
|
145
145
|
method: name,
|
|
146
|
-
forTypeId: entry.args[0]?.codecId ?? 'unknown',
|
|
147
146
|
self,
|
|
148
147
|
args: restArgs.length > 0 ? restArgs : undefined,
|
|
149
|
-
returns:
|
|
148
|
+
returns: entry.returns,
|
|
150
149
|
lowering: entry.lowering,
|
|
151
150
|
}),
|
|
152
151
|
entry.returns,
|
|
@@ -155,7 +154,7 @@ function createExtensionFunction(
|
|
|
155
154
|
}
|
|
156
155
|
|
|
157
156
|
export function createFunctions<QC extends QueryContext>(
|
|
158
|
-
queryOperationTypes: Readonly<Record<string,
|
|
157
|
+
queryOperationTypes: Readonly<Record<string, SqlOperationEntry>>,
|
|
159
158
|
): Functions<QC> {
|
|
160
159
|
const builtins = createBuiltinFunctions();
|
|
161
160
|
|
|
@@ -174,7 +173,7 @@ export function createFunctions<QC extends QueryContext>(
|
|
|
174
173
|
}
|
|
175
174
|
|
|
176
175
|
export function createAggregateFunctions<QC extends QueryContext>(
|
|
177
|
-
queryOperationTypes: Readonly<Record<string,
|
|
176
|
+
queryOperationTypes: Readonly<Record<string, SqlOperationEntry>>,
|
|
178
177
|
): AggregateFunctions<QC> {
|
|
179
178
|
const baseFns = createFunctions<QC>(queryOperationTypes);
|
|
180
179
|
const aggregates = createAggregateOnlyFunctions();
|
package/src/runtime/index.ts
CHANGED
|
@@ -119,7 +119,7 @@ export class InsertQueryImpl<
|
|
|
119
119
|
},
|
|
120
120
|
);
|
|
121
121
|
|
|
122
|
-
build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes']>> {
|
|
122
|
+
build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {
|
|
123
123
|
const paramValues = buildParamValues(
|
|
124
124
|
this.#values,
|
|
125
125
|
this.#table,
|
|
@@ -134,7 +134,11 @@ export class InsertQueryImpl<
|
|
|
134
134
|
ast = ast.withReturning(buildReturningColumnRefs(this.#tableName, this.#returningColumns));
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
-
return buildQueryPlan<ResolveRow<RowType, QC['codecTypes']>>(
|
|
137
|
+
return buildQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(
|
|
138
|
+
ast,
|
|
139
|
+
this.#rowFields,
|
|
140
|
+
this.ctx,
|
|
141
|
+
);
|
|
138
142
|
}
|
|
139
143
|
}
|
|
140
144
|
|
|
@@ -210,7 +214,7 @@ export class UpdateQueryImpl<
|
|
|
210
214
|
},
|
|
211
215
|
);
|
|
212
216
|
|
|
213
|
-
build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes']>> {
|
|
217
|
+
build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {
|
|
214
218
|
const setParams = buildParamValues(
|
|
215
219
|
this.#setValues,
|
|
216
220
|
this.#table,
|
|
@@ -233,7 +237,11 @@ export class UpdateQueryImpl<
|
|
|
233
237
|
ast = ast.withReturning(buildReturningColumnRefs(this.#tableName, this.#returningColumns));
|
|
234
238
|
}
|
|
235
239
|
|
|
236
|
-
return buildQueryPlan<ResolveRow<RowType, QC['codecTypes']>>(
|
|
240
|
+
return buildQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(
|
|
241
|
+
ast,
|
|
242
|
+
this.#rowFields,
|
|
243
|
+
this.ctx,
|
|
244
|
+
);
|
|
237
245
|
}
|
|
238
246
|
}
|
|
239
247
|
|
|
@@ -299,7 +307,7 @@ export class DeleteQueryImpl<
|
|
|
299
307
|
},
|
|
300
308
|
);
|
|
301
309
|
|
|
302
|
-
build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes']>> {
|
|
310
|
+
build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {
|
|
303
311
|
const whereExpr = combineWhereExprs(
|
|
304
312
|
this.#whereCallbacks.map((cb) =>
|
|
305
313
|
evaluateWhere(cb, this.#scope, this.ctx.queryOperationTypes),
|
|
@@ -312,6 +320,10 @@ export class DeleteQueryImpl<
|
|
|
312
320
|
ast = ast.withReturning(buildReturningColumnRefs(this.#tableName, this.#returningColumns));
|
|
313
321
|
}
|
|
314
322
|
|
|
315
|
-
return buildQueryPlan<ResolveRow<RowType, QC['codecTypes']>>(
|
|
323
|
+
return buildQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(
|
|
324
|
+
ast,
|
|
325
|
+
this.#rowFields,
|
|
326
|
+
this.ctx,
|
|
327
|
+
);
|
|
316
328
|
}
|
|
317
329
|
}
|
|
@@ -124,8 +124,11 @@ abstract class QueryBase<
|
|
|
124
124
|
return buildSelectAst(this.state);
|
|
125
125
|
}
|
|
126
126
|
|
|
127
|
-
build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes']>> {
|
|
128
|
-
return buildPlan<ResolveRow<RowType, QC['codecTypes']>>(
|
|
127
|
+
build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>> {
|
|
128
|
+
return buildPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>(
|
|
129
|
+
this.state,
|
|
130
|
+
this.ctx,
|
|
131
|
+
);
|
|
129
132
|
}
|
|
130
133
|
}
|
|
131
134
|
|
package/src/runtime/sql.ts
CHANGED
|
@@ -1,20 +1,21 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Contract } from '@prisma-next/contract/types';
|
|
2
|
+
import type { SqlStorage } from '@prisma-next/sql-contract/types';
|
|
2
3
|
import type { ExecutionContext } from '@prisma-next/sql-relational-core/query-lane-context';
|
|
3
4
|
import type { Db } from '../types/db';
|
|
4
5
|
import type { BuilderContext } from './builder-base';
|
|
5
6
|
import { TableProxyImpl } from './table-proxy-impl';
|
|
6
7
|
|
|
7
|
-
export interface SqlOptions<C extends
|
|
8
|
+
export interface SqlOptions<C extends Contract<SqlStorage>> {
|
|
8
9
|
readonly context: ExecutionContext<C>;
|
|
9
10
|
}
|
|
10
11
|
|
|
11
|
-
export function sql<C extends
|
|
12
|
+
export function sql<C extends Contract<SqlStorage>>(options: SqlOptions<C>): Db<C> {
|
|
12
13
|
const { context } = options;
|
|
13
14
|
const ctx: BuilderContext = {
|
|
14
15
|
capabilities: context.contract.capabilities,
|
|
15
16
|
queryOperationTypes: context.queryOperations.entries(),
|
|
16
17
|
target: context.contract.target ?? 'unknown',
|
|
17
|
-
storageHash: context.contract.storageHash ?? 'unknown',
|
|
18
|
+
storageHash: context.contract.storage.storageHash ?? 'unknown',
|
|
18
19
|
applyMutationDefaults: (options) => context.applyMutationDefaults(options),
|
|
19
20
|
};
|
|
20
21
|
|
package/src/scope.ts
CHANGED
|
@@ -78,6 +78,7 @@ export type QueryContext = {
|
|
|
78
78
|
readonly codecTypes: CodecTypesBase;
|
|
79
79
|
readonly capabilities: Record<string, Record<string, boolean>>;
|
|
80
80
|
readonly queryOperationTypes: QueryOperationTypesBase;
|
|
81
|
+
readonly resolvedColumnOutputTypes: Record<string, unknown>;
|
|
81
82
|
};
|
|
82
83
|
|
|
83
84
|
export type { CodecTypesBase, StorageTable };
|
|
@@ -37,7 +37,7 @@ export interface InsertQuery<
|
|
|
37
37
|
...columns: Columns
|
|
38
38
|
) => InsertQuery<QC, AvailableScope, WithFields<EmptyRow, AvailableScope['topLevel'], Columns>>
|
|
39
39
|
>;
|
|
40
|
-
build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes']>>;
|
|
40
|
+
build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>;
|
|
41
41
|
}
|
|
42
42
|
|
|
43
43
|
export interface UpdateQuery<
|
|
@@ -53,7 +53,7 @@ export interface UpdateQuery<
|
|
|
53
53
|
...columns: Columns
|
|
54
54
|
) => UpdateQuery<QC, AvailableScope, WithFields<EmptyRow, AvailableScope['topLevel'], Columns>>
|
|
55
55
|
>;
|
|
56
|
-
build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes']>>;
|
|
56
|
+
build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>;
|
|
57
57
|
}
|
|
58
58
|
|
|
59
59
|
export interface DeleteQuery<
|
|
@@ -69,5 +69,5 @@ export interface DeleteQuery<
|
|
|
69
69
|
...columns: Columns
|
|
70
70
|
) => DeleteQuery<QC, AvailableScope, WithFields<EmptyRow, AvailableScope['topLevel'], Columns>>
|
|
71
71
|
>;
|
|
72
|
-
build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes']>>;
|
|
72
|
+
build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>;
|
|
73
73
|
}
|
package/src/types/shared.ts
CHANGED
|
@@ -117,5 +117,5 @@ export interface WithAlias<RowType extends Record<string, ScopeField>> {
|
|
|
117
117
|
}
|
|
118
118
|
|
|
119
119
|
export interface WithBuild<QC extends QueryContext, RowType extends Record<string, ScopeField>> {
|
|
120
|
-
build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes']>>;
|
|
120
|
+
build(): SqlQueryPlan<ResolveRow<RowType, QC['codecTypes'], QC['resolvedColumnOutputTypes']>>;
|
|
121
121
|
}
|