@prisma-next/sql-runtime 0.5.0-dev.4 → 0.5.0-dev.41
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/README.md +29 -21
- package/dist/exports-CrHMfIKo.mjs +1564 -0
- package/dist/exports-CrHMfIKo.mjs.map +1 -0
- package/dist/{index-yb51L_1h.d.mts → index-_dXSGeho.d.mts} +78 -25
- package/dist/index-_dXSGeho.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/test/utils.d.mts +6 -5
- package/dist/test/utils.d.mts.map +1 -1
- package/dist/test/utils.mjs +11 -5
- package/dist/test/utils.mjs.map +1 -1
- package/package.json +10 -12
- package/src/codecs/decoding.ts +294 -173
- package/src/codecs/encoding.ts +162 -37
- package/src/codecs/validation.ts +22 -3
- package/src/exports/index.ts +11 -7
- package/src/fingerprint.ts +22 -0
- package/src/guardrails/raw.ts +165 -0
- package/src/lower-sql-plan.ts +3 -3
- package/src/marker.ts +75 -0
- package/src/middleware/before-compile-chain.ts +1 -0
- package/src/middleware/budgets.ts +26 -96
- package/src/middleware/lints.ts +3 -3
- package/src/middleware/sql-middleware.ts +6 -5
- package/src/runtime-spi.ts +44 -0
- package/src/sql-context.ts +332 -78
- package/src/sql-family-adapter.ts +3 -2
- package/src/sql-marker.ts +62 -47
- package/src/sql-runtime.ts +332 -113
- package/dist/exports-BQZSVXXt.mjs +0 -981
- package/dist/exports-BQZSVXXt.mjs.map +0 -1
- package/dist/index-yb51L_1h.d.mts.map +0 -1
- package/test/async-iterable-result.test.ts +0 -141
- package/test/before-compile-chain.test.ts +0 -223
- package/test/budgets.test.ts +0 -431
- package/test/context.types.test-d.ts +0 -68
- package/test/execution-stack.test.ts +0 -161
- package/test/json-schema-validation.test.ts +0 -571
- package/test/lints.test.ts +0 -160
- package/test/mutation-default-generators.test.ts +0 -254
- package/test/parameterized-types.test.ts +0 -529
- package/test/sql-context.test.ts +0 -384
- package/test/sql-family-adapter.test.ts +0 -103
- package/test/sql-runtime.test.ts +0 -792
- package/test/utils.ts +0 -297
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"exports-CrHMfIKo.mjs","names":["lookup: CodecLookupForValidation","invalidCodecs: Array<{ table: string; column: string; codecId: string }>","details: Record<string, unknown>","parsed: unknown","lints: LintFinding[]","budgets: BudgetFinding[]","findings: LintFinding[]","codec","helpers: TypeHelperRegistry","ctx: SqlCodecInstanceContext","resolvedCodec: Codec | undefined","applied: AppliedMutationDefault[]","contributors: Array<SqlStaticContributions & ComponentDescriptor<string>>","options","ensureSchemaStatement: SqlStatement","ensureTableStatement: SqlStatement","params: readonly unknown[]","EMPTY_INCLUDE_ALIASES: ReadonlySet<string>","aliases: string[]","codec","parsed: unknown","cellCtx: SqlCodecCallContext","decoded: unknown","tasks: Promise<unknown>[]","includeIndices: { index: number; alias: string; value: unknown }[]","decoded: Record<string, unknown>","NO_METADATA: ParamMetadata","codec","metadata: ParamMetadata[]","tasks: Promise<unknown>[]","sqlCtx: SqlMiddlewareContext","codecCtx: SqlCodecCallContext","exec: SqlExecutionPlan","outcome: TelemetryOutcome | null","txContext: TransactionContext","result: R"],"sources":["../src/codecs/validation.ts","../src/lower-sql-plan.ts","../src/marker.ts","../src/middleware/budgets.ts","../src/guardrails/raw.ts","../src/middleware/lints.ts","../src/sql-context.ts","../src/sql-marker.ts","../src/codecs/json-schema-validation.ts","../src/codecs/decoding.ts","../src/codecs/encoding.ts","../src/fingerprint.ts","../src/middleware/before-compile-chain.ts","../src/sql-family-adapter.ts","../src/sql-runtime.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { CodecRegistry } from '@prisma-next/sql-relational-core/ast';\nimport type { CodecDescriptorRegistry } from '@prisma-next/sql-relational-core/query-lane-context';\n\nexport function extractCodecIds(contract: Contract<SqlStorage>): Set<string> {\n const codecIds = new Set<string>();\n\n for (const table of Object.values(contract.storage.tables)) {\n for (const column of Object.values(table.columns)) {\n const codecId = column.codecId;\n codecIds.add(codecId);\n }\n }\n\n return codecIds;\n}\n\nfunction extractCodecIdsFromColumns(contract: Contract<SqlStorage>): Map<string, string> {\n const codecIds = new Map<string, string>();\n\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n const codecId = column.codecId;\n const key = `${tableName}.${columnName}`;\n codecIds.set(key, codecId);\n }\n }\n\n return codecIds;\n}\n\ninterface CodecLookupForValidation {\n has(id: string): boolean;\n}\n\nfunction adaptDescriptorRegistry(registry: CodecDescriptorRegistry): CodecLookupForValidation {\n return { has: (id: string) => registry.descriptorFor(id) !== undefined };\n}\n\nfunction isDescriptorRegistry(\n registry: CodecRegistry | CodecDescriptorRegistry,\n): registry is CodecDescriptorRegistry {\n return 'descriptorFor' in registry;\n}\n\nexport function validateContractCodecMappings(\n registry: CodecRegistry | CodecDescriptorRegistry,\n contract: Contract<SqlStorage>,\n): void {\n const lookup: CodecLookupForValidation = isDescriptorRegistry(registry)\n ? adaptDescriptorRegistry(registry)\n : registry;\n\n const codecIds = extractCodecIdsFromColumns(contract);\n const invalidCodecs: Array<{ table: string; column: string; codecId: string }> = [];\n\n for (const [key, codecId] of codecIds.entries()) {\n if (!lookup.has(codecId)) {\n const parts = key.split('.');\n const table = parts[0] ?? '';\n const column = parts[1] ?? '';\n invalidCodecs.push({ table, column, codecId });\n }\n }\n\n if (invalidCodecs.length > 0) {\n const details: Record<string, unknown> = {\n contractTarget: contract.target,\n invalidCodecs,\n };\n\n throw runtimeError(\n 'RUNTIME.CODEC_MISSING',\n `Missing codec implementations for column codecIds: ${invalidCodecs.map((c) => `${c.table}.${c.column} (${c.codecId})`).join(', ')}`,\n details,\n );\n }\n}\n\nexport function validateCodecRegistryCompleteness(\n registry: CodecRegistry | CodecDescriptorRegistry,\n contract: Contract<SqlStorage>,\n): void {\n validateContractCodecMappings(registry, contract);\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { Adapter, AnyQueryAst, LoweredStatement } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\n\n/**\n * Lowers a SQL query plan to an executable Plan by calling the adapter's lower method.\n *\n * @param adapter - Adapter to lower AST to SQL\n * @param contract - Contract for lowering context\n * @param queryPlan - SQL query plan from a lane (contains AST, params, meta, but no SQL)\n * @returns Fully executable Plan with SQL string\n */\nexport function lowerSqlPlan<Row>(\n adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>,\n contract: Contract<SqlStorage>,\n queryPlan: SqlQueryPlan<Row>,\n): SqlExecutionPlan<Row> {\n const lowered = adapter.lower(queryPlan.ast, {\n contract,\n params: queryPlan.params,\n });\n\n return Object.freeze({\n sql: lowered.sql,\n params: lowered.params ?? queryPlan.params,\n ast: queryPlan.ast,\n meta: queryPlan.meta,\n });\n}\n","import type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport { type } from 'arktype';\n\nexport interface ContractMarkerRow {\n core_hash: string;\n profile_hash: string;\n contract_json: unknown | null;\n canonical_version: number | null;\n updated_at: Date;\n app_tag: string | null;\n meta: unknown | null;\n invariants: readonly string[];\n}\n\nconst MetaSchema = type({ '[string]': 'unknown' });\n\nfunction parseMeta(meta: unknown): Record<string, unknown> {\n if (meta === null || meta === undefined) {\n return {};\n }\n\n let parsed: unknown;\n if (typeof meta === 'string') {\n try {\n parsed = JSON.parse(meta);\n } catch {\n return {};\n }\n } else {\n parsed = meta;\n }\n\n const result = MetaSchema(parsed);\n if (result instanceof type.errors) {\n return {};\n }\n\n return result as Record<string, unknown>;\n}\n\nconst ContractMarkerRowSchema = type({\n core_hash: 'string',\n profile_hash: 'string',\n 'contract_json?': 'unknown | null',\n 'canonical_version?': 'number | null',\n 'updated_at?': 'Date | string',\n 'app_tag?': 'string | null',\n 'meta?': 'unknown | null',\n invariants: type('string').array(),\n});\n\nexport function parseContractMarkerRow(row: unknown): ContractMarkerRecord {\n const result = ContractMarkerRowSchema(row);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Invalid contract marker row: ${messages}`);\n }\n\n const updatedAt = result.updated_at\n ? result.updated_at instanceof Date\n ? result.updated_at\n : new Date(result.updated_at)\n : new Date();\n\n return {\n storageHash: result.core_hash,\n profileHash: result.profile_hash,\n contractJson: result.contract_json ?? null,\n canonicalVersion: result.canonical_version ?? null,\n updatedAt,\n appTag: result.app_tag ?? null,\n meta: parseMeta(result.meta),\n invariants: result.invariants,\n };\n}\n","import {\n type AfterExecuteResult,\n type RuntimeErrorEnvelope,\n runtimeError,\n} from '@prisma-next/framework-components/runtime';\nimport { isQueryAst, type SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport type { SqlMiddleware, SqlMiddlewareContext } from './sql-middleware';\n\nexport interface BudgetsOptions {\n readonly maxRows?: number;\n readonly defaultTableRows?: number;\n readonly tableRows?: Record<string, number>;\n readonly maxLatencyMs?: number;\n readonly severities?: {\n readonly rowCount?: 'warn' | 'error';\n readonly latency?: 'warn' | 'error';\n };\n}\n\nfunction hasAggregateWithoutGroupBy(ast: SelectAst): boolean {\n if (ast.groupBy !== undefined) {\n return false;\n }\n return ast.projection.some((item) => item.expr.kind === 'aggregate');\n}\n\nfunction primaryTableFromAst(ast: SelectAst): string | undefined {\n switch (ast.from.kind) {\n case 'table-source':\n return ast.from.name;\n case 'derived-table-source':\n return ast.from.alias;\n default:\n return undefined;\n }\n}\n\nfunction estimateRowsFromAst(\n ast: SelectAst,\n tableRows: Record<string, number>,\n defaultTableRows: number,\n hasAggregateWithoutGroup: boolean,\n): number | null {\n if (hasAggregateWithoutGroup) {\n return 1;\n }\n\n const table = primaryTableFromAst(ast);\n if (!table) {\n return null;\n }\n\n const tableEstimate = tableRows[table] ?? defaultTableRows;\n\n if (ast.limit !== undefined) {\n return Math.min(ast.limit, tableEstimate);\n }\n\n return tableEstimate;\n}\n\nfunction emitBudgetViolation(\n error: RuntimeErrorEnvelope,\n shouldBlock: boolean,\n ctx: SqlMiddlewareContext,\n): void {\n if (shouldBlock) {\n throw error;\n }\n ctx.log.warn({\n code: error.code,\n message: error.message,\n details: error.details,\n });\n}\n\nexport function budgets(options?: BudgetsOptions): SqlMiddleware {\n const maxRows = options?.maxRows ?? 10_000;\n const defaultTableRows = options?.defaultTableRows ?? 10_000;\n const tableRows = options?.tableRows ?? {};\n const maxLatencyMs = options?.maxLatencyMs ?? 1_000;\n const rowSeverity = options?.severities?.rowCount ?? 'error';\n\n const observedRowsByPlan = new WeakMap<SqlExecutionPlan, { count: number }>();\n\n return Object.freeze({\n name: 'budgets',\n familyId: 'sql' as const,\n\n async beforeExecute(plan: SqlExecutionPlan, ctx: SqlMiddlewareContext) {\n observedRowsByPlan.set(plan, { count: 0 });\n\n if (isQueryAst(plan.ast) && plan.ast.kind === 'select') {\n return evaluateSelectAst(plan.ast, ctx);\n }\n },\n\n async onRow(_row: Record<string, unknown>, plan: SqlExecutionPlan, _ctx: SqlMiddlewareContext) {\n const state = observedRowsByPlan.get(plan);\n if (!state) return;\n state.count += 1;\n if (state.count > maxRows) {\n throw runtimeError('BUDGET.ROWS_EXCEEDED', 'Observed row count exceeds budget', {\n source: 'observed',\n observedRows: state.count,\n maxRows,\n });\n }\n },\n\n async afterExecute(\n _plan: SqlExecutionPlan,\n result: AfterExecuteResult,\n ctx: SqlMiddlewareContext,\n ) {\n const latencyMs = result.latencyMs;\n if (latencyMs > maxLatencyMs) {\n const shouldBlock = ctx.mode === 'strict';\n emitBudgetViolation(\n runtimeError('BUDGET.TIME_EXCEEDED', 'Query latency exceeds budget', {\n latencyMs,\n maxLatencyMs,\n }),\n shouldBlock,\n ctx,\n );\n }\n },\n });\n\n function evaluateSelectAst(ast: SelectAst, ctx: SqlMiddlewareContext) {\n const hasAggNoGroup = hasAggregateWithoutGroupBy(ast);\n const estimated = estimateRowsFromAst(ast, tableRows, defaultTableRows, hasAggNoGroup);\n const isUnbounded = ast.limit === undefined && !hasAggNoGroup;\n const shouldBlock = rowSeverity === 'error' || ctx.mode === 'strict';\n\n if (isUnbounded) {\n if (estimated !== null && estimated >= maxRows) {\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Unbounded SELECT query exceeds budget', {\n source: 'ast',\n estimatedRows: estimated,\n maxRows,\n }),\n shouldBlock,\n ctx,\n );\n return;\n }\n\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Unbounded SELECT query exceeds budget', {\n source: 'ast',\n maxRows,\n }),\n shouldBlock,\n ctx,\n );\n return;\n }\n\n if (estimated !== null && estimated > maxRows) {\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Estimated row count exceeds budget', {\n source: 'ast',\n estimatedRows: estimated,\n maxRows,\n }),\n shouldBlock,\n ctx,\n );\n }\n }\n}\n","import type { PlanMeta } from '@prisma-next/contract/types';\n\nexport type LintSeverity = 'error' | 'warn';\nexport type BudgetSeverity = 'error' | 'warn';\n\nexport interface LintFinding {\n readonly code: `LINT.${string}`;\n readonly severity: LintSeverity;\n readonly message: string;\n readonly details?: Record<string, unknown>;\n}\n\nexport interface BudgetFinding {\n readonly code: `BUDGET.${string}`;\n readonly severity: BudgetSeverity;\n readonly message: string;\n readonly details?: Record<string, unknown>;\n}\n\nexport interface RawGuardrailConfig {\n readonly budgets?: {\n readonly unboundedSelectSeverity?: BudgetSeverity;\n readonly estimatedRows?: number;\n };\n}\n\nexport interface RawGuardrailResult {\n readonly lints: LintFinding[];\n readonly budgets: BudgetFinding[];\n readonly statement: 'select' | 'mutation' | 'other';\n}\n\n/**\n * Minimal plan view consumed by raw-SQL guardrails. Structurally satisfied\n * by `SqlExecutionPlan`; declared inline so this module stays decoupled\n * from a specific plan type at the call site.\n */\ninterface RawGuardrailPlan {\n readonly sql: string;\n readonly meta: PlanMeta;\n}\n\nconst SELECT_STAR_REGEX = /select\\s+\\*/i;\nconst LIMIT_REGEX = /\\blimit\\b/i;\nconst MUTATION_PREFIX_REGEX = /^(insert|update|delete|create|alter|drop|truncate)\\b/i;\n\nconst READ_ONLY_INTENTS = new Set(['read', 'report', 'readonly']);\n\nexport function evaluateRawGuardrails(\n plan: RawGuardrailPlan,\n config?: RawGuardrailConfig,\n): RawGuardrailResult {\n const lints: LintFinding[] = [];\n const budgets: BudgetFinding[] = [];\n\n const normalized = normalizeWhitespace(plan.sql);\n const statementType = classifyStatement(normalized);\n\n if (statementType === 'select') {\n if (SELECT_STAR_REGEX.test(normalized)) {\n lints.push(\n createLint('LINT.SELECT_STAR', 'error', 'Raw SQL plan selects all columns via *', {\n sql: snippet(plan.sql),\n }),\n );\n }\n\n if (!LIMIT_REGEX.test(normalized)) {\n const severity = config?.budgets?.unboundedSelectSeverity ?? 'error';\n lints.push(\n createLint('LINT.NO_LIMIT', 'warn', 'Raw SQL plan omits LIMIT clause', {\n sql: snippet(plan.sql),\n }),\n );\n\n budgets.push(\n createBudget(\n 'BUDGET.ROWS_EXCEEDED',\n severity,\n 'Raw SQL plan is unbounded and may exceed row budget',\n {\n sql: snippet(plan.sql),\n ...(config?.budgets?.estimatedRows !== undefined\n ? { estimatedRows: config.budgets.estimatedRows }\n : {}),\n },\n ),\n );\n }\n }\n\n if (isMutationStatement(statementType) && isReadOnlyIntent(plan.meta)) {\n lints.push(\n createLint(\n 'LINT.READ_ONLY_MUTATION',\n 'error',\n 'Raw SQL plan mutates data despite read-only intent',\n {\n sql: snippet(plan.sql),\n intent: plan.meta.annotations?.['intent'],\n },\n ),\n );\n }\n\n return { lints, budgets, statement: statementType };\n}\n\nfunction classifyStatement(sql: string): 'select' | 'mutation' | 'other' {\n const trimmed = sql.trim();\n const lower = trimmed.toLowerCase();\n\n if (lower.startsWith('with')) {\n if (lower.includes('select')) {\n return 'select';\n }\n }\n\n if (lower.startsWith('select')) {\n return 'select';\n }\n\n if (MUTATION_PREFIX_REGEX.test(trimmed)) {\n return 'mutation';\n }\n\n return 'other';\n}\n\nfunction isMutationStatement(statement: 'select' | 'mutation' | 'other'): boolean {\n return statement === 'mutation';\n}\n\nfunction isReadOnlyIntent(meta: PlanMeta): boolean {\n const annotations = meta.annotations as { intent?: string } | undefined;\n const intent =\n typeof annotations?.intent === 'string' ? annotations.intent.toLowerCase() : undefined;\n return intent !== undefined && READ_ONLY_INTENTS.has(intent);\n}\n\nfunction normalizeWhitespace(value: string): string {\n return value.replace(/\\s+/g, ' ').trim();\n}\n\nfunction snippet(sql: string): string {\n return normalizeWhitespace(sql).slice(0, 200);\n}\n\nfunction createLint(\n code: LintFinding['code'],\n severity: LintFinding['severity'],\n message: string,\n details?: Record<string, unknown>,\n): LintFinding {\n return { code, severity, message, ...(details ? { details } : {}) };\n}\n\nfunction createBudget(\n code: BudgetFinding['code'],\n severity: BudgetFinding['severity'],\n message: string,\n details?: Record<string, unknown>,\n): BudgetFinding {\n return { code, severity, message, ...(details ? { details } : {}) };\n}\n","import { runtimeError } from '@prisma-next/framework-components/runtime';\nimport {\n type AnyFromSource,\n type AnyQueryAst,\n isQueryAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { evaluateRawGuardrails } from '../guardrails/raw';\nimport type { SqlMiddleware, SqlMiddlewareContext } from './sql-middleware';\n\nexport interface LintsOptions {\n readonly severities?: {\n readonly selectStar?: 'warn' | 'error';\n readonly noLimit?: 'warn' | 'error';\n readonly deleteWithoutWhere?: 'warn' | 'error';\n readonly updateWithoutWhere?: 'warn' | 'error';\n readonly readOnlyMutation?: 'warn' | 'error';\n readonly unindexedPredicate?: 'warn' | 'error';\n };\n readonly fallbackWhenAstMissing?: 'raw' | 'skip';\n}\n\nexport interface LintFinding {\n readonly code: `LINT.${string}`;\n readonly severity: 'error' | 'warn';\n readonly message: string;\n readonly details?: Record<string, unknown>;\n}\n\nfunction getFromSourceTableDetail(source: AnyFromSource): string | undefined {\n switch (source.kind) {\n case 'table-source':\n return source.name;\n case 'derived-table-source':\n return source.alias;\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported source kind: ${(source satisfies never as { kind: string }).kind}`,\n );\n }\n}\n\nfunction evaluateAstLints(ast: AnyQueryAst): LintFinding[] {\n const findings: LintFinding[] = [];\n\n switch (ast.kind) {\n case 'delete':\n if (ast.where === undefined) {\n findings.push({\n code: 'LINT.DELETE_WITHOUT_WHERE',\n severity: 'error',\n message:\n 'DELETE without WHERE clause blocks execution to prevent accidental full-table deletion',\n details: { table: ast.table.name },\n });\n }\n break;\n\n case 'update':\n if (ast.where === undefined) {\n findings.push({\n code: 'LINT.UPDATE_WITHOUT_WHERE',\n severity: 'error',\n message:\n 'UPDATE without WHERE clause blocks execution to prevent accidental full-table update',\n details: { table: ast.table.name },\n });\n }\n break;\n\n case 'select':\n if (ast.limit === undefined) {\n const table = getFromSourceTableDetail(ast.from);\n findings.push({\n code: 'LINT.NO_LIMIT',\n severity: 'warn',\n message: 'Unbounded SELECT may return large result sets',\n ...ifDefined('details', table !== undefined ? { table } : undefined),\n });\n }\n if (ast.selectAllIntent !== undefined) {\n const table = ast.selectAllIntent.table;\n findings.push({\n code: 'LINT.SELECT_STAR',\n severity: 'warn',\n message: 'Query selects all columns via selectAll intent',\n ...ifDefined('details', table !== undefined ? { table } : undefined),\n });\n }\n break;\n\n case 'insert':\n break;\n\n // v8 ignore next 2\n default:\n throw new Error(`Unsupported AST kind: ${(ast satisfies never as { kind: string }).kind}`);\n }\n\n return findings;\n}\n\nfunction getConfiguredSeverity(code: string, options?: LintsOptions): 'warn' | 'error' | undefined {\n const severities = options?.severities;\n if (!severities) return undefined;\n\n switch (code) {\n case 'LINT.SELECT_STAR':\n return severities.selectStar;\n case 'LINT.NO_LIMIT':\n return severities.noLimit;\n case 'LINT.DELETE_WITHOUT_WHERE':\n return severities.deleteWithoutWhere;\n case 'LINT.UPDATE_WITHOUT_WHERE':\n return severities.updateWithoutWhere;\n case 'LINT.READ_ONLY_MUTATION':\n return severities.readOnlyMutation;\n case 'LINT.UNINDEXED_PREDICATE':\n return severities.unindexedPredicate;\n default:\n return undefined;\n }\n}\n\n/**\n * AST-first lint middleware for SQL plans. When `plan.ast` is a SQL QueryAst, inspects\n * the AST structurally. When `plan.ast` is missing, falls back to raw heuristic\n * guardrails or skips linting depending on `fallbackWhenAstMissing`.\n *\n * Rules (AST-based):\n * - DELETE without WHERE: blocks execution (configurable severity, default error)\n * - UPDATE without WHERE: blocks execution (configurable severity, default error)\n * - Unbounded SELECT: warn/error (severity from noLimit)\n * - SELECT * intent: warn/error (severity from selectStar)\n *\n * Fallback: When ast is missing, `fallbackWhenAstMissing: 'raw'` uses heuristic\n * SQL parsing; `'skip'` skips all lints. Default is `'raw'`.\n */\nexport function lints(options?: LintsOptions): SqlMiddleware {\n const fallback = options?.fallbackWhenAstMissing ?? 'raw';\n\n return Object.freeze({\n name: 'lints',\n familyId: 'sql' as const,\n\n async beforeExecute(plan: SqlExecutionPlan, ctx: SqlMiddlewareContext) {\n if (isQueryAst(plan.ast)) {\n const findings = evaluateAstLints(plan.ast);\n\n for (const lint of findings) {\n const configuredSeverity = getConfiguredSeverity(lint.code, options);\n const effectiveSeverity = configuredSeverity ?? lint.severity;\n\n if (effectiveSeverity === 'error') {\n throw runtimeError(lint.code, lint.message, lint.details);\n }\n if (effectiveSeverity === 'warn') {\n ctx.log.warn({\n code: lint.code,\n message: lint.message,\n details: lint.details,\n });\n }\n }\n return;\n }\n\n if (fallback === 'skip') {\n return;\n }\n\n const evaluation = evaluateRawGuardrails(plan);\n for (const lint of evaluation.lints) {\n const configuredSeverity = getConfiguredSeverity(lint.code, options);\n const effectiveSeverity = configuredSeverity ?? lint.severity;\n\n if (effectiveSeverity === 'error') {\n throw runtimeError(lint.code, lint.message, lint.details);\n }\n if (effectiveSeverity === 'warn') {\n ctx.log.warn({\n code: lint.code,\n message: lint.message,\n details: lint.details,\n });\n }\n }\n },\n });\n}\n","import type { Contract, ExecutionMutationDefaultValue } from '@prisma-next/contract/types';\nimport type { CodecDescriptor } from '@prisma-next/framework-components/codec';\nimport { synthesizeNonParameterizedDescriptor } from '@prisma-next/framework-components/codec';\nimport type { ComponentDescriptor } from '@prisma-next/framework-components/components';\nimport { checkContractComponentRequirements } from '@prisma-next/framework-components/components';\nimport {\n createExecutionStack,\n type ExecutionStack,\n type RuntimeAdapterDescriptor,\n type RuntimeAdapterInstance,\n type RuntimeDriverDescriptor,\n type RuntimeDriverInstance,\n type RuntimeExtensionDescriptor,\n type RuntimeExtensionInstance,\n type RuntimeTargetDescriptor,\n type RuntimeTargetInstance,\n} from '@prisma-next/framework-components/execution';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport {\n createSqlOperationRegistry,\n type SqlOperationDescriptor,\n} from '@prisma-next/sql-operations';\nimport type {\n Adapter,\n AnyQueryAst,\n Codec,\n CodecRegistry,\n ContractCodecRegistry,\n LoweredStatement,\n SqlCodecInstanceContext,\n SqlDriver,\n} from '@prisma-next/sql-relational-core/ast';\nimport { createCodecRegistry } from '@prisma-next/sql-relational-core/ast';\nimport type {\n AppliedMutationDefault,\n CodecDescriptorRegistry,\n ExecutionContext,\n JsonSchemaValidateFn,\n JsonSchemaValidatorRegistry,\n MutationDefaultsOptions,\n TypeHelperRegistry,\n} from '@prisma-next/sql-relational-core/query-lane-context';\n\n/**\n * Runtime parameterized codec descriptor.\n *\n * The unified `CodecDescriptor<P>` shape applied to parameterized codecs\n * — `paramsSchema: StandardSchemaV1<P>` for JSON-boundary validation,\n * `factory: (P) => (CodecInstanceContext) => Codec` for the curried higher-order codec.\n * The factory is called once per `storage.types` instance (or once per\n * inline-`typeParams` column); per-instance state lives in the closure.\n *\n * Codec-registry-unification spec § Decision.\n */\nexport type RuntimeParameterizedCodecDescriptor<P = Record<string, unknown>> = CodecDescriptor<P>;\n\nexport interface SqlStaticContributions {\n readonly codecs: () => CodecRegistry;\n // biome-ignore lint/suspicious/noExplicitAny: needed for covariance with concrete descriptor types\n readonly parameterizedCodecs: () => ReadonlyArray<RuntimeParameterizedCodecDescriptor<any>>;\n readonly queryOperations?: () => ReadonlyArray<SqlOperationDescriptor>;\n readonly mutationDefaultGenerators?: () => ReadonlyArray<RuntimeMutationDefaultGenerator>;\n}\n\nexport interface RuntimeMutationDefaultGenerator {\n readonly id: string;\n readonly generate: (params?: Record<string, unknown>) => unknown;\n}\n\nexport interface SqlRuntimeTargetDescriptor<\n TTargetId extends string = string,\n TTargetInstance extends RuntimeTargetInstance<'sql', TTargetId> = RuntimeTargetInstance<\n 'sql',\n TTargetId\n >,\n> extends RuntimeTargetDescriptor<'sql', TTargetId, TTargetInstance>,\n SqlStaticContributions {}\n\nexport interface SqlRuntimeAdapterDescriptor<\n TTargetId extends string = string,\n TAdapterInstance extends RuntimeAdapterInstance<\n 'sql',\n TTargetId\n > = SqlRuntimeAdapterInstance<TTargetId>,\n> extends RuntimeAdapterDescriptor<'sql', TTargetId, TAdapterInstance>,\n SqlStaticContributions {}\n\nexport interface SqlRuntimeExtensionDescriptor<TTargetId extends string = string>\n extends RuntimeExtensionDescriptor<'sql', TTargetId, SqlRuntimeExtensionInstance<TTargetId>>,\n SqlStaticContributions {\n create(): SqlRuntimeExtensionInstance<TTargetId>;\n}\n\nexport interface SqlExecutionStack<TTargetId extends string = string> {\n readonly target: SqlRuntimeTargetDescriptor<TTargetId>;\n readonly adapter: SqlRuntimeAdapterDescriptor<TTargetId>;\n readonly extensionPacks: readonly SqlRuntimeExtensionDescriptor<TTargetId>[];\n}\n\nexport type SqlExecutionStackWithDriver<TTargetId extends string = string> = Omit<\n ExecutionStack<\n 'sql',\n TTargetId,\n SqlRuntimeAdapterInstance<TTargetId>,\n SqlRuntimeDriverInstance<TTargetId>,\n SqlRuntimeExtensionInstance<TTargetId>\n >,\n 'target' | 'adapter' | 'driver' | 'extensionPacks'\n> & {\n readonly target: SqlRuntimeTargetDescriptor<TTargetId>;\n readonly adapter: SqlRuntimeAdapterDescriptor<TTargetId, SqlRuntimeAdapterInstance<TTargetId>>;\n readonly driver:\n | RuntimeDriverDescriptor<'sql', TTargetId, unknown, SqlRuntimeDriverInstance<TTargetId>>\n | undefined;\n readonly extensionPacks: readonly SqlRuntimeExtensionDescriptor<TTargetId>[];\n};\n\nexport interface SqlRuntimeExtensionInstance<TTargetId extends string>\n extends RuntimeExtensionInstance<'sql', TTargetId> {}\n\nexport type SqlRuntimeAdapterInstance<TTargetId extends string = string> = RuntimeAdapterInstance<\n 'sql',\n TTargetId\n> &\n Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>;\n\n/**\n * NOTE: Binding type is intentionally erased to unknown at this shared runtime layer.\n * Target clients (for example `postgres()`) validate and construct the concrete binding\n * before calling `driver.connect(binding)`, which keeps runtime behavior safe today.\n * A future follow-up can preserve TBinding through stack/context generics end-to-end.\n */\nexport type SqlRuntimeDriverInstance<TTargetId extends string = string> = RuntimeDriverInstance<\n 'sql',\n TTargetId\n> &\n SqlDriver<unknown>;\n\nexport function createSqlExecutionStack<TTargetId extends string>(options: {\n readonly target: SqlRuntimeTargetDescriptor<TTargetId>;\n readonly adapter: SqlRuntimeAdapterDescriptor<TTargetId>;\n readonly driver?:\n | RuntimeDriverDescriptor<'sql', TTargetId, unknown, SqlRuntimeDriverInstance<TTargetId>>\n | undefined;\n readonly extensionPacks?: readonly SqlRuntimeExtensionDescriptor<TTargetId>[] | undefined;\n}): SqlExecutionStackWithDriver<TTargetId> {\n return createExecutionStack({\n target: options.target,\n adapter: options.adapter,\n driver: options.driver,\n extensionPacks: options.extensionPacks,\n });\n}\n\nexport type { ExecutionContext, JsonSchemaValidatorRegistry, TypeHelperRegistry };\n\nexport function assertExecutionStackContractRequirements(\n contract: Contract<SqlStorage>,\n stack: SqlExecutionStack,\n): void {\n const providedComponentIds = new Set<string>([\n stack.target.id,\n stack.adapter.id,\n ...stack.extensionPacks.map((pack) => pack.id),\n ]);\n\n const result = checkContractComponentRequirements({\n contract,\n expectedTargetFamily: 'sql',\n expectedTargetId: stack.target.targetId,\n providedComponentIds,\n });\n\n if (result.familyMismatch) {\n throw runtimeError(\n 'RUNTIME.CONTRACT_FAMILY_MISMATCH',\n `Contract target family '${result.familyMismatch.actual}' does not match runtime family '${result.familyMismatch.expected}'.`,\n {\n actual: result.familyMismatch.actual,\n expected: result.familyMismatch.expected,\n },\n );\n }\n\n if (result.targetMismatch) {\n throw runtimeError(\n 'RUNTIME.CONTRACT_TARGET_MISMATCH',\n `Contract target '${result.targetMismatch.actual}' does not match runtime target descriptor '${result.targetMismatch.expected}'.`,\n {\n actual: result.targetMismatch.actual,\n expected: result.targetMismatch.expected,\n },\n );\n }\n\n if (result.missingExtensionPackIds.length > 0) {\n const packIds = result.missingExtensionPackIds;\n const packList = packIds.map((id) => `'${id}'`).join(', ');\n throw runtimeError(\n 'RUNTIME.MISSING_EXTENSION_PACK',\n `Contract requires extension pack(s) ${packList}, but runtime descriptors do not provide matching component(s).`,\n { packIds },\n );\n }\n}\n\nfunction validateTypeParams(\n typeParams: Record<string, unknown>,\n codecDescriptor: RuntimeParameterizedCodecDescriptor,\n context: { typeName?: string; tableName?: string; columnName?: string },\n): Record<string, unknown> {\n const result = codecDescriptor.paramsSchema['~standard'].validate(typeParams);\n if (result instanceof Promise) {\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `paramsSchema for codec '${codecDescriptor.codecId}' returned a Promise; runtime validation requires a synchronous Standard Schema validator.`,\n { ...context, codecId: codecDescriptor.codecId, typeParams },\n );\n }\n if (result.issues) {\n const messages = result.issues.map((issue) => issue.message).join('; ');\n const locationInfo = context.typeName\n ? `type '${context.typeName}'`\n : `column '${context.tableName}.${context.columnName}'`;\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `Invalid typeParams for ${locationInfo} (codecId: ${codecDescriptor.codecId}): ${messages}`,\n { ...context, codecId: codecDescriptor.codecId, typeParams },\n );\n }\n return result.value as Record<string, unknown>;\n}\n\nfunction collectParameterizedCodecDescriptors(\n contributors: ReadonlyArray<SqlStaticContributions>,\n): Map<string, RuntimeParameterizedCodecDescriptor> {\n const descriptors = new Map<string, RuntimeParameterizedCodecDescriptor>();\n\n for (const contributor of contributors) {\n for (const descriptor of contributor.parameterizedCodecs()) {\n if (descriptors.has(descriptor.codecId)) {\n throw runtimeError(\n 'RUNTIME.DUPLICATE_PARAMETERIZED_CODEC',\n `Duplicate parameterized codec descriptor for codecId '${descriptor.codecId}'.`,\n { codecId: descriptor.codecId },\n );\n }\n descriptors.set(descriptor.codecId, descriptor);\n }\n }\n\n return descriptors;\n}\n\n/**\n * Build the unified descriptor map. Combines parameterized descriptors\n * (which already ship as `CodecDescriptor`s) with synthesized descriptors\n * for non-parameterized codecs registered through the legacy `codecs:`\n * slot. Codec ids that ship a parameterized descriptor take precedence —\n * even when the legacy registry registers a representative codec under\n * the same id, the parameterized descriptor is the authoritative source.\n *\n * Codec-registry-unification spec § Decision: every codec resolves\n * through one descriptor map; reads are non-branching.\n */\nfunction buildCodecDescriptorRegistry(\n codecRegistry: CodecRegistry,\n parameterizedDescriptors: Map<string, RuntimeParameterizedCodecDescriptor>,\n): CodecDescriptorRegistry {\n type AnyDescriptor = CodecDescriptor<unknown>;\n const byId = new Map<string, AnyDescriptor>();\n const byTargetType = new Map<string, Array<AnyDescriptor>>();\n\n function registerInIndices(descriptor: AnyDescriptor): void {\n byId.set(descriptor.codecId, descriptor);\n for (const targetType of descriptor.targetTypes) {\n const list = byTargetType.get(targetType);\n if (list) {\n list.push(descriptor);\n } else {\n byTargetType.set(targetType, [descriptor]);\n }\n }\n }\n\n // The descriptor map is heterogeneous in `P` — each codec id has its own\n // params shape. The public `CodecDescriptorRegistry` interface widens to\n // `CodecDescriptor<unknown>` and consumers narrow per codec id at the\n // call site (the descriptor's `paramsSchema` validates JSON-sourced\n // params before the factory ever sees them, so the runtime narrow is\n // safe). The cast at registration goes through `unknown` because\n // `CodecDescriptor<P>` is invariant in `P` (the `factory` and\n // `renderOutputType` slots use `P` contravariantly).\n for (const descriptor of parameterizedDescriptors.values()) {\n registerInIndices(descriptor as unknown as AnyDescriptor);\n }\n\n for (const codec of codecRegistry.values()) {\n if (byId.has(codec.id)) continue;\n registerInIndices(synthesizeNonParameterizedDescriptor(codec) as unknown as AnyDescriptor);\n }\n\n return {\n descriptorFor(codecId: string): AnyDescriptor | undefined {\n return byId.get(codecId);\n },\n *values(): IterableIterator<AnyDescriptor> {\n yield* byId.values();\n },\n byTargetType(targetType: string): readonly AnyDescriptor[] {\n return byTargetType.get(targetType) ?? Object.freeze([]);\n },\n };\n}\n\nfunction collectTypeRefSites(\n storage: SqlStorage,\n): Map<string, Array<{ readonly table: string; readonly column: string }>> {\n const sites = new Map<string, Array<{ readonly table: string; readonly column: string }>>();\n for (const [tableName, table] of Object.entries(storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (typeof column.typeRef !== 'string') continue;\n const list = sites.get(column.typeRef);\n const entry = { table: tableName, column: columnName };\n if (list) {\n list.push(entry);\n } else {\n sites.set(column.typeRef, [entry]);\n }\n }\n }\n return sites;\n}\n\nfunction initializeTypeHelpers(\n storage: SqlStorage,\n codecDescriptors: Map<string, RuntimeParameterizedCodecDescriptor>,\n): TypeHelperRegistry {\n const helpers: TypeHelperRegistry = {};\n const storageTypes = storage.types;\n\n if (!storageTypes) {\n return helpers;\n }\n\n const typeRefSites = collectTypeRefSites(storage);\n\n for (const [typeName, typeInstance] of Object.entries(storageTypes)) {\n const descriptor = codecDescriptors.get(typeInstance.codecId);\n\n if (!descriptor) {\n // No parameterized descriptor for this codec id — store the raw\n // type instance for callers that need typeParams metadata.\n helpers[typeName] = typeInstance;\n continue;\n }\n\n const validatedParams = validateTypeParams(typeInstance.typeParams, descriptor, {\n typeName,\n });\n\n const usedAt = typeRefSites.get(typeName) ?? [];\n const ctx: SqlCodecInstanceContext = { name: typeName, usedAt };\n helpers[typeName] = descriptor.factory(validatedParams)(ctx);\n }\n\n return helpers;\n}\n\nfunction validateColumnTypeParams(\n storage: SqlStorage,\n codecDescriptors: Map<string, RuntimeParameterizedCodecDescriptor>,\n): void {\n for (const [tableName, table] of Object.entries(storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (column.typeParams) {\n const descriptor = codecDescriptors.get(column.codecId);\n if (descriptor) {\n validateTypeParams(column.typeParams, descriptor, { tableName, columnName });\n }\n }\n }\n }\n}\n\n/**\n * View of a codec that exposes a per-instance JSON-schema `validate`\n * function. Codecs declare this contract by including the\n * `'json-validator'` `CodecTrait` in their `traits` array; the trait is\n * the gate that lets `extractValidator` resolve from structurally-typed\n * `unknown` to this typed view.\n */\ntype JsonValidatorCodec = {\n readonly traits?: ReadonlyArray<unknown>;\n readonly validate: JsonSchemaValidateFn;\n};\n\nfunction hasJsonValidatorTrait(candidate: unknown): candidate is JsonValidatorCodec {\n if (candidate === null || typeof candidate !== 'object') return false;\n const traits = (candidate as { readonly traits?: unknown }).traits;\n if (!Array.isArray(traits)) return false;\n if (!traits.includes('json-validator')) return false;\n const validate = (candidate as { readonly validate?: unknown }).validate;\n return typeof validate === 'function';\n}\n\nfunction extractValidator(candidate: unknown): JsonSchemaValidateFn | undefined {\n return hasJsonValidatorTrait(candidate) ? candidate.validate : undefined;\n}\n\nfunction isResolvedCodec(candidate: unknown): candidate is Codec {\n return (\n candidate !== null &&\n typeof candidate === 'object' &&\n 'id' in candidate &&\n 'decode' in candidate\n );\n}\n\n/**\n * Walk the contract's `storage.tables[].columns[]` and resolve each\n * column to a `Codec` through the unified descriptor map. Per-instance\n * behavior:\n *\n * - **typeRef columns**: reuse the resolved codec materialized once by\n * `initializeTypeHelpers` for the `storage.types` entry. Multiple\n * columns sharing one typeRef share one codec instance.\n * - **inline-typeParams columns**: call `descriptor.factory(typeParams)\n * (ctx)` once per column (per-column anonymous instance).\n * - **non-parameterized columns**: call `descriptor.factory()(ctx)`\n * once. The synthesized descriptor's factory is constant — every call\n * returns the same shared codec instance — so columns sharing a non-\n * parameterized codec id share one resolved codec without explicit\n * caching.\n *\n * Combines what `initializeTypeHelpers` (named-instance walk) and the\n * old `buildJsonSchemaValidatorRegistry` (per-column walk) used to do\n * separately: one walk over all columns, one resolved codec per column,\n * one trait-gated validator extraction per column. The result drives\n * both the dispatch registry (`ContractCodecRegistry.forColumn`) and the\n * validator registry.\n *\n * Codec-registry-unification spec § AC-4: every column resolves through\n * one descriptor map without branching on parameterization.\n */\nfunction buildContractCodecRegistry(\n contract: Contract<SqlStorage>,\n codecDescriptors: CodecDescriptorRegistry,\n legacyCodecRegistry: CodecRegistry,\n types: TypeHelperRegistry,\n parameterizedDescriptors: Map<string, RuntimeParameterizedCodecDescriptor>,\n): {\n readonly registry: ContractCodecRegistry;\n readonly jsonValidators: JsonSchemaValidatorRegistry | undefined;\n} {\n const byColumn = new Map<string, Codec>();\n const byCodecId = new Map<string, Codec>();\n // Codec ids whose `byCodecId` entry is ambiguous — multiple distinct\n // resolved instances landed under the same parameterized codec id (e.g.\n // `Vector<1024>` and `Vector<1536>` both registering under\n // `pg/vector@1`). The encode-side `forCodecId` fallback rejects these\n // ids so a DSL-param without a column ref cannot silently bind to the\n // wrong instance. Retires when AC-5's `ParamRef.refs` plumbing lands\n // (TML-2357).\n const ambiguousCodecIds = new Set<string>();\n const validators = new Map<string, JsonSchemaValidateFn>();\n\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n const columnKey = `${tableName}.${columnName}`;\n const descriptor = codecDescriptors.descriptorFor(column.codecId);\n\n let resolvedCodec: Codec | undefined;\n\n if (descriptor) {\n const isParameterized = parameterizedDescriptors.has(column.codecId);\n\n if (column.typeRef) {\n // The named instance was already materialized once by\n // `initializeTypeHelpers`; reuse it so multiple columns sharing\n // the same typeRef share one codec instance (and any per-\n // instance helper state on it).\n const helper = types[column.typeRef];\n if (isResolvedCodec(helper)) {\n resolvedCodec = helper;\n }\n } else if (column.typeParams && isParameterized) {\n const parameterizedDescriptor = parameterizedDescriptors.get(column.codecId);\n if (parameterizedDescriptor) {\n const validatedParams = validateTypeParams(column.typeParams, parameterizedDescriptor, {\n tableName,\n columnName,\n });\n const ctx: SqlCodecInstanceContext = {\n name: `<anon:${tableName}.${columnName}>`,\n usedAt: [{ table: tableName, column: columnName }],\n };\n resolvedCodec = parameterizedDescriptor.factory(validatedParams)(ctx);\n }\n } else if (!isParameterized) {\n // Non-parameterized column. Cache the resolved codec by codec\n // id — the synthesized descriptor's factory is constant for\n // non-parameterized codecs, so columns sharing this codec id\n // share one resolved instance.\n let cached = byCodecId.get(column.codecId);\n if (!cached) {\n const ctx: SqlCodecInstanceContext = {\n name: `<shared:${column.codecId}>`,\n usedAt: [{ table: tableName, column: columnName }],\n };\n // `synthesizeNonParameterizedDescriptor` produces a\n // `CodecDescriptor<void>` whose factory ignores its params\n // and ctx; the runtime's `void` value is `undefined`. The\n // structural cast goes through `unknown` to satisfy the\n // heterogeneous-`P` registry boundary (the factory's\n // declared `P` is `any` here; the consumer narrows per\n // codec id). The cast narrows the descriptor's\n // family-agnostic `CodecInstanceContext` slot to the SQL\n // `SqlCodecInstanceContext` we pass at this call site —\n // function-argument contravariance makes the narrow safe\n // (a callee that accepts the base will also accept the\n // SQL extension). Per spec § Non-functional constraints.\n const voidFactory = descriptor.factory as unknown as (\n params: undefined,\n ) => (ctx: SqlCodecInstanceContext) => Codec;\n cached = voidFactory(undefined)(ctx);\n byCodecId.set(column.codecId, cached);\n }\n resolvedCodec = cached;\n }\n // else: parameterized codec id with no typeRef and no typeParams\n // — this is the legitimate \"undimensioned\" form for codecs that\n // ship a no-params column variant alongside a parameterized one\n // (e.g. pgvector's `vectorColumn` vs. `vector(N)`). Leave\n // `resolvedCodec` undefined; encode/decode for this column flows\n // through `forCodecId` (the AC-5-deferred carve-out documented\n // in `relational-core/src/ast/codec-types.ts`). The fallback\n // works for these cases because their wire format is\n // params-independent (vector formats `[v1,v2,...]` regardless\n // of declared length).\n }\n\n if (resolvedCodec) {\n byColumn.set(columnKey, resolvedCodec);\n const validate = extractValidator(resolvedCodec);\n if (validate) {\n validators.set(columnKey, validate);\n }\n const existing = byCodecId.get(column.codecId);\n if (existing === undefined) {\n byCodecId.set(column.codecId, resolvedCodec);\n } else if (existing !== resolvedCodec && parameterizedDescriptors.has(column.codecId)) {\n ambiguousCodecIds.add(column.codecId);\n }\n }\n }\n }\n\n const registry: ContractCodecRegistry = {\n forColumn(table, column) {\n return byColumn.get(`${table}.${column}`);\n },\n forCodecId(codecId) {\n // Codec-id-only fallback for sites without a column ref (encode-\n // side DSL params whose `ParamRef.refs` isn't populated). Prefer\n // the contract-walk-derived shared codec; fall back to the legacy\n // `codecRegistry.get` for parameterized codec ids whose contracts\n // don't have a typeRef/typeParams column the walk could resolve\n // through. The legacy fallback retires once `ParamRef.refs` is\n // threaded everywhere (TML-2357).\n //\n // Reject ambiguous parameterized fallbacks: if the contract walk\n // resolved more than one distinct codec instance under this id\n // (e.g. multiple vector dimensions, multiple arktype-json\n // schemas), the codec-id-keyed lookup cannot honor the call site\n // — fail fast rather than bind to whichever instance happened to\n // land first.\n if (ambiguousCodecIds.has(codecId)) {\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `Codec '${codecId}' resolves to multiple parameterized instances; column-aware dispatch is required.`,\n { codecId },\n );\n }\n return byCodecId.get(codecId) ?? legacyCodecRegistry.get(codecId);\n },\n };\n\n const jsonValidators: JsonSchemaValidatorRegistry | undefined =\n validators.size > 0\n ? {\n get: (key: string) => validators.get(key),\n size: validators.size,\n }\n : undefined;\n\n return { registry, jsonValidators };\n}\n\nfunction collectMutationDefaultGenerators(\n contributors: ReadonlyArray<SqlStaticContributions & { readonly id: string }>,\n): ReadonlyMap<string, RuntimeMutationDefaultGenerator> {\n const generators = new Map<string, RuntimeMutationDefaultGenerator>();\n const owners = new Map<string, string>();\n\n for (const contributor of contributors) {\n const nextGenerators = contributor.mutationDefaultGenerators?.() ?? [];\n for (const generator of nextGenerators) {\n const existingOwner = owners.get(generator.id);\n if (existingOwner !== undefined) {\n throw runtimeError(\n 'RUNTIME.DUPLICATE_MUTATION_DEFAULT_GENERATOR',\n `Duplicate mutation default generator '${generator.id}'.`,\n {\n id: generator.id,\n existingOwner,\n incomingOwner: contributor.id,\n },\n );\n }\n generators.set(generator.id, generator);\n owners.set(generator.id, contributor.id);\n }\n }\n\n return generators;\n}\n\nfunction computeExecutionDefaultValue(\n spec: ExecutionMutationDefaultValue,\n generatorRegistry: ReadonlyMap<string, RuntimeMutationDefaultGenerator>,\n): unknown {\n switch (spec.kind) {\n case 'generator': {\n const generator = generatorRegistry.get(spec.id);\n if (!generator) {\n throw runtimeError(\n 'RUNTIME.MUTATION_DEFAULT_GENERATOR_MISSING',\n `Contract references mutation default generator '${spec.id}' but no runtime component provides it.`,\n {\n id: spec.id,\n },\n );\n }\n // nosemgrep: javascript.express.security.express-wkhtml-injection.express-wkhtmltoimage-injection\n return generator.generate(spec.params);\n }\n }\n}\n\nfunction applyMutationDefaults(\n contract: Contract<SqlStorage>,\n generatorRegistry: ReadonlyMap<string, RuntimeMutationDefaultGenerator>,\n options: MutationDefaultsOptions,\n): ReadonlyArray<AppliedMutationDefault> {\n const defaults = contract.execution?.mutations.defaults ?? [];\n if (defaults.length === 0) {\n return [];\n }\n\n const applied: AppliedMutationDefault[] = [];\n const appliedColumns = new Set<string>();\n\n for (const mutationDefault of defaults) {\n if (mutationDefault.ref.table !== options.table) {\n continue;\n }\n\n const defaultSpec =\n options.op === 'create' ? mutationDefault.onCreate : mutationDefault.onUpdate;\n if (!defaultSpec) {\n continue;\n }\n\n const columnName = mutationDefault.ref.column;\n if (Object.hasOwn(options.values, columnName) || appliedColumns.has(columnName)) {\n continue;\n }\n\n applied.push({\n column: columnName,\n value: computeExecutionDefaultValue(defaultSpec, generatorRegistry),\n });\n appliedColumns.add(columnName);\n }\n\n return applied;\n}\n\nexport function createExecutionContext<\n TContract extends Contract<SqlStorage> = Contract<SqlStorage>,\n TTargetId extends string = string,\n>(options: {\n readonly contract: TContract;\n readonly stack: SqlExecutionStack<TTargetId>;\n}): ExecutionContext<TContract> {\n const { contract, stack } = options;\n\n assertExecutionStackContractRequirements(contract, stack);\n\n const codecRegistry = createCodecRegistry();\n\n const contributors: Array<SqlStaticContributions & ComponentDescriptor<string>> = [\n stack.target,\n stack.adapter,\n ...stack.extensionPacks,\n ];\n\n for (const contributor of contributors) {\n for (const c of contributor.codecs().values()) {\n codecRegistry.register(c);\n }\n }\n\n const queryOperationRegistry = createSqlOperationRegistry();\n for (const contributor of contributors) {\n for (const op of contributor.queryOperations?.() ?? []) {\n queryOperationRegistry.register(op);\n }\n }\n\n const parameterizedCodecDescriptors = collectParameterizedCodecDescriptors(contributors);\n const codecDescriptors = buildCodecDescriptorRegistry(\n codecRegistry,\n parameterizedCodecDescriptors,\n );\n const mutationDefaultGeneratorRegistry = collectMutationDefaultGenerators(contributors);\n\n if (parameterizedCodecDescriptors.size > 0) {\n validateColumnTypeParams(contract.storage, parameterizedCodecDescriptors);\n }\n\n const types = initializeTypeHelpers(contract.storage, parameterizedCodecDescriptors);\n\n const { registry: contractCodecs, jsonValidators: jsonSchemaValidators } =\n buildContractCodecRegistry(\n contract,\n codecDescriptors,\n codecRegistry,\n types,\n parameterizedCodecDescriptors,\n );\n\n return {\n contract,\n codecs: codecRegistry,\n contractCodecs,\n codecDescriptors,\n queryOperations: queryOperationRegistry,\n types,\n ...(jsonSchemaValidators ? { jsonSchemaValidators } : {}),\n applyMutationDefaults: (options) =>\n applyMutationDefaults(contract, mutationDefaultGeneratorRegistry, options),\n };\n}\n","import type { MarkerStatement } from '@prisma-next/sql-relational-core/ast';\n\nexport interface SqlStatement {\n readonly sql: string;\n readonly params: readonly unknown[];\n}\n\nexport interface WriteMarkerInput {\n readonly storageHash: string;\n readonly profileHash: string;\n readonly contractJson?: unknown;\n readonly canonicalVersion?: number;\n readonly appTag?: string;\n readonly meta?: Record<string, unknown>;\n /**\n * Applied-invariants set on the marker.\n *\n * - `undefined` → existing column left untouched. Sign and\n * verify-database paths use this; they don't accumulate invariants.\n * - explicit value (including `[]`) → column overwritten with\n * exactly that value.\n */\n readonly invariants?: readonly string[];\n}\n\nexport const ensureSchemaStatement: SqlStatement = {\n sql: 'create schema if not exists prisma_contract',\n params: [],\n};\n\nexport const ensureTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.marker (\n id smallint primary key default 1,\n core_hash text not null,\n profile_hash text not null,\n contract_json jsonb,\n canonical_version int,\n updated_at timestamptz not null default now(),\n app_tag text,\n meta jsonb not null default '{}',\n invariants text[] not null default '{}'\n )`,\n params: [],\n};\n\nexport function readContractMarker(): MarkerStatement {\n return {\n sql: `select\n core_hash,\n profile_hash,\n contract_json,\n canonical_version,\n updated_at,\n app_tag,\n meta,\n invariants\n from prisma_contract.marker\n where id = $1`,\n params: [1],\n };\n}\n\nexport interface WriteContractMarkerStatements {\n readonly insert: SqlStatement;\n readonly update: SqlStatement;\n}\n\n/**\n * Variable columns that participate in INSERT/UPDATE alongside the\n * always-on `id = $1` and `updated_at = now()`. Each column declares\n * its name, optional cast type, and parameter value; the placeholder\n * (`$N`) is computed positionally below — adding or reordering a\n * column doesn't desync indices. `invariants` only appears when the\n * caller supplies it — see `WriteMarkerInput.invariants`.\n */\nfunction markerColumns(\n input: WriteMarkerInput,\n): ReadonlyArray<{ readonly name: string; readonly type?: string; readonly param: unknown }> {\n return [\n { name: 'core_hash', param: input.storageHash },\n { name: 'profile_hash', param: input.profileHash },\n { name: 'contract_json', type: 'jsonb', param: input.contractJson ?? null },\n { name: 'canonical_version', param: input.canonicalVersion ?? null },\n { name: 'app_tag', param: input.appTag ?? null },\n { name: 'meta', type: 'jsonb', param: JSON.stringify(input.meta ?? {}) },\n ...(input.invariants !== undefined\n ? [{ name: 'invariants' as const, type: 'text[]' as const, param: input.invariants }]\n : []),\n ];\n}\n\nexport function writeContractMarker(input: WriteMarkerInput): WriteContractMarkerStatements {\n const cols = markerColumns(input);\n // $1 is reserved for `id`; subsequent positions follow the order of cols.\n const placed = cols.map((c, i) => ({\n name: c.name,\n expr: c.type ? `$${i + 2}::${c.type}` : `$${i + 2}`,\n param: c.param,\n }));\n const params: readonly unknown[] = [1, ...placed.map((c) => c.param)];\n\n // `updated_at = now()` is a SQL literal with no parameter slot, so it\n // sits outside `placed` and is appended directly to each statement.\n const insertColumns = ['id', ...placed.map((c) => c.name), 'updated_at'].join(', ');\n const insertValues = ['$1', ...placed.map((c) => c.expr), 'now()'].join(', ');\n const setClauses = [...placed.map((c) => `${c.name} = ${c.expr}`), 'updated_at = now()'].join(\n ', ',\n );\n\n return {\n insert: {\n sql: `insert into prisma_contract.marker (${insertColumns}) values (${insertValues})`,\n params,\n },\n update: {\n sql: `update prisma_contract.marker set ${setClauses} where id = $1`,\n params,\n },\n };\n}\n","import { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type {\n JsonSchemaValidationError,\n JsonSchemaValidatorRegistry,\n} from '@prisma-next/sql-relational-core/query-lane-context';\n\n/**\n * Validates a JSON value against its column's JSON Schema, if a validator exists.\n *\n * Throws `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` on validation failure.\n * No-ops if no validator is registered for the column.\n */\nexport function validateJsonValue(\n registry: JsonSchemaValidatorRegistry,\n table: string,\n column: string,\n value: unknown,\n direction: 'encode' | 'decode',\n codecId?: string,\n): void {\n const key = `${table}.${column}`;\n const validate = registry.get(key);\n if (!validate) return;\n\n const result = validate(value);\n if (result.valid) return;\n\n throw createJsonSchemaValidationError(table, column, direction, result.errors, codecId);\n}\n\nfunction createJsonSchemaValidationError(\n table: string,\n column: string,\n direction: 'encode' | 'decode',\n errors: ReadonlyArray<JsonSchemaValidationError>,\n codecId?: string,\n): Error {\n const summary = formatErrorSummary(errors);\n return runtimeError(\n 'RUNTIME.JSON_SCHEMA_VALIDATION_FAILED',\n `JSON schema validation failed for column '${table}.${column}' (${direction}): ${summary}`,\n {\n table,\n column,\n codecId,\n direction,\n errors: [...errors],\n },\n );\n}\n\nfunction formatErrorSummary(errors: ReadonlyArray<JsonSchemaValidationError>): string {\n if (errors.length === 0) return 'unknown validation error';\n if (errors.length === 1) {\n const err = errors[0] as JsonSchemaValidationError;\n return err.path === '/' ? err.message : `${err.path}: ${err.message}`;\n }\n return errors\n .map((err) => (err.path === '/' ? err.message : `${err.path}: ${err.message}`))\n .join('; ');\n}\n","import {\n checkAborted,\n isRuntimeError,\n raceAgainstAbort,\n runtimeError,\n} from '@prisma-next/framework-components/runtime';\nimport type {\n AnyQueryAst,\n Codec,\n CodecRegistry,\n ContractCodecRegistry,\n ProjectionItem,\n SqlCodecCallContext,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport type { JsonSchemaValidatorRegistry } from '@prisma-next/sql-relational-core/query-lane-context';\nimport { validateJsonValue } from './json-schema-validation';\n\ntype ColumnRef = { table: string; column: string };\n\ninterface DecodeContext {\n readonly aliases: ReadonlyArray<string> | undefined;\n readonly codecs: ReadonlyMap<string, Codec>;\n readonly columnRefs: ReadonlyMap<string, ColumnRef>;\n readonly includeAliases: ReadonlySet<string>;\n}\n\nconst WIRE_PREVIEW_LIMIT = 100;\nconst EMPTY_INCLUDE_ALIASES: ReadonlySet<string> = new Set<string>();\n\nfunction isAstBackedPlan(\n plan: SqlExecutionPlan,\n): plan is SqlExecutionPlan & { readonly ast: AnyQueryAst } {\n return plan.ast !== undefined;\n}\n\nfunction projectionListFromAst(ast: AnyQueryAst): ReadonlyArray<ProjectionItem> | undefined {\n if (ast.kind === 'select') {\n return ast.projection;\n }\n return ast.returning;\n}\n\n/**\n * Resolve the per-cell codec for a projection item.\n *\n * Phase B: when a `(table, column)` ref is available for the projection,\n * prefer `contractCodecs.forColumn(table, column)` — that's the per-\n * instance resolved codec materialized from the codec descriptor's\n * factory at context-construction time (carries any per-instance state\n * such as the compiled JSON-Schema validator). When the projection\n * resolves to a non-`column-ref` expression (computed projections, raw\n * SQL aliases) but still carries a codec id (ADR 205 stamps every\n * `ProjectionItem` with the producer's codec id), fall back to the\n * codec-id-keyed `forCodecId(codecId)` lookup, which itself falls back\n * to the legacy `CodecRegistry` for codec ids the contract walk\n * couldn't resolve.\n *\n * Codec-registry-unification spec § AC-4.\n */\nfunction resolveProjectionCodec(\n item: ProjectionItem,\n registry: CodecRegistry,\n contractCodecs: ContractCodecRegistry | undefined,\n): Codec | undefined {\n if (item.expr.kind === 'column-ref' && contractCodecs) {\n const byColumn = contractCodecs.forColumn(item.expr.table, item.expr.column);\n if (byColumn) return byColumn;\n }\n if (item.codecId) {\n const fromContract = contractCodecs?.forCodecId(item.codecId);\n if (fromContract) return fromContract;\n return registry.get(item.codecId);\n }\n return undefined;\n}\n\nfunction buildDecodeContext(\n plan: SqlExecutionPlan,\n registry: CodecRegistry,\n contractCodecs: ContractCodecRegistry | undefined,\n): DecodeContext {\n if (!isAstBackedPlan(plan)) {\n return {\n aliases: undefined,\n codecs: new Map(),\n columnRefs: new Map(),\n includeAliases: EMPTY_INCLUDE_ALIASES,\n };\n }\n\n const projection = projectionListFromAst(plan.ast);\n if (!projection) {\n return {\n aliases: undefined,\n codecs: new Map(),\n columnRefs: new Map(),\n includeAliases: EMPTY_INCLUDE_ALIASES,\n };\n }\n\n const aliases: string[] = [];\n const codecs = new Map<string, Codec>();\n const columnRefs = new Map<string, ColumnRef>();\n const includeAliases = new Set<string>();\n\n for (const item of projection) {\n aliases.push(item.alias);\n\n const codec = resolveProjectionCodec(item, registry, contractCodecs);\n if (codec) {\n codecs.set(item.alias, codec);\n }\n\n if (item.expr.kind === 'column-ref') {\n columnRefs.set(item.alias, { table: item.expr.table, column: item.expr.column });\n } else if (item.expr.kind === 'subquery' || item.expr.kind === 'json-array-agg') {\n includeAliases.add(item.alias);\n }\n }\n\n return { aliases, codecs, columnRefs, includeAliases };\n}\n\nfunction previewWireValue(wireValue: unknown): string {\n if (typeof wireValue === 'string') {\n return wireValue.length > WIRE_PREVIEW_LIMIT\n ? `${wireValue.substring(0, WIRE_PREVIEW_LIMIT)}...`\n : wireValue;\n }\n return String(wireValue).substring(0, WIRE_PREVIEW_LIMIT);\n}\n\nfunction isJsonSchemaValidationError(error: unknown): boolean {\n return isRuntimeError(error) && error.code === 'RUNTIME.JSON_SCHEMA_VALIDATION_FAILED';\n}\n\nfunction wrapDecodeFailure(\n error: unknown,\n alias: string,\n ref: ColumnRef | undefined,\n codec: Codec,\n wireValue: unknown,\n): never {\n const message = error instanceof Error ? error.message : String(error);\n const target = ref ? `${ref.table}.${ref.column}` : alias;\n const wrapped = runtimeError(\n 'RUNTIME.DECODE_FAILED',\n `Failed to decode column ${target} with codec '${codec.id}': ${message}`,\n {\n ...(ref ? { table: ref.table, column: ref.column } : { alias }),\n codec: codec.id,\n wirePreview: previewWireValue(wireValue),\n },\n );\n wrapped.cause = error;\n throw wrapped;\n}\n\nfunction wrapIncludeAggregateFailure(error: unknown, alias: string, wireValue: unknown): never {\n const message = error instanceof Error ? error.message : String(error);\n const wrapped = runtimeError(\n 'RUNTIME.DECODE_FAILED',\n `Failed to parse JSON array for include alias '${alias}': ${message}`,\n {\n alias,\n wirePreview: previewWireValue(wireValue),\n },\n );\n wrapped.cause = error;\n throw wrapped;\n}\n\nfunction decodeIncludeAggregate(alias: string, wireValue: unknown): unknown {\n if (wireValue === null || wireValue === undefined) {\n return [];\n }\n\n try {\n let parsed: unknown;\n if (typeof wireValue === 'string') {\n parsed = JSON.parse(wireValue);\n } else if (Array.isArray(wireValue)) {\n parsed = wireValue;\n } else {\n parsed = JSON.parse(String(wireValue));\n }\n\n if (!Array.isArray(parsed)) {\n throw new Error(`Expected array for include alias '${alias}', got ${typeof parsed}`);\n }\n\n return parsed;\n } catch (error) {\n wrapIncludeAggregateFailure(error, alias, wireValue);\n }\n}\n\n/**\n * Decodes a single field. Single-armed: every cell takes the same path —\n * `codec.decode → await → JSON-Schema validate → return plain value` — so\n * sync- and async-authored codecs are indistinguishable to callers.\n *\n * The row-level `rowCtx` is repackaged into a per-cell\n * `SqlCodecCallContext` whose `column = { table, name }` is a structural\n * projection of the per-cell `ColumnRef = { table, column }` resolved from\n * the AST-backed `DecodeContext` (the same resolution `wrapDecodeFailure`\n * uses for envelope construction — one resolution per cell, two consumers).\n * Cells the runtime cannot resolve to a single underlying column (aggregate\n * aliases, computed projections without a simple ref) get\n * `column: undefined`, matching the spec contract that the runtime never\n * silently defaults this field.\n */\nasync function decodeField(\n alias: string,\n wireValue: unknown,\n decodeCtx: DecodeContext,\n jsonValidators: JsonSchemaValidatorRegistry | undefined,\n rowCtx: SqlCodecCallContext,\n): Promise<unknown> {\n if (wireValue === null) {\n return null;\n }\n\n const codec = decodeCtx.codecs.get(alias);\n if (!codec) {\n return wireValue;\n }\n\n const ref = decodeCtx.columnRefs.get(alias);\n\n // Per-cell ctx: the cell-level `column` is a `SqlColumnRef = { table, name }`\n // projection of the resolved `ColumnRef = { table, column }` (same\n // resolution `wrapDecodeFailure` uses below — no double work). Cells the\n // runtime cannot resolve (aggregate aliases, computed projections without\n // a simple ref) drop the `column` field entirely — explicitly cleared so\n // a previously-populated `rowCtx.column` cannot leak through to unrelated\n // cells. Destructuring (rather than `column: undefined`) is required\n // because `SqlCodecCallContext.column` is declared `column?: SqlColumnRef`\n // under `exactOptionalPropertyTypes`.\n let cellCtx: SqlCodecCallContext;\n if (ref) {\n cellCtx = { ...rowCtx, column: { table: ref.table, name: ref.column } };\n } else {\n const { column: _drop, ...rowCtxWithoutColumn } = rowCtx;\n cellCtx = rowCtxWithoutColumn;\n }\n\n let decoded: unknown;\n try {\n decoded = await codec.decode(wireValue, cellCtx);\n } catch (error) {\n wrapDecodeFailure(error, alias, ref, codec, wireValue);\n }\n\n if (jsonValidators && ref) {\n try {\n validateJsonValue(jsonValidators, ref.table, ref.column, decoded, 'decode', codec.id);\n } catch (error) {\n if (isJsonSchemaValidationError(error)) throw error;\n wrapDecodeFailure(error, alias, ref, codec, wireValue);\n }\n }\n\n return decoded;\n}\n\n/**\n * Decodes a row by dispatching all per-cell codec calls concurrently via\n * `Promise.all`. Each cell follows the single-armed `decodeField` path.\n * Failures are wrapped in `RUNTIME.DECODE_FAILED` with `{ table, column,\n * codec }` (or `{ alias, codec }` when no column ref is resolvable) and the\n * original error attached on `cause`.\n *\n * When `rowCtx.signal` is provided:\n *\n * - **Already-aborted at entry** short-circuits with `RUNTIME.ABORTED`\n * (`{ phase: 'decode' }`) before any `codec.decode` call is made.\n * - **Mid-flight aborts** race the per-cell `Promise.all` against the\n * signal so the runtime returns promptly even when codec bodies ignore\n * it. In-flight bodies that ignore the signal complete in the\n * background (cooperative cancellation).\n * - Existing `RUNTIME.DECODE_FAILED` envelopes from codec bodies pass\n * through unchanged (no double wrap).\n */\nexport async function decodeRow(\n row: Record<string, unknown>,\n plan: SqlExecutionPlan,\n registry: CodecRegistry,\n jsonValidators: JsonSchemaValidatorRegistry | undefined,\n rowCtx: SqlCodecCallContext,\n contractCodecs?: ContractCodecRegistry,\n): Promise<Record<string, unknown>> {\n checkAborted(rowCtx, 'decode');\n const signal = rowCtx.signal;\n\n const decodeCtx = buildDecodeContext(plan, registry, contractCodecs);\n\n const aliases = decodeCtx.aliases ?? Object.keys(row);\n\n if (decodeCtx.aliases !== undefined) {\n for (const alias of decodeCtx.aliases) {\n if (!Object.hasOwn(row, alias)) {\n throw runtimeError('RUNTIME.DECODE_FAILED', `Row missing projection alias \"${alias}\"`, {\n alias,\n expectedAliases: decodeCtx.aliases,\n presentKeys: Object.keys(row),\n });\n }\n }\n }\n\n const tasks: Promise<unknown>[] = [];\n const includeIndices: { index: number; alias: string; value: unknown }[] = [];\n\n for (let i = 0; i < aliases.length; i++) {\n const alias = aliases[i] as string;\n const wireValue = row[alias];\n\n if (decodeCtx.includeAliases.has(alias)) {\n includeIndices.push({ index: i, alias, value: wireValue });\n tasks.push(Promise.resolve(undefined));\n continue;\n }\n\n tasks.push(decodeField(alias, wireValue, decodeCtx, jsonValidators, rowCtx));\n }\n\n const settled = await raceAgainstAbort(Promise.all(tasks), signal, 'decode');\n\n // Include aggregates are decoded synchronously after concurrent codec\n // dispatch settles, so any decode failures upstream propagate first.\n for (const entry of includeIndices) {\n settled[entry.index] = decodeIncludeAggregate(entry.alias, entry.value);\n }\n\n const decoded: Record<string, unknown> = {};\n for (let i = 0; i < aliases.length; i++) {\n decoded[aliases[i] as string] = settled[i];\n }\n return decoded;\n}\n","import {\n checkAborted,\n raceAgainstAbort,\n runtimeError,\n} from '@prisma-next/framework-components/runtime';\nimport {\n type Codec,\n type CodecRegistry,\n type ContractCodecRegistry,\n collectOrderedParamRefs,\n type SqlCodecCallContext,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\n\ninterface ParamMetadata {\n readonly codecId: string | undefined;\n readonly name: string | undefined;\n}\n\nconst NO_METADATA: ParamMetadata = Object.freeze({ codecId: undefined, name: undefined });\n\n/**\n * Resolve the codec for an outgoing param.\n *\n * Phase B (and AC-5-deferred carve-out): `ParamRef` does not carry a\n * `(table, column)` ref today — every `ParamRef` carries `codecId` but\n * not the column it relates to. Encode-side dispatch therefore consults\n * `contractCodecs.forCodecId(codecId)` (which itself prefers the\n * contract-walk-derived shared codec, falling back to the legacy\n * `CodecRegistry.get` for parameterized codec ids whose contracts don't\n * have a column the walk could resolve through).\n *\n * For the parameterized codecs shipped at Phase B (pgvector, postgres\n * json/jsonb), encode is per-instance-stateless w.r.t. params:\n * - pgvector formats `[v1,v2,...]` regardless of declared length;\n * - postgres json/jsonb encode is `JSON.stringify` regardless of schema.\n *\n * So the codec-id-keyed lookup yields a structurally equivalent encoder\n * even when the resolved per-instance codec carries extra state (e.g. a\n * compiled JSON-Schema validator used only by `decode`). TML-2357 retires\n * the fallback by threading `ParamRef.refs` through column-bound\n * construction sites.\n */\nfunction resolveParamCodec(\n metadata: ParamMetadata,\n registry: CodecRegistry,\n contractCodecs: ContractCodecRegistry | undefined,\n): Codec | undefined {\n if (!metadata.codecId) return undefined;\n const fromContract = contractCodecs?.forCodecId(metadata.codecId);\n if (fromContract) return fromContract;\n return registry.get(metadata.codecId);\n}\n\nfunction paramLabel(metadata: ParamMetadata, paramIndex: number): string {\n return metadata.name ?? `param[${paramIndex}]`;\n}\n\nfunction wrapEncodeFailure(\n error: unknown,\n metadata: ParamMetadata,\n paramIndex: number,\n codecId: string,\n): never {\n const label = paramLabel(metadata, paramIndex);\n const message = error instanceof Error ? error.message : String(error);\n const wrapped = runtimeError(\n 'RUNTIME.ENCODE_FAILED',\n `Failed to encode parameter ${label} with codec '${codecId}': ${message}`,\n { label, codec: codecId, paramIndex },\n );\n wrapped.cause = error;\n throw wrapped;\n}\n\n/**\n * Encodes a single parameter through its codec. Always awaits codec.encode so\n * a Promise can never leak into the driver, even if a sync-authored codec is\n * lifted to async by the codec() factory. Failures are wrapped in\n * `RUNTIME.ENCODE_FAILED` with `{ label, codec, paramIndex }` and the original\n * error attached on `cause`.\n *\n * `ctx` is forwarded verbatim to `codec.encode` so codec authors who opt\n * into the `(value, ctx)` arity see the same `SqlCodecCallContext` the\n * runtime built for the surrounding `runtime.execute()` call. The ctx is\n * always present; its `signal` field may be `undefined`. Encode call\n * sites do not populate `ctx.column` — encode-time column context is the\n * middleware's domain.\n */\nexport async function encodeParam(\n value: unknown,\n paramRef: { readonly codecId?: string; readonly name?: string },\n paramIndex: number,\n registry: CodecRegistry,\n ctx: SqlCodecCallContext,\n contractCodecs?: ContractCodecRegistry,\n): Promise<unknown> {\n return encodeParamValue(\n value,\n { codecId: paramRef.codecId, name: paramRef.name },\n paramIndex,\n registry,\n ctx,\n contractCodecs,\n );\n}\n\nasync function encodeParamValue(\n value: unknown,\n metadata: ParamMetadata,\n paramIndex: number,\n registry: CodecRegistry,\n ctx: SqlCodecCallContext,\n contractCodecs: ContractCodecRegistry | undefined,\n): Promise<unknown> {\n if (value === null || value === undefined) {\n return null;\n }\n\n const codec = resolveParamCodec(metadata, registry, contractCodecs);\n if (!codec) {\n return value;\n }\n\n try {\n return await codec.encode(value, ctx);\n } catch (error) {\n wrapEncodeFailure(error, metadata, paramIndex, codec.id);\n }\n}\n\n/**\n * Encodes all parameters concurrently via `Promise.all`. Per parameter, sync-\n * and async-authored codecs share the same path: `codec.encode → await →\n * return`. Param-level failures are wrapped in `RUNTIME.ENCODE_FAILED`.\n *\n * When `ctx.signal` is provided:\n *\n * - **Already-aborted at entry** short-circuits with `RUNTIME.ABORTED`\n * (`{ phase: 'encode' }`) before any `codec.encode` call is made — codecs\n * can pin this with a per-call counter that stays at zero.\n * - **Mid-flight abort** races the per-param `Promise.all` against\n * `abortable(ctx.signal)`. The runtime returns `RUNTIME.ABORTED` promptly\n * even if codec bodies ignore the signal; the in-flight bodies are\n * abandoned and run to completion in the background (cooperative\n * cancellation, see ADR 204).\n * - Existing `RUNTIME.ENCODE_FAILED` envelopes that surface from a codec\n * body before the runtime observes the abort pass through unchanged\n * (no double wrap).\n */\nexport async function encodeParams(\n plan: SqlExecutionPlan,\n registry: CodecRegistry,\n ctx: SqlCodecCallContext,\n contractCodecs?: ContractCodecRegistry,\n): Promise<readonly unknown[]> {\n checkAborted(ctx, 'encode');\n const signal = ctx.signal;\n\n if (plan.params.length === 0) {\n return plan.params;\n }\n\n const paramCount = plan.params.length;\n const metadata: ParamMetadata[] = new Array(paramCount).fill(NO_METADATA);\n\n if (plan.ast) {\n const refs = collectOrderedParamRefs(plan.ast);\n for (let i = 0; i < paramCount && i < refs.length; i++) {\n const ref = refs[i];\n if (ref) {\n metadata[i] = { codecId: ref.codecId, name: ref.name };\n }\n }\n }\n\n const tasks: Promise<unknown>[] = new Array(paramCount);\n for (let i = 0; i < paramCount; i++) {\n tasks[i] = encodeParamValue(\n plan.params[i],\n metadata[i] ?? NO_METADATA,\n i,\n registry,\n ctx,\n contractCodecs,\n );\n }\n\n const settled = await raceAgainstAbort(Promise.all(tasks), signal, 'encode');\n return Object.freeze(settled);\n}\n","import { createHash } from 'node:crypto';\n\nconst STRING_LITERAL_REGEX = /'(?:''|[^'])*'/g;\nconst NUMERIC_LITERAL_REGEX = /\\b\\d+(?:\\.\\d+)?\\b/g;\nconst WHITESPACE_REGEX = /\\s+/g;\n\n/**\n * Computes a literal-stripped, normalized fingerprint of a SQL statement.\n *\n * The function strips string and numeric literals, collapses whitespace, and\n * lowercases the result before hashing — so two structurally equivalent\n * statements (with different parameter values) produce the same fingerprint.\n * Used by SQL telemetry to group queries.\n */\nexport function computeSqlFingerprint(sql: string): string {\n const withoutStrings = sql.replace(STRING_LITERAL_REGEX, '?');\n const withoutNumbers = withoutStrings.replace(NUMERIC_LITERAL_REGEX, '?');\n const normalized = withoutNumbers.replace(WHITESPACE_REGEX, ' ').trim().toLowerCase();\n\n const hash = createHash('sha256').update(normalized).digest('hex');\n return `sha256:${hash}`;\n}\n","import type { DraftPlan, SqlMiddleware, SqlMiddlewareContext } from './sql-middleware';\n\nexport async function runBeforeCompileChain(\n middleware: readonly SqlMiddleware[],\n initial: DraftPlan,\n ctx: SqlMiddlewareContext,\n): Promise<DraftPlan> {\n let current = initial;\n for (const mw of middleware) {\n if (!mw.beforeCompile) {\n continue;\n }\n const result = await mw.beforeCompile(current, ctx);\n if (result === undefined) {\n continue;\n }\n if (result.ast === current.ast) {\n continue;\n }\n ctx.log.debug?.({\n event: 'middleware.rewrite',\n middleware: mw.name,\n lane: current.meta.lane,\n });\n current = result;\n }\n\n return current;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { ExecutionPlan } from '@prisma-next/framework-components/runtime';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { AdapterProfile } from '@prisma-next/sql-relational-core/ast';\nimport type { MarkerReader, RuntimeFamilyAdapter } from './runtime-spi';\n\nexport class SqlFamilyAdapter<TContract extends Contract<SqlStorage>>\n implements RuntimeFamilyAdapter<TContract>\n{\n readonly contract: TContract;\n readonly markerReader: MarkerReader;\n\n constructor(contract: TContract, adapterProfile: AdapterProfile) {\n this.contract = contract;\n this.markerReader = adapterProfile;\n }\n\n validatePlan(plan: ExecutionPlan, contract: TContract): void {\n if (plan.meta.target !== contract.target) {\n throw runtimeError('PLAN.TARGET_MISMATCH', 'Plan target does not match runtime target', {\n planTarget: plan.meta.target,\n runtimeTarget: contract.target,\n });\n }\n\n if (plan.meta.storageHash !== contract.storage.storageHash) {\n throw runtimeError(\n 'PLAN.HASH_MISMATCH',\n 'Plan storage hash does not match runtime contract',\n {\n planStorageHash: plan.meta.storageHash,\n runtimeStorageHash: contract.storage.storageHash,\n },\n );\n }\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type {\n ExecutionStackInstance,\n RuntimeDriverInstance,\n} from '@prisma-next/framework-components/execution';\nimport {\n AsyncIterableResult,\n checkAborted,\n checkMiddlewareCompatibility,\n RuntimeCore,\n type RuntimeExecuteOptions,\n type RuntimeLog,\n runtimeError,\n runWithMiddleware,\n} from '@prisma-next/framework-components/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type {\n Adapter,\n AnyQueryAst,\n CodecRegistry,\n ContractCodecRegistry,\n LoweredStatement,\n SqlCodecCallContext,\n SqlDriver,\n SqlQueryable,\n SqlTransaction,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type {\n CodecDescriptorRegistry,\n JsonSchemaValidatorRegistry,\n} from '@prisma-next/sql-relational-core/query-lane-context';\nimport type { RuntimeScope } from '@prisma-next/sql-relational-core/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { decodeRow } from './codecs/decoding';\nimport { encodeParams } from './codecs/encoding';\nimport { validateCodecRegistryCompleteness } from './codecs/validation';\nimport { computeSqlFingerprint } from './fingerprint';\nimport { lowerSqlPlan } from './lower-sql-plan';\nimport { runBeforeCompileChain } from './middleware/before-compile-chain';\nimport type { SqlMiddleware, SqlMiddlewareContext } from './middleware/sql-middleware';\nimport type {\n RuntimeFamilyAdapter,\n RuntimeTelemetryEvent,\n RuntimeVerifyOptions,\n TelemetryOutcome,\n} from './runtime-spi';\nimport type {\n ExecutionContext,\n SqlRuntimeAdapterInstance,\n SqlRuntimeExtensionInstance,\n} from './sql-context';\nimport { SqlFamilyAdapter } from './sql-family-adapter';\n\nexport type Log = RuntimeLog;\n\nexport interface RuntimeOptions<TContract extends Contract<SqlStorage> = Contract<SqlStorage>> {\n readonly context: ExecutionContext<TContract>;\n readonly adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>;\n readonly driver: SqlDriver<unknown>;\n readonly verify: RuntimeVerifyOptions;\n readonly middleware?: readonly SqlMiddleware[];\n readonly mode?: 'strict' | 'permissive';\n readonly log?: Log;\n}\n\nexport interface CreateRuntimeOptions<\n TContract extends Contract<SqlStorage> = Contract<SqlStorage>,\n TTargetId extends string = string,\n> {\n readonly stackInstance: ExecutionStackInstance<\n 'sql',\n TTargetId,\n SqlRuntimeAdapterInstance<TTargetId>,\n RuntimeDriverInstance<'sql', TTargetId>,\n SqlRuntimeExtensionInstance<TTargetId>\n >;\n readonly context: ExecutionContext<TContract>;\n readonly driver: SqlDriver<unknown>;\n readonly verify: RuntimeVerifyOptions;\n readonly middleware?: readonly SqlMiddleware[];\n readonly mode?: 'strict' | 'permissive';\n readonly log?: Log;\n}\n\nexport interface Runtime extends RuntimeQueryable {\n connection(): Promise<RuntimeConnection>;\n telemetry(): RuntimeTelemetryEvent | null;\n close(): Promise<void>;\n}\n\nexport interface RuntimeConnection extends RuntimeQueryable {\n transaction(): Promise<RuntimeTransaction>;\n /**\n * Returns the connection to the pool for reuse. Only call this when the\n * connection is known to be in a clean state. If a transaction\n * commit/rollback failed or the connection is otherwise suspect, call\n * `destroy(reason)` instead.\n */\n release(): Promise<void>;\n /**\n * Evicts the connection so it is never reused. Call this when the\n * connection may be in an indeterminate state (e.g. a failed rollback\n * leaving an open transaction, or a broken socket).\n *\n * If teardown fails the error is propagated and the connection remains\n * retryable, so the caller can decide whether to swallow the failure or\n * retry cleanup. Calling destroy() or release() more than once after a\n * successful teardown is caller error.\n *\n * `reason` is advisory context only. It may be surfaced to driver-level\n * observability hooks (e.g. pg-pool's `'release'` event) but does not\n * influence eviction behavior and is not rethrown.\n */\n destroy(reason?: unknown): Promise<void>;\n}\n\nexport interface RuntimeTransaction extends RuntimeQueryable {\n commit(): Promise<void>;\n rollback(): Promise<void>;\n}\n\nexport interface RuntimeQueryable extends RuntimeScope {}\n\nexport interface TransactionContext extends RuntimeQueryable {\n readonly invalidated: boolean;\n}\n\nexport type { RuntimeTelemetryEvent, RuntimeVerifyOptions, TelemetryOutcome };\n\nfunction isExecutionPlan(plan: SqlExecutionPlan | SqlQueryPlan): plan is SqlExecutionPlan {\n return 'sql' in plan;\n}\n\nclass SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorage>>\n extends RuntimeCore<SqlQueryPlan, SqlExecutionPlan, SqlMiddleware>\n implements Runtime\n{\n private readonly contract: TContract;\n private readonly adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>;\n private readonly driver: SqlDriver<unknown>;\n private readonly familyAdapter: RuntimeFamilyAdapter<Contract<SqlStorage>>;\n private readonly codecRegistry: CodecRegistry;\n private readonly contractCodecs: ContractCodecRegistry;\n private readonly codecDescriptors: CodecDescriptorRegistry;\n private readonly jsonSchemaValidators: JsonSchemaValidatorRegistry | undefined;\n private readonly sqlCtx: SqlMiddlewareContext;\n private readonly verify: RuntimeVerifyOptions;\n private codecRegistryValidated: boolean;\n private verified: boolean;\n private startupVerified: boolean;\n private _telemetry: RuntimeTelemetryEvent | null;\n\n constructor(options: RuntimeOptions<TContract>) {\n const { context, adapter, driver, verify, middleware, mode, log } = options;\n\n if (middleware) {\n for (const mw of middleware) {\n checkMiddlewareCompatibility(mw, 'sql', context.contract.target);\n }\n }\n\n const sqlCtx: SqlMiddlewareContext = {\n contract: context.contract,\n mode: mode ?? 'strict',\n now: () => Date.now(),\n log: log ?? {\n info: () => {},\n warn: () => {},\n error: () => {},\n },\n };\n\n super({ middleware: middleware ?? [], ctx: sqlCtx });\n\n this.contract = context.contract;\n this.adapter = adapter;\n this.driver = driver;\n this.familyAdapter = new SqlFamilyAdapter(context.contract, adapter.profile);\n this.codecRegistry = context.codecs;\n this.contractCodecs = context.contractCodecs;\n this.codecDescriptors = context.codecDescriptors;\n this.jsonSchemaValidators = context.jsonSchemaValidators;\n this.sqlCtx = sqlCtx;\n this.verify = verify;\n this.codecRegistryValidated = false;\n this.verified = verify.mode === 'startup' ? false : verify.mode === 'always';\n this.startupVerified = false;\n this._telemetry = null;\n\n if (verify.mode === 'startup') {\n validateCodecRegistryCompleteness(this.codecDescriptors, context.contract);\n this.codecRegistryValidated = true;\n }\n }\n\n /**\n * Lower a `SqlQueryPlan` (AST + meta) into a `SqlExecutionPlan` with\n * encoded parameters ready for the driver. This is the single point at\n * which params transition from app-layer values to driver wire-format.\n *\n * `ctx: SqlCodecCallContext` is forwarded to `encodeParams` so per-query\n * cancellation reaches every codec body during parameter encoding. The\n * framework abstract typed this as `CodecCallContext`; the SQL family\n * narrows it to the SQL-specific extension. SQL params do not populate\n * `ctx.column` — encode-side column metadata is the middleware's domain.\n */\n protected override async lower(\n plan: SqlQueryPlan,\n ctx: SqlCodecCallContext,\n ): Promise<SqlExecutionPlan> {\n const lowered = lowerSqlPlan(this.adapter, this.contract, plan);\n return Object.freeze({\n ...lowered,\n params: await encodeParams(lowered, this.codecRegistry, ctx, this.contractCodecs),\n });\n }\n\n /**\n * Default driver invocation. Production execution paths override the\n * queryable target (e.g. transaction or connection) by going through\n * `executeAgainstQueryable`; this implementation supports any caller of\n * `super.execute(plan)` and the abstract-base contract.\n */\n protected override runDriver(exec: SqlExecutionPlan): AsyncIterable<Record<string, unknown>> {\n return this.driver.execute<Record<string, unknown>>({\n sql: exec.sql,\n params: exec.params,\n });\n }\n\n /**\n * SQL pre-compile hook. Runs the registered middleware `beforeCompile`\n * chain over the plan's draft (AST + meta). Returns the original plan\n * unchanged when no middleware rewrote the AST; otherwise returns a new\n * plan carrying the rewritten AST and meta. The AST is the authoritative\n * source of execution metadata, so a rewrite needs no sidecar\n * reconciliation here — the lowering adapter and the encoder both walk\n * the rewritten AST directly.\n */\n protected override async runBeforeCompile(plan: SqlQueryPlan): Promise<SqlQueryPlan> {\n const rewrittenDraft = await runBeforeCompileChain(\n this.middleware,\n { ast: plan.ast, meta: plan.meta },\n this.sqlCtx,\n );\n return rewrittenDraft.ast === plan.ast\n ? plan\n : { ...plan, ast: rewrittenDraft.ast, meta: rewrittenDraft.meta };\n }\n\n override execute<Row>(\n plan: (SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>) & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n return this.executeAgainstQueryable<Row>(plan, this.driver, options);\n }\n\n private executeAgainstQueryable<Row>(\n plan: SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>,\n queryable: SqlQueryable,\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n this.ensureCodecRegistryValidated();\n\n const self = this;\n const signal = options?.signal;\n // One ctx per execute() call — the same reference is shared by\n // encodeParams (lower), decodeRow (per-row), and the stream loop's\n // between-row checks. Per-cell ctx allocations inside decodeField add\n // `column` for resolvable cells without re-wrapping the signal. The\n // ctx object is always allocated; the `signal` field is only included\n // when a signal was supplied (exactOptionalPropertyTypes).\n const codecCtx: SqlCodecCallContext = signal === undefined ? {} : { signal };\n\n const generator = async function* (): AsyncGenerator<Row, void, unknown> {\n checkAborted(codecCtx, 'stream');\n\n const exec: SqlExecutionPlan = isExecutionPlan(plan)\n ? Object.freeze({\n ...plan,\n params: await encodeParams(plan, self.codecRegistry, codecCtx, self.contractCodecs),\n })\n : await self.lower(await self.runBeforeCompile(plan), codecCtx);\n\n self.familyAdapter.validatePlan(exec, self.contract);\n self._telemetry = null;\n\n if (!self.startupVerified && self.verify.mode === 'startup') {\n await self.verifyMarker();\n }\n\n if (!self.verified && self.verify.mode === 'onFirstUse') {\n await self.verifyMarker();\n }\n\n const startedAt = Date.now();\n let outcome: TelemetryOutcome | null = null;\n\n try {\n if (self.verify.mode === 'always') {\n await self.verifyMarker();\n }\n\n const stream = runWithMiddleware<SqlExecutionPlan, Record<string, unknown>>(\n exec,\n self.middleware,\n self.ctx,\n () =>\n queryable.execute<Record<string, unknown>>({\n sql: exec.sql,\n params: exec.params,\n }),\n );\n\n // Manually drive the driver's async iterator so the between-row\n // abort check fires *before* requesting the next row. With a\n // `for await...of` loop the runtime would await `iterator.next()`\n // first, leaving a window where one extra row is pulled through\n // the driver after the signal aborted.\n const iterator = stream[Symbol.asyncIterator]();\n try {\n while (true) {\n checkAborted(codecCtx, 'stream');\n const next = await iterator.next();\n if (next.done) {\n break;\n }\n const decodedRow = await decodeRow(\n next.value,\n exec,\n self.codecRegistry,\n self.jsonSchemaValidators,\n codecCtx,\n self.contractCodecs,\n );\n yield decodedRow as Row;\n }\n } finally {\n // Best-effort iterator cleanup so the driver can release its\n // resources whether the stream finished normally, threw, or was\n // abandoned by the consumer.\n await iterator.return?.();\n }\n\n outcome = 'success';\n } catch (error) {\n outcome = 'runtime-error';\n throw error;\n } finally {\n if (outcome !== null) {\n self.recordTelemetry(exec, outcome, Date.now() - startedAt);\n }\n }\n };\n\n return new AsyncIterableResult(generator());\n }\n\n async connection(): Promise<RuntimeConnection> {\n const driverConn = await this.driver.acquireConnection();\n const self = this;\n\n const wrappedConnection: RuntimeConnection = {\n async transaction(): Promise<RuntimeTransaction> {\n const driverTx = await driverConn.beginTransaction();\n return self.wrapTransaction(driverTx);\n },\n async release(): Promise<void> {\n await driverConn.release();\n },\n async destroy(reason?: unknown): Promise<void> {\n await driverConn.destroy(reason);\n },\n execute<Row>(\n plan: (SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>) & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n return self.executeAgainstQueryable<Row>(plan, driverConn, options);\n },\n };\n\n return wrappedConnection;\n }\n\n private wrapTransaction(driverTx: SqlTransaction): RuntimeTransaction {\n const self = this;\n return {\n async commit(): Promise<void> {\n await driverTx.commit();\n },\n async rollback(): Promise<void> {\n await driverTx.rollback();\n },\n execute<Row>(\n plan: (SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>) & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n return self.executeAgainstQueryable<Row>(plan, driverTx, options);\n },\n };\n }\n\n telemetry(): RuntimeTelemetryEvent | null {\n return this._telemetry;\n }\n\n async close(): Promise<void> {\n await this.driver.close();\n }\n\n private ensureCodecRegistryValidated(): void {\n if (!this.codecRegistryValidated) {\n validateCodecRegistryCompleteness(this.codecDescriptors, this.contract);\n this.codecRegistryValidated = true;\n }\n }\n\n private async verifyMarker(): Promise<void> {\n if (this.verify.mode === 'always') {\n this.verified = false;\n }\n\n if (this.verified) {\n return;\n }\n\n const readStatement = this.familyAdapter.markerReader.readMarkerStatement();\n const result = await this.driver.query(readStatement.sql, readStatement.params);\n\n if (result.rows.length === 0) {\n if (this.verify.requireMarker) {\n throw runtimeError('CONTRACT.MARKER_MISSING', 'Contract marker not found in database');\n }\n\n this.verified = true;\n return;\n }\n\n const marker = this.familyAdapter.markerReader.parseMarkerRow(result.rows[0]);\n\n const contract = this.contract as {\n storage: { storageHash: string };\n execution?: { executionHash?: string | null };\n profileHash?: string | null;\n };\n\n if (marker.storageHash !== contract.storage.storageHash) {\n throw runtimeError(\n 'CONTRACT.MARKER_MISMATCH',\n 'Database storage hash does not match contract',\n {\n expected: contract.storage.storageHash,\n actual: marker.storageHash,\n },\n );\n }\n\n const expectedProfile = contract.profileHash ?? null;\n if (expectedProfile !== null && marker.profileHash !== expectedProfile) {\n throw runtimeError(\n 'CONTRACT.MARKER_MISMATCH',\n 'Database profile hash does not match contract',\n {\n expectedProfile,\n actualProfile: marker.profileHash,\n },\n );\n }\n\n this.verified = true;\n this.startupVerified = true;\n }\n\n private recordTelemetry(\n plan: SqlExecutionPlan,\n outcome: TelemetryOutcome,\n durationMs?: number,\n ): void {\n const contract = this.contract as { target: string };\n this._telemetry = Object.freeze({\n lane: plan.meta.lane,\n target: contract.target,\n fingerprint: computeSqlFingerprint(plan.sql),\n outcome,\n ...(durationMs !== undefined ? { durationMs } : {}),\n });\n }\n}\n\nfunction transactionClosedError(): Error {\n return runtimeError(\n 'RUNTIME.TRANSACTION_CLOSED',\n 'Cannot read from a query result after the transaction has ended. Await the result or call .toArray() inside the transaction callback.',\n {},\n );\n}\n\nexport async function withTransaction<R>(\n runtime: Runtime,\n fn: (tx: TransactionContext) => PromiseLike<R>,\n): Promise<R> {\n const connection = await runtime.connection();\n const transaction = await connection.transaction();\n\n let invalidated = false;\n const txContext: TransactionContext = {\n get invalidated() {\n return invalidated;\n },\n execute<Row>(\n plan: (SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>) & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n if (invalidated) {\n throw transactionClosedError();\n }\n const inner = transaction.execute(plan, options);\n const guarded = async function* (): AsyncGenerator<Row, void, unknown> {\n for await (const row of inner) {\n if (invalidated) {\n throw transactionClosedError();\n }\n yield row;\n }\n };\n return new AsyncIterableResult(guarded());\n },\n };\n\n let connectionDisposed = false;\n const destroyConnection = async (reason: unknown): Promise<void> => {\n if (connectionDisposed) return;\n connectionDisposed = true;\n // SqlConnection.destroy() propagates teardown errors so callers can\n // decide what to do with them. Here, we're already about to throw a\n // more informative error describing why we're evicting the connection\n // (rollback/commit failure), so swallowing the teardown error is the\n // right call — surfacing it would mask the original cause.\n await connection.destroy(reason).catch(() => undefined);\n };\n\n try {\n let result: R;\n try {\n result = await fn(txContext);\n } catch (error) {\n try {\n await transaction.rollback();\n } catch (rollbackError) {\n await destroyConnection(rollbackError);\n const wrapped = runtimeError(\n 'RUNTIME.TRANSACTION_ROLLBACK_FAILED',\n 'Transaction rollback failed after callback error',\n { rollbackError },\n );\n wrapped.cause = error;\n throw wrapped;\n }\n throw error;\n } finally {\n invalidated = true;\n }\n\n try {\n await transaction.commit();\n } catch (commitError) {\n // After a failed COMMIT the server-side transaction may be: (a) already\n // committed (error on response path), (b) already rolled back (deferred\n // constraint / serialization failure), or (c) still open (COMMIT never\n // reached the server). Attempt a best-effort rollback to cover (c) and\n // confirm the protocol is healthy.\n //\n // If rollback succeeds, the server is definitely no longer in a\n // transaction (no-op in (a)/(b), real cleanup in (c)) and we've just\n // proved the connection round-trips correctly — it's safe to return\n // to the pool. If rollback fails, the connection state is ambiguous\n // (broken socket, protocol desync, etc.) and we must destroy it.\n try {\n await transaction.rollback();\n } catch {\n await destroyConnection(commitError);\n }\n const wrapped = runtimeError(\n 'RUNTIME.TRANSACTION_COMMIT_FAILED',\n 'Transaction commit failed',\n { commitError },\n );\n wrapped.cause = commitError;\n throw wrapped;\n }\n return result;\n } finally {\n if (!connectionDisposed) {\n await connection.release();\n }\n }\n}\n\nexport function createRuntime<TContract extends Contract<SqlStorage>, TTargetId extends string>(\n options: CreateRuntimeOptions<TContract, TTargetId>,\n): Runtime {\n const { stackInstance, context, driver, verify, middleware, mode, log } = options;\n\n return new SqlRuntimeImpl({\n context,\n adapter: stackInstance.adapter,\n driver,\n verify,\n ...ifDefined('middleware', middleware),\n ...ifDefined('mode', mode),\n ...ifDefined('log', log),\n });\n}\n"],"mappings":";;;;;;;;;;;AAMA,SAAgB,gBAAgB,UAA6C;CAC3E,MAAM,2BAAW,IAAI,KAAa;AAElC,MAAK,MAAM,SAAS,OAAO,OAAO,SAAS,QAAQ,OAAO,CACxD,MAAK,MAAM,UAAU,OAAO,OAAO,MAAM,QAAQ,EAAE;EACjD,MAAM,UAA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YAAY,UAAU;WACtB;AACN,UAAM,kBAAkB,YAAY;;GAEtC,MAAM,UAAU,aACd,qCACA,6BACA,EAAE,aAAa,CAChB;AACD,WAAQ,QAAQ;AAChB,SAAM;;AAER,SAAO;WACC;AACR,MAAI,CAAC,mBACH,OAAM,WAAW,SAAS;;;AAKhC,SAAgB,cACd,SACS;CACT,MAAM,EAAE,eAAe,SAAS,QAAQ,QAAQ,YAAY,MAAM,QAAQ;AAE1E,QAAO,IAAI,eAAe;EACxB;EACA,SAAS,cAAc;EACvB;EACA;EACA,GAAG,UAAU,cAAc,WAAW;EACtC,GAAG,UAAU,QAAQ,KAAK;EAC1B,GAAG,UAAU,OAAO,IAAI;EACzB,CAAC"}
|
|
@@ -1,17 +1,18 @@
|
|
|
1
|
-
import { AfterExecuteResult, RuntimeMiddleware, RuntimeMiddlewareContext } from "@prisma-next/framework-components/runtime";
|
|
2
|
-
import { Adapter, AnyQueryAst,
|
|
3
|
-
import {
|
|
1
|
+
import { AfterExecuteResult, AfterExecuteResult as AfterExecuteResult$1, ExecutionPlan, RuntimeLog, RuntimeLog as Log, RuntimeMiddleware, RuntimeMiddlewareContext } from "@prisma-next/framework-components/runtime";
|
|
2
|
+
import { Adapter, AnyQueryAst, CodecRegistry, LoweredStatement, MarkerStatement, MarkerStatement as MarkerStatement$1, SqlDriver } from "@prisma-next/sql-relational-core/ast";
|
|
3
|
+
import { CodecDescriptor } from "@prisma-next/framework-components/codec";
|
|
4
4
|
import { ExecutionStack, ExecutionStackInstance, RuntimeAdapterDescriptor, RuntimeAdapterInstance, RuntimeDriverDescriptor, RuntimeDriverInstance, RuntimeExtensionDescriptor, RuntimeExtensionInstance, RuntimeTargetDescriptor, RuntimeTargetInstance } from "@prisma-next/framework-components/execution";
|
|
5
5
|
import { SqlOperationDescriptor } from "@prisma-next/sql-operations";
|
|
6
|
-
import { Contract,
|
|
6
|
+
import { Contract, ContractMarkerRecord, PlanMeta } from "@prisma-next/contract/types";
|
|
7
7
|
import { SqlStorage } from "@prisma-next/sql-contract/types";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
8
|
+
import { CodecDescriptorRegistry, ExecutionContext, TypeHelperRegistry } from "@prisma-next/sql-relational-core/query-lane-context";
|
|
9
|
+
import { SqlExecutionPlan, SqlQueryPlan } from "@prisma-next/sql-relational-core/plan";
|
|
10
|
+
import { RuntimeScope } from "@prisma-next/sql-relational-core/types";
|
|
10
11
|
|
|
11
12
|
//#region src/codecs/validation.d.ts
|
|
12
13
|
declare function extractCodecIds(contract: Contract<SqlStorage>): Set<string>;
|
|
13
|
-
declare function validateContractCodecMappings(registry: CodecRegistry, contract: Contract<SqlStorage>): void;
|
|
14
|
-
declare function validateCodecRegistryCompleteness(registry: CodecRegistry, contract: Contract<SqlStorage>): void;
|
|
14
|
+
declare function validateContractCodecMappings(registry: CodecRegistry | CodecDescriptorRegistry, contract: Contract<SqlStorage>): void;
|
|
15
|
+
declare function validateCodecRegistryCompleteness(registry: CodecRegistry | CodecDescriptorRegistry, contract: Contract<SqlStorage>): void;
|
|
15
16
|
//#endregion
|
|
16
17
|
//#region src/lower-sql-plan.d.ts
|
|
17
18
|
/**
|
|
@@ -22,7 +23,10 @@ declare function validateCodecRegistryCompleteness(registry: CodecRegistry, cont
|
|
|
22
23
|
* @param queryPlan - SQL query plan from a lane (contains AST, params, meta, but no SQL)
|
|
23
24
|
* @returns Fully executable Plan with SQL string
|
|
24
25
|
*/
|
|
25
|
-
declare function lowerSqlPlan<Row>(adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>, contract: Contract<SqlStorage>, queryPlan: SqlQueryPlan<Row>):
|
|
26
|
+
declare function lowerSqlPlan<Row>(adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>, contract: Contract<SqlStorage>, queryPlan: SqlQueryPlan<Row>): SqlExecutionPlan<Row>;
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region src/marker.d.ts
|
|
29
|
+
declare function parseContractMarkerRow(row: unknown): ContractMarkerRecord;
|
|
26
30
|
//#endregion
|
|
27
31
|
//#region src/middleware/sql-middleware.d.ts
|
|
28
32
|
interface SqlMiddlewareContext extends RuntimeMiddlewareContext {
|
|
@@ -36,7 +40,7 @@ interface DraftPlan {
|
|
|
36
40
|
readonly ast: AnyQueryAst;
|
|
37
41
|
readonly meta: PlanMeta;
|
|
38
42
|
}
|
|
39
|
-
interface SqlMiddleware extends RuntimeMiddleware {
|
|
43
|
+
interface SqlMiddleware extends RuntimeMiddleware<SqlExecutionPlan> {
|
|
40
44
|
readonly familyId?: 'sql';
|
|
41
45
|
/**
|
|
42
46
|
* Rewrite the query AST before it is lowered to SQL. Middlewares run in
|
|
@@ -57,9 +61,9 @@ interface SqlMiddleware extends RuntimeMiddleware {
|
|
|
57
61
|
* See `docs/architecture docs/subsystems/4. Runtime & Middleware Framework.md`.
|
|
58
62
|
*/
|
|
59
63
|
beforeCompile?(draft: DraftPlan, ctx: SqlMiddlewareContext): Promise<DraftPlan | undefined>;
|
|
60
|
-
beforeExecute?(plan:
|
|
61
|
-
onRow?(row: Record<string, unknown>, plan:
|
|
62
|
-
afterExecute?(plan:
|
|
64
|
+
beforeExecute?(plan: SqlExecutionPlan, ctx: SqlMiddlewareContext): Promise<void>;
|
|
65
|
+
onRow?(row: Record<string, unknown>, plan: SqlExecutionPlan, ctx: SqlMiddlewareContext): Promise<void>;
|
|
66
|
+
afterExecute?(plan: SqlExecutionPlan, result: AfterExecuteResult, ctx: SqlMiddlewareContext): Promise<void>;
|
|
63
67
|
}
|
|
64
68
|
//#endregion
|
|
65
69
|
//#region src/middleware/budgets.d.ts
|
|
@@ -103,19 +107,60 @@ interface LintsOptions {
|
|
|
103
107
|
*/
|
|
104
108
|
declare function lints(options?: LintsOptions): SqlMiddleware;
|
|
105
109
|
//#endregion
|
|
110
|
+
//#region src/runtime-spi.d.ts
|
|
111
|
+
/**
|
|
112
|
+
* Reader of the SQL contract marker. SQL runtimes verify the database's
|
|
113
|
+
* `prisma_contract.marker` row against the runtime's contract by issuing
|
|
114
|
+
* this statement before executing user queries (when `verify` is enabled).
|
|
115
|
+
* Each adapter is responsible for any target-specific row decoding before
|
|
116
|
+
* delegating to the shared row schema.
|
|
117
|
+
*/
|
|
118
|
+
interface MarkerReader {
|
|
119
|
+
readMarkerStatement(): MarkerStatement;
|
|
120
|
+
parseMarkerRow(row: unknown): ContractMarkerRecord;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* SQL family adapter SPI consumed by `SqlRuntime`. Encapsulates the
|
|
124
|
+
* runtime contract, marker reader, and plan validation logic so the
|
|
125
|
+
* runtime can be unit-tested without a concrete SQL adapter profile.
|
|
126
|
+
*
|
|
127
|
+
* Implemented by `SqlFamilyAdapter` for production and by mock classes
|
|
128
|
+
* in tests.
|
|
129
|
+
*/
|
|
130
|
+
interface RuntimeFamilyAdapter<TContract = unknown> {
|
|
131
|
+
readonly contract: TContract;
|
|
132
|
+
readonly markerReader: MarkerReader;
|
|
133
|
+
validatePlan(plan: ExecutionPlan, contract: TContract): void;
|
|
134
|
+
}
|
|
135
|
+
interface RuntimeVerifyOptions {
|
|
136
|
+
readonly mode: 'onFirstUse' | 'startup' | 'always';
|
|
137
|
+
readonly requireMarker: boolean;
|
|
138
|
+
}
|
|
139
|
+
type TelemetryOutcome = 'success' | 'runtime-error';
|
|
140
|
+
interface RuntimeTelemetryEvent {
|
|
141
|
+
readonly lane: string;
|
|
142
|
+
readonly target: string;
|
|
143
|
+
readonly fingerprint: string;
|
|
144
|
+
readonly outcome: TelemetryOutcome;
|
|
145
|
+
readonly durationMs?: number;
|
|
146
|
+
}
|
|
147
|
+
//#endregion
|
|
106
148
|
//#region src/sql-context.d.ts
|
|
107
149
|
/**
|
|
108
150
|
* Runtime parameterized codec descriptor.
|
|
109
|
-
* Provides validation schema and optional init hook for codecs that support type parameters.
|
|
110
|
-
* Used at runtime to validate typeParams and create type helpers.
|
|
111
151
|
*
|
|
112
|
-
*
|
|
113
|
-
*
|
|
152
|
+
* The unified `CodecDescriptor<P>` shape applied to parameterized codecs
|
|
153
|
+
* — `paramsSchema: StandardSchemaV1<P>` for JSON-boundary validation,
|
|
154
|
+
* `factory: (P) => (CodecInstanceContext) => Codec` for the curried higher-order codec.
|
|
155
|
+
* The factory is called once per `storage.types` instance (or once per
|
|
156
|
+
* inline-`typeParams` column); per-instance state lives in the closure.
|
|
157
|
+
*
|
|
158
|
+
* Codec-registry-unification spec § Decision.
|
|
114
159
|
*/
|
|
115
|
-
type RuntimeParameterizedCodecDescriptor<
|
|
160
|
+
type RuntimeParameterizedCodecDescriptor<P = Record<string, unknown>> = CodecDescriptor<P>;
|
|
116
161
|
interface SqlStaticContributions {
|
|
117
162
|
readonly codecs: () => CodecRegistry;
|
|
118
|
-
readonly parameterizedCodecs: () => ReadonlyArray<RuntimeParameterizedCodecDescriptor<any
|
|
163
|
+
readonly parameterizedCodecs: () => ReadonlyArray<RuntimeParameterizedCodecDescriptor<any>>;
|
|
119
164
|
readonly queryOperations?: () => ReadonlyArray<SqlOperationDescriptor>;
|
|
120
165
|
readonly mutationDefaultGenerators?: () => ReadonlyArray<RuntimeMutationDefaultGenerator>;
|
|
121
166
|
}
|
|
@@ -171,6 +216,15 @@ interface WriteMarkerInput {
|
|
|
171
216
|
readonly canonicalVersion?: number;
|
|
172
217
|
readonly appTag?: string;
|
|
173
218
|
readonly meta?: Record<string, unknown>;
|
|
219
|
+
/**
|
|
220
|
+
* Applied-invariants set on the marker.
|
|
221
|
+
*
|
|
222
|
+
* - `undefined` → existing column left untouched. Sign and
|
|
223
|
+
* verify-database paths use this; they don't accumulate invariants.
|
|
224
|
+
* - explicit value (including `[]`) → column overwritten with
|
|
225
|
+
* exactly that value.
|
|
226
|
+
*/
|
|
227
|
+
readonly invariants?: readonly string[];
|
|
174
228
|
}
|
|
175
229
|
declare const ensureSchemaStatement: SqlStatement;
|
|
176
230
|
declare const ensureTableStatement: SqlStatement;
|
|
@@ -182,6 +236,7 @@ interface WriteContractMarkerStatements {
|
|
|
182
236
|
declare function writeContractMarker(input: WriteMarkerInput): WriteContractMarkerStatements;
|
|
183
237
|
//#endregion
|
|
184
238
|
//#region src/sql-runtime.d.ts
|
|
239
|
+
type Log$1 = RuntimeLog;
|
|
185
240
|
interface CreateRuntimeOptions<TContract extends Contract<SqlStorage> = Contract<SqlStorage>, TTargetId extends string = string> {
|
|
186
241
|
readonly stackInstance: ExecutionStackInstance<'sql', TTargetId, SqlRuntimeAdapterInstance<TTargetId>, RuntimeDriverInstance<'sql', TTargetId>, SqlRuntimeExtensionInstance<TTargetId>>;
|
|
187
242
|
readonly context: ExecutionContext<TContract>;
|
|
@@ -189,7 +244,7 @@ interface CreateRuntimeOptions<TContract extends Contract<SqlStorage> = Contract
|
|
|
189
244
|
readonly verify: RuntimeVerifyOptions;
|
|
190
245
|
readonly middleware?: readonly SqlMiddleware[];
|
|
191
246
|
readonly mode?: 'strict' | 'permissive';
|
|
192
|
-
readonly log?: Log;
|
|
247
|
+
readonly log?: Log$1;
|
|
193
248
|
}
|
|
194
249
|
interface Runtime extends RuntimeQueryable {
|
|
195
250
|
connection(): Promise<RuntimeConnection>;
|
|
@@ -225,14 +280,12 @@ interface RuntimeTransaction extends RuntimeQueryable {
|
|
|
225
280
|
commit(): Promise<void>;
|
|
226
281
|
rollback(): Promise<void>;
|
|
227
282
|
}
|
|
228
|
-
interface RuntimeQueryable {
|
|
229
|
-
execute<Row = Record<string, unknown>>(plan: ExecutionPlan<Row> | SqlQueryPlan<Row>): AsyncIterableResult<Row>;
|
|
230
|
-
}
|
|
283
|
+
interface RuntimeQueryable extends RuntimeScope {}
|
|
231
284
|
interface TransactionContext extends RuntimeQueryable {
|
|
232
285
|
readonly invalidated: boolean;
|
|
233
286
|
}
|
|
234
287
|
declare function withTransaction<R>(runtime: Runtime, fn: (tx: TransactionContext) => PromiseLike<R>): Promise<R>;
|
|
235
288
|
declare function createRuntime<TContract extends Contract<SqlStorage>, TTargetId extends string>(options: CreateRuntimeOptions<TContract, TTargetId>): Runtime;
|
|
236
289
|
//#endregion
|
|
237
|
-
export {
|
|
238
|
-
//# sourceMappingURL=index-
|
|
290
|
+
export { createExecutionContext as A, budgets as B, SqlRuntimeAdapterInstance as C, SqlRuntimeTargetDescriptor as D, SqlRuntimeExtensionInstance as E, RuntimeVerifyOptions as F, extractCodecIds as G, SqlMiddlewareContext as H, TelemetryOutcome as I, validateCodecRegistryCompleteness as K, LintsOptions as L, MarkerReader as M, RuntimeFamilyAdapter as N, SqlStaticContributions as O, RuntimeTelemetryEvent as P, lints as R, SqlRuntimeAdapterDescriptor as S, SqlRuntimeExtensionDescriptor as T, parseContractMarkerRow as U, SqlMiddleware as V, lowerSqlPlan as W, ExecutionContext as _, Runtime as a, SqlExecutionStack as b, RuntimeTransaction as c, withTransaction as d, SqlStatement as f, writeContractMarker as g, readContractMarker as h, CreateRuntimeOptions as i, createSqlExecutionStack as j, TypeHelperRegistry as k, TransactionContext as l, ensureTableStatement as m, Log as n, RuntimeConnection as o, ensureSchemaStatement as p, validateContractCodecMappings as q, MarkerStatement$1 as r, RuntimeQueryable as s, AfterExecuteResult$1 as t, createRuntime as u, RuntimeMutationDefaultGenerator as v, SqlRuntimeDriverInstance as w, SqlExecutionStackWithDriver as x, RuntimeParameterizedCodecDescriptor as y, BudgetsOptions as z };
|
|
291
|
+
//# sourceMappingURL=index-_dXSGeho.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index-_dXSGeho.d.mts","names":[],"sources":["../src/codecs/validation.ts","../src/lower-sql-plan.ts","../src/marker.ts","../src/middleware/sql-middleware.ts","../src/middleware/budgets.ts","../src/middleware/lints.ts","../src/runtime-spi.ts","../src/sql-context.ts","../src/sql-marker.ts","../src/sql-runtime.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;iBAMgB,eAAA,WAA0B,SAAS,cAAc;iBAyCjD,6BAAA,WACJ,gBAAgB,mCAChB,SAAS;iBAgCL,iCAAA,WACJ,gBA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ONxGyC,CAAA,IAAA,CAAA;AAQtE;AAKiB,UM8FA,kBAAA,SAA2B,gBN9Fb,CAAA;EAA0B,MAAA,EAAA,EM+F7C,ON/F6C,CAAA,IAAA,CAAA;EAoBjC,QAAA,EAAA,EM4EV,ON5EU,CAAA,IAAA,CAAA;;AAA+C,UM+EtD,gBAAA,SAAyB,YN/E6B,CAAA;AAChD,UMgFN,kBAAA,SAA2B,gBNhFrB,CAAA;EAAuB,SAAA,WAAA,EAAA,OAAA;;AAGpC,iBMmcY,eNncZ,CAAA,CAAA,CAAA,CAAA,OAAA,EMocC,ONpcD,EAAA,EAAA,EAAA,CAAA,EAAA,EMqcC,kBNrcD,EAAA,GMqcwB,WNrcxB,CMqcoC,CNrcpC,CAAA,CAAA,EMscP,ONtcO,CMscC,CNtcD,CAAA;AACD,iBMuiBO,aNviBP,CAAA,kBMuiBuC,QNviBvC,CMuiBgD,UNviBhD,CAAA,EAAA,kBAAA,MAAA,CAAA,CAAA,OAAA,EMwiBE,oBNxiBF,CMwiBuB,SNxiBvB,EMwiBkC,SNxiBlC,CAAA,CAAA,EMyiBN,ONziBM"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
export { AfterExecuteResult, BudgetsOptions, CreateRuntimeOptions, ExecutionContext, LintsOptions, Log,
|
|
1
|
+
import { A as createExecutionContext, B as budgets, C as SqlRuntimeAdapterInstance, D as SqlRuntimeTargetDescriptor, E as SqlRuntimeExtensionInstance, F as RuntimeVerifyOptions, G as extractCodecIds, H as SqlMiddlewareContext, I as TelemetryOutcome, K as validateCodecRegistryCompleteness, L as LintsOptions, M as MarkerReader, N as RuntimeFamilyAdapter, O as SqlStaticContributions, P as RuntimeTelemetryEvent, R as lints, S as SqlRuntimeAdapterDescriptor, T as SqlRuntimeExtensionDescriptor, U as parseContractMarkerRow, V as SqlMiddleware, W as lowerSqlPlan, _ as ExecutionContext, a as Runtime, b as SqlExecutionStack, c as RuntimeTransaction, d as withTransaction, f as SqlStatement, g as writeContractMarker, h as readContractMarker, i as CreateRuntimeOptions, j as createSqlExecutionStack, k as TypeHelperRegistry, l as TransactionContext, m as ensureTableStatement, n as Log, o as RuntimeConnection, p as ensureSchemaStatement, q as validateContractCodecMappings, r as MarkerStatement, s as RuntimeQueryable, t as AfterExecuteResult, u as createRuntime, v as RuntimeMutationDefaultGenerator, w as SqlRuntimeDriverInstance, x as SqlExecutionStackWithDriver, y as RuntimeParameterizedCodecDescriptor, z as BudgetsOptions } from "./index-_dXSGeho.mjs";
|
|
2
|
+
export { AfterExecuteResult, BudgetsOptions, CreateRuntimeOptions, ExecutionContext, LintsOptions, Log, MarkerReader, MarkerStatement, Runtime, RuntimeConnection, RuntimeFamilyAdapter, RuntimeMutationDefaultGenerator, RuntimeParameterizedCodecDescriptor, RuntimeQueryable, RuntimeTelemetryEvent, RuntimeTransaction, RuntimeVerifyOptions, SqlExecutionStack, SqlExecutionStackWithDriver, SqlMiddleware, SqlMiddlewareContext, SqlRuntimeAdapterDescriptor, SqlRuntimeAdapterInstance, SqlRuntimeDriverInstance, SqlRuntimeExtensionDescriptor, SqlRuntimeExtensionInstance, SqlRuntimeTargetDescriptor, SqlStatement, SqlStaticContributions, TelemetryOutcome, TransactionContext, TypeHelperRegistry, budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, parseContractMarkerRow, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { a as readContractMarker, c as createSqlExecutionStack, d as
|
|
1
|
+
import { a as readContractMarker, c as createSqlExecutionStack, d as parseContractMarkerRow, f as lowerSqlPlan, h as validateContractCodecMappings, i as ensureTableStatement, l as lints, m as validateCodecRegistryCompleteness, n as withTransaction, o as writeContractMarker, p as extractCodecIds, r as ensureSchemaStatement, s as createExecutionContext, t as createRuntime, u as budgets } from "./exports-CrHMfIKo.mjs";
|
|
2
2
|
|
|
3
|
-
export { budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
|
|
3
|
+
export { budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, parseContractMarkerRow, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
|
package/dist/test/utils.d.mts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { C as SqlRuntimeAdapterInstance, D as SqlRuntimeTargetDescriptor, E as SqlRuntimeExtensionInstance, S as SqlRuntimeAdapterDescriptor, T as SqlRuntimeExtensionDescriptor, _ as ExecutionContext, f as SqlStatement, u as createRuntime, w as SqlRuntimeDriverInstance } from "../index-_dXSGeho.mjs";
|
|
2
|
+
import { ResultType } from "@prisma-next/framework-components/runtime";
|
|
2
3
|
import { Adapter, LoweredStatement, SelectAst } from "@prisma-next/sql-relational-core/ast";
|
|
3
4
|
import * as _prisma_next_framework_components_execution0 from "@prisma-next/framework-components/execution";
|
|
4
5
|
import { RuntimeDriverDescriptor } from "@prisma-next/framework-components/execution";
|
|
5
|
-
import { Contract
|
|
6
|
+
import { Contract } from "@prisma-next/contract/types";
|
|
6
7
|
import { DevDatabase, collectAsync, createDevDatabase, teardownTestDatabase, withClient } from "@prisma-next/test-utils";
|
|
7
8
|
import { SqlStorage } from "@prisma-next/sql-contract/types";
|
|
8
|
-
import { SqlQueryPlan } from "@prisma-next/sql-relational-core/plan";
|
|
9
|
+
import { SqlExecutionPlan, SqlQueryPlan } from "@prisma-next/sql-relational-core/plan";
|
|
9
10
|
import { Client } from "pg";
|
|
10
11
|
|
|
11
12
|
//#region test/utils.d.ts
|
|
@@ -15,12 +16,12 @@ import { Client } from "pg";
|
|
|
15
16
|
* This helper DRYs up the common pattern of executing plans in tests.
|
|
16
17
|
* The return type is inferred from the plan's type parameter.
|
|
17
18
|
*/
|
|
18
|
-
declare function executePlanAndCollect<P extends
|
|
19
|
+
declare function executePlanAndCollect<P extends SqlExecutionPlan<ResultType<P>> | SqlQueryPlan<ResultType<P>>>(runtime: ReturnType<typeof createRuntime>, plan: P): Promise<ResultType<P>[]>;
|
|
19
20
|
/**
|
|
20
21
|
* Drains a plan execution, consuming all results without collecting them.
|
|
21
22
|
* Useful for testing side effects without memory overhead.
|
|
22
23
|
*/
|
|
23
|
-
declare function drainPlanExecution(runtime: ReturnType<typeof createRuntime>, plan:
|
|
24
|
+
declare function drainPlanExecution(runtime: ReturnType<typeof createRuntime>, plan: SqlExecutionPlan | SqlQueryPlan<unknown>): Promise<void>;
|
|
24
25
|
/**
|
|
25
26
|
* Executes a SQL statement on a database client.
|
|
26
27
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.mts","names":[],"sources":["../../test/utils.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"utils.d.mts","names":[],"sources":["../../test/utils.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;AA8CA;;;AACY,iBADU,qBACV,CAAA,UAAA,gBAAA,CAAiB,UAAjB,CAA4B,CAA5B,CAAA,CAAA,GAAkC,YAAlC,CAA+C,UAA/C,CAA0D,CAA1D,CAAA,CAAA,CAAA,CAAA,OAAA,EACD,UADC,CAAA,OACiB,aADjB,CAAA,EAAA,IAAA,EACuC,CADvC,CAAA,EAC2C,OAD3C,CACmD,UADnD,CAC8D,CAD9D,CAAA,EAAA,CAAA;;;;;AACD,iBASW,kBAAA,CATX,OAAA,EAUA,UAVA,CAAA,OAUkB,aAVlB,CAAA,EAAA,IAAA,EAWH,gBAXG,GAWgB,YAXhB,CAAA,OAAA,CAAA,CAAA,EAYR,OAZQ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