@prisma-next/target-postgres 0.5.0 → 0.6.0-dev.3

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.
Files changed (30) hide show
  1. package/dist/control.mjs +2 -3
  2. package/dist/control.mjs.map +1 -1
  3. package/dist/{issue-planner-CiNmA4ls.mjs → issue-planner-DQ6WJkad.mjs} +7 -78
  4. package/dist/issue-planner-DQ6WJkad.mjs.map +1 -0
  5. package/dist/issue-planner.d.mts +3 -4
  6. package/dist/issue-planner.d.mts.map +1 -1
  7. package/dist/issue-planner.mjs +1 -1
  8. package/dist/migration.d.mts +21 -1
  9. package/dist/migration.d.mts.map +1 -1
  10. package/dist/migration.mjs +2 -2
  11. package/dist/{op-factory-call-Bs3HWhvG.mjs → op-factory-call-DeaFxa8_.mjs} +4 -5
  12. package/dist/{op-factory-call-Bs3HWhvG.mjs.map → op-factory-call-DeaFxa8_.mjs.map} +1 -1
  13. package/dist/{op-factory-call-BUhxZuUA.d.mts → op-factory-call-UFpUPJL6.d.mts} +3 -4
  14. package/dist/{op-factory-call-BUhxZuUA.d.mts.map → op-factory-call-UFpUPJL6.d.mts.map} +1 -1
  15. package/dist/op-factory-call.d.mts +1 -1
  16. package/dist/op-factory-call.mjs +1 -1
  17. package/dist/{planner-Lhacw3uU.mjs → planner-CYtKhLYa.mjs} +2 -2
  18. package/dist/{planner-Lhacw3uU.mjs.map → planner-CYtKhLYa.mjs.map} +1 -1
  19. package/dist/planner.mjs +1 -1
  20. package/dist/{tables-r9Zk1y-Y.mjs → tables-DgYIXjUt.mjs} +36 -2
  21. package/dist/tables-DgYIXjUt.mjs.map +1 -0
  22. package/package.json +14 -14
  23. package/src/core/migrations/issue-planner.ts +8 -32
  24. package/src/core/migrations/op-factory-call.ts +2 -3
  25. package/src/core/migrations/operations/dependencies.ts +52 -0
  26. package/src/core/migrations/planner-strategies.ts +4 -86
  27. package/src/exports/control.ts +0 -1
  28. package/src/exports/migration.ts +5 -1
  29. package/dist/issue-planner-CiNmA4ls.mjs.map +0 -1
  30. package/dist/tables-r9Zk1y-Y.mjs.map +0 -1
package/dist/control.mjs CHANGED
@@ -2,7 +2,7 @@ import { t as postgresTargetDescriptorMeta } from "./descriptor-meta-Dde_BS3K.mj
2
2
  import { t as parsePostgresDefault } from "./default-normalizer-C8XyZj85.mjs";
3
3
  import { t as normalizeSchemaNativeType } from "./native-type-normalizer-Cry4QoLf.mjs";
4
4
  import { o as renderDefaultLiteral } from "./planner-ddl-builders-CLB7Umhh.mjs";
5
- import { t as createPostgresMigrationPlanner } from "./planner-Lhacw3uU.mjs";
5
+ import { t as createPostgresMigrationPlanner } from "./planner-CYtKhLYa.mjs";
6
6
  import { a as ensureMarkerTableStatement, i as ensureLedgerTableStatement, n as buildLedgerInsertStatement, o as ensurePrismaContractSchemaStatement, r as buildMergeMarkerStatements } from "./statement-builders-BT889jV0.mjs";
7
7
  import { contractToSchemaIR, extractCodecControlHooks, runnerFailure, runnerSuccess } from "@prisma-next/family-sql/control";
8
8
  import { ifDefined } from "@prisma-next/utils/defined";
@@ -411,8 +411,7 @@ const postgresTargetDescriptor = {
411
411
  return contractToSchemaIR(contract, {
412
412
  annotationNamespace: "pg",
413
413
  ...ifDefined("expandNativeType", buildNativeTypeExpander(frameworkComponents)),
414
- renderDefault: postgresRenderDefault,
415
- frameworkComponents: frameworkComponents ?? []
414
+ renderDefault: postgresRenderDefault
416
415
  });
417
416
  }
418
417
  },
@@ -1 +1 @@
1
- {"version":3,"file":"control.mjs","names":[],"sources":["../src/core/migrations/runner.ts","../src/exports/control.ts"],"sourcesContent":["import type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n MultiSpaceRunnerResult,\n SqlControlFamilyInstance,\n SqlMigrationPlanContractInfo,\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n SqlMigrationRunner,\n SqlMigrationRunnerExecuteOptions,\n SqlMigrationRunnerFailure,\n SqlMigrationRunnerResult,\n SqlMigrationRunnerSuccessValue,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { ControlDriverInstance } from '@prisma-next/framework-components/control';\nimport { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok, okVoid } from '@prisma-next/utils/result';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\nimport {\n buildLedgerInsertStatement,\n buildMergeMarkerStatements,\n ensureLedgerTableStatement,\n ensureMarkerTableStatement,\n ensurePrismaContractSchemaStatement,\n type SqlStatement,\n} from './statement-builders';\n\ninterface RunnerConfig {\n readonly defaultSchema: string;\n}\n\ninterface ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n}\n\nconst DEFAULT_CONFIG: RunnerConfig = {\n defaultSchema: 'public',\n};\n\nconst LOCK_DOMAIN = 'prisma_next.contract.marker';\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n // Clone array (shallow clone of array elements)\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n // Recursively clone nested objects\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n // Primitives are copied as-is\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n config: Partial<RunnerConfig> = {},\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family, { ...DEFAULT_CONFIG, ...config });\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(\n private readonly family: SqlControlFamilyInstance,\n private readonly config: RunnerConfig,\n ) {}\n\n async execute(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const driver = options.driver;\n\n // Static checks fail fast before any transaction work — no point\n // burning a BEGIN/ROLLBACK round-trip on a destination-contract\n // mismatch the caller can fix locally.\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) return destinationCheck;\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) return policyCheck;\n\n await this.beginTransaction(driver);\n let committed = false;\n try {\n const result = await this.executeOnConnection(options);\n if (!result.ok) {\n return result;\n }\n await this.commitTransaction(driver);\n committed = true;\n return result;\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n /**\n * Body of the migration runner without transaction management. The\n * caller (single-space `execute(...)` above, or the multi-space\n * outer-tx orchestrator at the SQL family level) owns the\n * `BEGIN`/`COMMIT`/`ROLLBACK` lifecycle.\n */\n async executeOnConnection(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema = options.schemaName ?? this.config.defaultSchema;\n const driver = options.driver;\n if (options.space !== undefined && options.space !== options.plan.spaceId) {\n throw new Error(\n `SqlMigrationRunner: options.space (${options.space}) does not match plan.spaceId (${options.plan.spaceId})`,\n );\n }\n const space = options.plan.spaceId;\n const lockKey = `${LOCK_DOMAIN}:${schema}:${space}`;\n\n // Static checks (idempotent — safe to run again when the caller is\n // `execute(...)` because the cost is a single object comparison).\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) return destinationCheck;\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) return policyCheck;\n\n await this.acquireLock(driver, lockKey);\n const ensureResult = await this.ensureControlTables(driver);\n if (!ensureResult.ok) return ensureResult;\n const existingMarker = await this.family.readMarker({ driver, space });\n\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) return markerCheck;\n\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;\n const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;\n let applyValue: ApplyPlanSuccessValue;\n\n if (skipOperations) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options);\n if (!applyResult.ok) return applyResult;\n applyValue = applyResult.value;\n }\n\n // Schema verification on app-space only — extension spaces don't\n // own user-facing tables in the live schema, and `verifySqlSchema`\n // matches the destination contract against the database, which\n // would flag every app-space table as \"extra\" when called against\n // an extension contract.\n if (space === APP_SPACE_ID) {\n const schemaIR = await this.family.introspect({\n driver,\n contract: options.destinationContract,\n });\n const schemaVerifyResult = verifySqlSchema({\n contract: options.destinationContract,\n schema: schemaIR,\n strict: options.strictVerification ?? true,\n context: options.context ?? {},\n typeMetadataRegistry: this.family.typeMetadataRegistry,\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\n if (!schemaVerifyResult.ok) {\n return runnerFailure('SCHEMA_VERIFY_FAILED', schemaVerifyResult.summary, {\n why: 'The resulting database schema does not satisfy the destination contract.',\n meta: { issues: schemaVerifyResult.schema.issues },\n });\n }\n }\n\n const incomingInvariants = options.plan.providedInvariants ?? [];\n const existingInvariants = new Set(existingMarker?.invariants ?? []);\n const incomingIsSubsetOfExisting = incomingInvariants.every((id) => existingInvariants.has(id));\n const isSelfEdgeNoOp =\n isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting;\n\n if (!isSelfEdgeNoOp) {\n await this.upsertMarker(driver, options, existingMarker, space);\n await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);\n }\n\n return runnerSuccess({\n operationsPlanned: options.plan.operations.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n }\n\n async executeAcrossSpaces(options: {\n readonly driver: ControlDriverInstance<'sql', string>;\n readonly perSpaceOptions: ReadonlyArray<\n SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>\n >;\n }): Promise<MultiSpaceRunnerResult> {\n const driver = options.driver;\n const perSpaceOptions = options.perSpaceOptions;\n\n if (perSpaceOptions.length === 0) {\n return ok({ perSpaceResults: [] });\n }\n\n await this.beginTransaction(driver);\n let committed = false;\n try {\n const perSpaceResults: Array<{\n space: string;\n value: SqlMigrationRunnerSuccessValue;\n }> = [];\n for (const spaceOptions of perSpaceOptions) {\n const space = spaceOptions.space ?? spaceOptions.plan.spaceId;\n const result = await this.executeOnConnection({ ...spaceOptions, driver, space });\n if (!result.ok) {\n return notOk({ ...result.failure, failingSpace: space });\n }\n perSpaceResults.push({ space, value: result.value });\n }\n\n await this.commitTransaction(driver);\n committed = true;\n return ok({ perSpaceResults });\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n private async applyPlan(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<Result<ApplyPlanSuccessValue, SqlMigrationRunnerFailure>> {\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false; // Default true\n const runPostchecks = checks?.postchecks !== false; // Default true\n const runIdempotency = checks?.idempotencyChecks !== false; // Default true\n\n let operationsExecuted = 0;\n const executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> = [];\n for (const operation of options.plan.operations) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n // Idempotency probe: only run if both postchecks and idempotency checks are enabled\n if (runPostchecks && runIdempotency) {\n const postcheckAlreadySatisfied = await this.expectationsAreSatisfied(\n driver,\n operation.postcheck,\n );\n if (postcheckAlreadySatisfied) {\n executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));\n continue;\n }\n }\n\n // Prechecks: only run if enabled\n if (runPrechecks) {\n const precheckResult = await this.runExpectationSteps(\n driver,\n operation.precheck,\n operation,\n 'precheck',\n );\n if (!precheckResult.ok) {\n return precheckResult;\n }\n }\n\n const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);\n if (!executeResult.ok) {\n return executeResult;\n }\n\n // Postchecks: only run if enabled\n if (runPostchecks) {\n const postcheckResult = await this.runExpectationSteps(\n driver,\n operation.postcheck,\n operation,\n 'postcheck',\n );\n if (!postcheckResult.ok) {\n return postcheckResult;\n }\n }\n\n executedOperations.push(operation);\n operationsExecuted += 1;\n } finally {\n options.callbacks?.onOperationComplete?.(operation);\n }\n }\n return ok({ operationsExecuted, executedOperations });\n }\n\n private async ensureControlTables(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n await this.executeStatement(driver, ensurePrismaContractSchemaStatement);\n // Pre-1.0 zero-range guardrail: detect a pre-cleanup single-row\n // marker table (no `space` column) and surface a structured failure\n // rather than silently auto-migrating it to the per-space shape.\n // See `specs/framework-mechanism.spec.md § 2`.\n const legacyDetection = await this.detectLegacyMarkerShape(driver);\n if (!legacyDetection.ok) {\n return legacyDetection;\n }\n await this.executeStatement(driver, ensureMarkerTableStatement);\n await this.executeStatement(driver, ensureLedgerTableStatement);\n return okVoid();\n }\n\n private async detectLegacyMarkerShape(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const result = await driver.query<{ column_name: string }>(\n `select column_name\n from information_schema.columns\n where table_schema = 'prisma_contract'\n and table_name = 'marker'`,\n );\n if (result.rows.length === 0) {\n return okVoid();\n }\n const columns = new Set(result.rows.map((row) => row.column_name));\n if (columns.has('space')) {\n return okVoid();\n }\n return runnerFailure(\n 'LEGACY_MARKER_SHAPE',\n 'Legacy marker-table shape detected on prisma_contract.marker (no `space` column). ' +\n 'Prisma Next is in pre-1.0; the previous transitional auto-migration to the per-space-row schema has been removed. ' +\n 'Drop `prisma_contract.marker` and re-run `dbInit` to reinitialise from a clean baseline.',\n {\n meta: {\n table: 'prisma_contract.marker',\n columns: [...columns].sort(),\n },\n },\n );\n }\n\n private async runExpectationSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n phase: 'precheck' | 'postcheck',\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n const result = await driver.query(step.sql, step.params ?? []);\n if (!this.stepResultIsTrue(result.rows)) {\n const code = phase === 'precheck' ? 'PRECHECK_FAILED' : 'POSTCHECK_FAILED';\n return runnerFailure(\n code,\n `Operation ${operation.id} failed during ${phase}: ${step.description}`,\n {\n meta: {\n operationId: operation.id,\n phase,\n stepDescription: step.description,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private async runExecuteSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n try {\n await driver.query(step.sql, step.params ?? []);\n } catch (error: unknown) {\n // Catch SqlQueryError and include normalized metadata\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error.message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n sqlState: error.sqlState,\n constraint: error.constraint,\n table: error.table,\n column: error.column,\n detail: error.detail,\n },\n },\n );\n }\n // Let SqlConnectionError and other errors propagate (fail-fast)\n throw error;\n }\n }\n return okVoid();\n }\n\n private stepResultIsTrue(rows: readonly Record<string, unknown>[]): boolean {\n if (!rows || rows.length === 0) {\n return false;\n }\n const firstRow = rows[0];\n const firstValue = firstRow ? Object.values(firstRow)[0] : undefined;\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n // PostgreSQL boolean representations: 't'/'f', 'true'/'false', '1'/'0'\n if (lower === 't' || lower === 'true' || lower === '1') {\n return true;\n }\n if (lower === 'f' || lower === 'false' || lower === '0') {\n return false;\n }\n // For other strings, non-empty is truthy (though this case shouldn't occur for boolean checks)\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n ): Promise<boolean> {\n if (steps.length === 0) {\n return false;\n }\n for (const step of steps) {\n const result = await driver.query(step.sql, step.params ?? []);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n // Clone and freeze existing meta if present\n const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : undefined;\n\n // Create frozen runner metadata\n const runnerMeta = Object.freeze({\n skipped: true,\n reason: 'postcheck_pre_satisfied',\n });\n\n // Merge and freeze the combined meta\n const mergedMeta = Object.freeze({\n ...(clonedMeta ?? {}),\n runner: runnerMeta,\n });\n\n // Clone and freeze arrays to prevent mutation\n const frozenPostcheck = Object.freeze([...operation.postcheck]);\n\n return Object.freeze({\n id: operation.id,\n label: operation.label,\n ...ifDefined('summary', operation.summary),\n operationClass: operation.operationClass,\n target: operation.target, // Already frozen from plan creation\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: frozenPostcheck,\n ...ifDefined('meta', operation.meta || mergedMeta ? mergedMeta : undefined),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.storageHash !== plan.destination.storageHash) {\n return false;\n }\n if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) {\n return false;\n }\n return true;\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, SqlMigrationRunnerFailure> {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${policy.allowedOperationClasses.join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n allowedClasses: policy.allowedOperationClasses,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n // No origin assertion on the plan — the caller does not want origin validation.\n // This is the case for `db update`, which introspects the live schema and does not\n // rely on marker continuity. `db init` handles its own marker checks before the runner.\n return okVoid();\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n {\n meta: {\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (marker.storageHash !== origin.storageHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (origin.profileHash && marker.profileHash !== origin.profileHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`,\n {\n meta: {\n markerProfileHash: marker.profileHash,\n expectedOriginProfileHash: origin.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private ensurePlanMatchesDestinationContract(\n destination: SqlMigrationPlanContractInfo,\n contract: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['destinationContract'],\n ): Result<void, SqlMigrationRunnerFailure> {\n if (destination.storageHash !== contract.storage.storageHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storage.storageHash}).`,\n {\n meta: {\n planStorageHash: destination.storageHash,\n contractStorageHash: contract.storage.storageHash,\n },\n },\n );\n }\n if (\n destination.profileHash &&\n contract.profileHash &&\n destination.profileHash !== contract.profileHash\n ) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`,\n {\n meta: {\n planProfileHash: destination.profileHash,\n contractProfileHash: contract.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async upsertMarker(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n space: string,\n ): Promise<void> {\n const incomingInvariants = options.plan.providedInvariants ?? [];\n const writeStatements = buildMergeMarkerStatements({\n space,\n storageHash: options.plan.destination.storageHash,\n profileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJson: options.destinationContract,\n canonicalVersion: null,\n meta: {},\n invariants: incomingInvariants,\n });\n const statement = existingMarker ? writeStatements.update : writeStatements.insert;\n await this.executeStatement(driver, statement);\n }\n\n private async recordLedgerEntry(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Promise<void> {\n const ledgerStatement = buildLedgerInsertStatement({\n originStorageHash: existingMarker?.storageHash ?? null,\n originProfileHash: existingMarker?.profileHash ?? null,\n destinationStorageHash: options.plan.destination.storageHash,\n destinationProfileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJsonBefore: existingMarker?.contractJson ?? null,\n contractJsonAfter: options.destinationContract,\n operations: executedOperations,\n });\n await this.executeStatement(driver, ledgerStatement);\n }\n\n private async acquireLock(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n key: string,\n ): Promise<void> {\n await driver.query('select pg_advisory_xact_lock(hashtext($1))', [key]);\n }\n\n private async beginTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN');\n }\n\n private async commitTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n statement: SqlStatement,\n ): Promise<void> {\n if (statement.params.length > 0) {\n await driver.query(statement.sql, statement.params);\n return;\n }\n await driver.query(statement.sql);\n }\n}\n","import type { ColumnDefault, Contract } from '@prisma-next/contract/types';\nimport type {\n SqlControlFamilyInstance,\n SqlControlTargetDescriptor,\n} from '@prisma-next/family-sql/control';\nimport { contractToSchemaIR, extractCodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlTargetInstance,\n MigrationRunner,\n} from '@prisma-next/framework-components/control';\nimport type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { renderDefaultLiteral } from '../core/migrations/planner-ddl-builders';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner-target-details';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nfunction buildNativeTypeExpander(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n if (!frameworkComponents) {\n return undefined;\n }\n const codecHooks = extractCodecControlHooks(frameworkComponents);\n return (input: {\n readonly nativeType: string;\n readonly codecId?: string;\n readonly typeParams?: Record<string, unknown>;\n }) => {\n if (!input.typeParams) return input.nativeType;\n // Mirror `renderExpectedNativeType` in verify-sql-schema: when a codec\n // has no `expandNativeType` hook (e.g. `pg/enum@1`, whose typeParams\n // describe the value set rather than a DDL suffix), fall back to the\n // bare native type rather than throwing. Throwing here would reject\n // every plan involving an enum-/values-typed column as soon as its\n // `typeRef` resolved to a `StorageTypeInstance` carrying typeParams.\n if (!input.codecId) return input.nativeType;\n const hooks = codecHooks.get(input.codecId);\n if (!hooks?.expandNativeType) return input.nativeType;\n return hooks.expandNativeType(input);\n };\n}\n\nexport function postgresRenderDefault(def: ColumnDefault, column: StorageColumn): string {\n if (def.kind === 'function') {\n return def.expression;\n }\n return renderDefaultLiteral(def.value, column);\n}\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n migrations: {\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n return contractToSchemaIR(contract as Contract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n frameworkComponents: frameworkComponents ?? [],\n });\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;;AA2CA,MAAM,iBAA+B,EACnC,eAAe,UAChB;AAED,MAAM,cAAc;;;;;AAMpB,SAAS,qBAAwD,OAAa;CAC5E,MAAM,SAAkC,EAAE;CAC1C,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,MAAM,EAC5C,IAAI,QAAQ,QAAQ,QAAQ,KAAA,GAC1B,OAAO,OAAO;MACT,IAAI,MAAM,QAAQ,IAAI,EAE3B,OAAO,OAAO,OAAO,OAAO,CAAC,GAAG,IAAI,CAAC;MAChC,IAAI,OAAO,QAAQ,UAExB,OAAO,OAAO,qBAAqB,IAA+B;MAGlE,OAA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K,UAAU,OAAO;GACnD;;EAEF,MAAM,OAAO,MAAM,UAAU,IAAI;;;;;ACjrBrC,SAAS,wBACP,qBACA;CACA,IAAI,CAAC,qBACH;CAEF,MAAM,aAAa,yBAAyB,oBAAoB;CAChE,QAAQ,UAIF;EACJ,IAAI,CAAC,MAAM,YAAY,OAAO,MAAM;EAOpC,IAAI,CAAC,MAAM,SAAS,OAAO,MAAM;EACjC,MAAM,QAAQ,WAAW,IAAI,MAAM,QAAQ;EAC3C,IAAI,CAAC,OAAO,kBAAkB,OAAO,MAAM;EAC3C,OAAO,MAAM,iBAAiB,MAAM;;;AAIxC,SAAgB,sBAAsB,KAAoB,QAA+B;CACvF,IAAI,IAAI,SAAS,YACf,OAAO,IAAI;CAEb,OAAO,qBAAqB,IAAI,OAAO,OAAO;;AAGhD,MAAM,2BACJ;CACE,GAAG;CACH,YAAY;EACV,cAAc,SAAmC;GAC/C,OAAO,gCAAgC;;EAEzC,aAAa,QAAQ;GACnB,OAAO,8BAA8B,OAAO;;EAE9C,iBAAiB,UAAU,qBAAqB;GAE9C,OAAO,mBAAmB,UAAyC;IACjE,qBAAqB;IACrB,GAAG,UAAU,oBAHE,wBAAwB,oBAGE,CAAC;IAC1C,eAAe;IACf,qBAAqB,uBAAuB,EAAE;IAC/C,CAAC;;EAEL;CACD,SAAmD;EACjD,OAAO;GACL,UAAU;GACV,UAAU;GACX;;;;;;CAMH,cAAc,SAAmC;EAC/C,OAAO,gCAAgC;;;;;;CAMzC,aAAa,QAAQ;EACnB,OAAO,8BAA8B,OAAO;;CAE/C"}
1
+ {"version":3,"file":"control.mjs","names":[],"sources":["../src/core/migrations/runner.ts","../src/exports/control.ts"],"sourcesContent":["import type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n MultiSpaceRunnerResult,\n SqlControlFamilyInstance,\n SqlMigrationPlanContractInfo,\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n SqlMigrationRunner,\n SqlMigrationRunnerExecuteOptions,\n SqlMigrationRunnerFailure,\n SqlMigrationRunnerResult,\n SqlMigrationRunnerSuccessValue,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { ControlDriverInstance } from '@prisma-next/framework-components/control';\nimport { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok, okVoid } from '@prisma-next/utils/result';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\nimport {\n buildLedgerInsertStatement,\n buildMergeMarkerStatements,\n ensureLedgerTableStatement,\n ensureMarkerTableStatement,\n ensurePrismaContractSchemaStatement,\n type SqlStatement,\n} from './statement-builders';\n\ninterface RunnerConfig {\n readonly defaultSchema: string;\n}\n\ninterface ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n}\n\nconst DEFAULT_CONFIG: RunnerConfig = {\n defaultSchema: 'public',\n};\n\nconst LOCK_DOMAIN = 'prisma_next.contract.marker';\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n // Clone array (shallow clone of array elements)\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n // Recursively clone nested objects\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n // Primitives are copied as-is\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n config: Partial<RunnerConfig> = {},\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family, { ...DEFAULT_CONFIG, ...config });\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(\n private readonly family: SqlControlFamilyInstance,\n private readonly config: RunnerConfig,\n ) {}\n\n async execute(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const driver = options.driver;\n\n // Static checks fail fast before any transaction work — no point\n // burning a BEGIN/ROLLBACK round-trip on a destination-contract\n // mismatch the caller can fix locally.\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) return destinationCheck;\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) return policyCheck;\n\n await this.beginTransaction(driver);\n let committed = false;\n try {\n const result = await this.executeOnConnection(options);\n if (!result.ok) {\n return result;\n }\n await this.commitTransaction(driver);\n committed = true;\n return result;\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n /**\n * Body of the migration runner without transaction management. The\n * caller (single-space `execute(...)` above, or the multi-space\n * outer-tx orchestrator at the SQL family level) owns the\n * `BEGIN`/`COMMIT`/`ROLLBACK` lifecycle.\n */\n async executeOnConnection(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema = options.schemaName ?? this.config.defaultSchema;\n const driver = options.driver;\n if (options.space !== undefined && options.space !== options.plan.spaceId) {\n throw new Error(\n `SqlMigrationRunner: options.space (${options.space}) does not match plan.spaceId (${options.plan.spaceId})`,\n );\n }\n const space = options.plan.spaceId;\n const lockKey = `${LOCK_DOMAIN}:${schema}:${space}`;\n\n // Static checks (idempotent — safe to run again when the caller is\n // `execute(...)` because the cost is a single object comparison).\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) return destinationCheck;\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) return policyCheck;\n\n await this.acquireLock(driver, lockKey);\n const ensureResult = await this.ensureControlTables(driver);\n if (!ensureResult.ok) return ensureResult;\n const existingMarker = await this.family.readMarker({ driver, space });\n\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) return markerCheck;\n\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;\n const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;\n let applyValue: ApplyPlanSuccessValue;\n\n if (skipOperations) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options);\n if (!applyResult.ok) return applyResult;\n applyValue = applyResult.value;\n }\n\n // Schema verification on app-space only — extension spaces don't\n // own user-facing tables in the live schema, and `verifySqlSchema`\n // matches the destination contract against the database, which\n // would flag every app-space table as \"extra\" when called against\n // an extension contract.\n if (space === APP_SPACE_ID) {\n const schemaIR = await this.family.introspect({\n driver,\n contract: options.destinationContract,\n });\n const schemaVerifyResult = verifySqlSchema({\n contract: options.destinationContract,\n schema: schemaIR,\n strict: options.strictVerification ?? true,\n context: options.context ?? {},\n typeMetadataRegistry: this.family.typeMetadataRegistry,\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\n if (!schemaVerifyResult.ok) {\n return runnerFailure('SCHEMA_VERIFY_FAILED', schemaVerifyResult.summary, {\n why: 'The resulting database schema does not satisfy the destination contract.',\n meta: { issues: schemaVerifyResult.schema.issues },\n });\n }\n }\n\n const incomingInvariants = options.plan.providedInvariants ?? [];\n const existingInvariants = new Set(existingMarker?.invariants ?? []);\n const incomingIsSubsetOfExisting = incomingInvariants.every((id) => existingInvariants.has(id));\n const isSelfEdgeNoOp =\n isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting;\n\n if (!isSelfEdgeNoOp) {\n await this.upsertMarker(driver, options, existingMarker, space);\n await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);\n }\n\n return runnerSuccess({\n operationsPlanned: options.plan.operations.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n }\n\n async executeAcrossSpaces(options: {\n readonly driver: ControlDriverInstance<'sql', string>;\n readonly perSpaceOptions: ReadonlyArray<\n SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>\n >;\n }): Promise<MultiSpaceRunnerResult> {\n const driver = options.driver;\n const perSpaceOptions = options.perSpaceOptions;\n\n if (perSpaceOptions.length === 0) {\n return ok({ perSpaceResults: [] });\n }\n\n await this.beginTransaction(driver);\n let committed = false;\n try {\n const perSpaceResults: Array<{\n space: string;\n value: SqlMigrationRunnerSuccessValue;\n }> = [];\n for (const spaceOptions of perSpaceOptions) {\n const space = spaceOptions.space ?? spaceOptions.plan.spaceId;\n const result = await this.executeOnConnection({ ...spaceOptions, driver, space });\n if (!result.ok) {\n return notOk({ ...result.failure, failingSpace: space });\n }\n perSpaceResults.push({ space, value: result.value });\n }\n\n await this.commitTransaction(driver);\n committed = true;\n return ok({ perSpaceResults });\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n private async applyPlan(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<Result<ApplyPlanSuccessValue, SqlMigrationRunnerFailure>> {\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false; // Default true\n const runPostchecks = checks?.postchecks !== false; // Default true\n const runIdempotency = checks?.idempotencyChecks !== false; // Default true\n\n let operationsExecuted = 0;\n const executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> = [];\n for (const operation of options.plan.operations) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n // Idempotency probe: only run if both postchecks and idempotency checks are enabled\n if (runPostchecks && runIdempotency) {\n const postcheckAlreadySatisfied = await this.expectationsAreSatisfied(\n driver,\n operation.postcheck,\n );\n if (postcheckAlreadySatisfied) {\n executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));\n continue;\n }\n }\n\n // Prechecks: only run if enabled\n if (runPrechecks) {\n const precheckResult = await this.runExpectationSteps(\n driver,\n operation.precheck,\n operation,\n 'precheck',\n );\n if (!precheckResult.ok) {\n return precheckResult;\n }\n }\n\n const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);\n if (!executeResult.ok) {\n return executeResult;\n }\n\n // Postchecks: only run if enabled\n if (runPostchecks) {\n const postcheckResult = await this.runExpectationSteps(\n driver,\n operation.postcheck,\n operation,\n 'postcheck',\n );\n if (!postcheckResult.ok) {\n return postcheckResult;\n }\n }\n\n executedOperations.push(operation);\n operationsExecuted += 1;\n } finally {\n options.callbacks?.onOperationComplete?.(operation);\n }\n }\n return ok({ operationsExecuted, executedOperations });\n }\n\n private async ensureControlTables(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n await this.executeStatement(driver, ensurePrismaContractSchemaStatement);\n // Pre-1.0 zero-range guardrail: detect a pre-cleanup single-row\n // marker table (no `space` column) and surface a structured failure\n // rather than silently auto-migrating it to the per-space shape.\n // See `specs/framework-mechanism.spec.md § 2`.\n const legacyDetection = await this.detectLegacyMarkerShape(driver);\n if (!legacyDetection.ok) {\n return legacyDetection;\n }\n await this.executeStatement(driver, ensureMarkerTableStatement);\n await this.executeStatement(driver, ensureLedgerTableStatement);\n return okVoid();\n }\n\n private async detectLegacyMarkerShape(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const result = await driver.query<{ column_name: string }>(\n `select column_name\n from information_schema.columns\n where table_schema = 'prisma_contract'\n and table_name = 'marker'`,\n );\n if (result.rows.length === 0) {\n return okVoid();\n }\n const columns = new Set(result.rows.map((row) => row.column_name));\n if (columns.has('space')) {\n return okVoid();\n }\n return runnerFailure(\n 'LEGACY_MARKER_SHAPE',\n 'Legacy marker-table shape detected on prisma_contract.marker (no `space` column). ' +\n 'Prisma Next is in pre-1.0; the previous transitional auto-migration to the per-space-row schema has been removed. ' +\n 'Drop `prisma_contract.marker` and re-run `dbInit` to reinitialise from a clean baseline.',\n {\n meta: {\n table: 'prisma_contract.marker',\n columns: [...columns].sort(),\n },\n },\n );\n }\n\n private async runExpectationSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n phase: 'precheck' | 'postcheck',\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n const result = await driver.query(step.sql, step.params ?? []);\n if (!this.stepResultIsTrue(result.rows)) {\n const code = phase === 'precheck' ? 'PRECHECK_FAILED' : 'POSTCHECK_FAILED';\n return runnerFailure(\n code,\n `Operation ${operation.id} failed during ${phase}: ${step.description}`,\n {\n meta: {\n operationId: operation.id,\n phase,\n stepDescription: step.description,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private async runExecuteSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n try {\n await driver.query(step.sql, step.params ?? []);\n } catch (error: unknown) {\n // Catch SqlQueryError and include normalized metadata\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error.message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n sqlState: error.sqlState,\n constraint: error.constraint,\n table: error.table,\n column: error.column,\n detail: error.detail,\n },\n },\n );\n }\n // Let SqlConnectionError and other errors propagate (fail-fast)\n throw error;\n }\n }\n return okVoid();\n }\n\n private stepResultIsTrue(rows: readonly Record<string, unknown>[]): boolean {\n if (!rows || rows.length === 0) {\n return false;\n }\n const firstRow = rows[0];\n const firstValue = firstRow ? Object.values(firstRow)[0] : undefined;\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n // PostgreSQL boolean representations: 't'/'f', 'true'/'false', '1'/'0'\n if (lower === 't' || lower === 'true' || lower === '1') {\n return true;\n }\n if (lower === 'f' || lower === 'false' || lower === '0') {\n return false;\n }\n // For other strings, non-empty is truthy (though this case shouldn't occur for boolean checks)\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n ): Promise<boolean> {\n if (steps.length === 0) {\n return false;\n }\n for (const step of steps) {\n const result = await driver.query(step.sql, step.params ?? []);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n // Clone and freeze existing meta if present\n const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : undefined;\n\n // Create frozen runner metadata\n const runnerMeta = Object.freeze({\n skipped: true,\n reason: 'postcheck_pre_satisfied',\n });\n\n // Merge and freeze the combined meta\n const mergedMeta = Object.freeze({\n ...(clonedMeta ?? {}),\n runner: runnerMeta,\n });\n\n // Clone and freeze arrays to prevent mutation\n const frozenPostcheck = Object.freeze([...operation.postcheck]);\n\n return Object.freeze({\n id: operation.id,\n label: operation.label,\n ...ifDefined('summary', operation.summary),\n operationClass: operation.operationClass,\n target: operation.target, // Already frozen from plan creation\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: frozenPostcheck,\n ...ifDefined('meta', operation.meta || mergedMeta ? mergedMeta : undefined),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.storageHash !== plan.destination.storageHash) {\n return false;\n }\n if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) {\n return false;\n }\n return true;\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, SqlMigrationRunnerFailure> {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${policy.allowedOperationClasses.join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n allowedClasses: policy.allowedOperationClasses,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n // No origin assertion on the plan — the caller does not want origin validation.\n // This is the case for `db update`, which introspects the live schema and does not\n // rely on marker continuity. `db init` handles its own marker checks before the runner.\n return okVoid();\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n {\n meta: {\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (marker.storageHash !== origin.storageHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (origin.profileHash && marker.profileHash !== origin.profileHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`,\n {\n meta: {\n markerProfileHash: marker.profileHash,\n expectedOriginProfileHash: origin.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private ensurePlanMatchesDestinationContract(\n destination: SqlMigrationPlanContractInfo,\n contract: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['destinationContract'],\n ): Result<void, SqlMigrationRunnerFailure> {\n if (destination.storageHash !== contract.storage.storageHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storage.storageHash}).`,\n {\n meta: {\n planStorageHash: destination.storageHash,\n contractStorageHash: contract.storage.storageHash,\n },\n },\n );\n }\n if (\n destination.profileHash &&\n contract.profileHash &&\n destination.profileHash !== contract.profileHash\n ) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`,\n {\n meta: {\n planProfileHash: destination.profileHash,\n contractProfileHash: contract.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async upsertMarker(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n space: string,\n ): Promise<void> {\n const incomingInvariants = options.plan.providedInvariants ?? [];\n const writeStatements = buildMergeMarkerStatements({\n space,\n storageHash: options.plan.destination.storageHash,\n profileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJson: options.destinationContract,\n canonicalVersion: null,\n meta: {},\n invariants: incomingInvariants,\n });\n const statement = existingMarker ? writeStatements.update : writeStatements.insert;\n await this.executeStatement(driver, statement);\n }\n\n private async recordLedgerEntry(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Promise<void> {\n const ledgerStatement = buildLedgerInsertStatement({\n originStorageHash: existingMarker?.storageHash ?? null,\n originProfileHash: existingMarker?.profileHash ?? null,\n destinationStorageHash: options.plan.destination.storageHash,\n destinationProfileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJsonBefore: existingMarker?.contractJson ?? null,\n contractJsonAfter: options.destinationContract,\n operations: executedOperations,\n });\n await this.executeStatement(driver, ledgerStatement);\n }\n\n private async acquireLock(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n key: string,\n ): Promise<void> {\n await driver.query('select pg_advisory_xact_lock(hashtext($1))', [key]);\n }\n\n private async beginTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN');\n }\n\n private async commitTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n statement: SqlStatement,\n ): Promise<void> {\n if (statement.params.length > 0) {\n await driver.query(statement.sql, statement.params);\n return;\n }\n await driver.query(statement.sql);\n }\n}\n","import type { ColumnDefault, Contract } from '@prisma-next/contract/types';\nimport type {\n SqlControlFamilyInstance,\n SqlControlTargetDescriptor,\n} from '@prisma-next/family-sql/control';\nimport { contractToSchemaIR, extractCodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlTargetInstance,\n MigrationRunner,\n} from '@prisma-next/framework-components/control';\nimport type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { renderDefaultLiteral } from '../core/migrations/planner-ddl-builders';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner-target-details';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nfunction buildNativeTypeExpander(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n if (!frameworkComponents) {\n return undefined;\n }\n const codecHooks = extractCodecControlHooks(frameworkComponents);\n return (input: {\n readonly nativeType: string;\n readonly codecId?: string;\n readonly typeParams?: Record<string, unknown>;\n }) => {\n if (!input.typeParams) return input.nativeType;\n // Mirror `renderExpectedNativeType` in verify-sql-schema: when a codec\n // has no `expandNativeType` hook (e.g. `pg/enum@1`, whose typeParams\n // describe the value set rather than a DDL suffix), fall back to the\n // bare native type rather than throwing. Throwing here would reject\n // every plan involving an enum-/values-typed column as soon as its\n // `typeRef` resolved to a `StorageTypeInstance` carrying typeParams.\n if (!input.codecId) return input.nativeType;\n const hooks = codecHooks.get(input.codecId);\n if (!hooks?.expandNativeType) return input.nativeType;\n return hooks.expandNativeType(input);\n };\n}\n\nexport function postgresRenderDefault(def: ColumnDefault, column: StorageColumn): string {\n if (def.kind === 'function') {\n return def.expression;\n }\n return renderDefaultLiteral(def.value, column);\n}\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n migrations: {\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n return contractToSchemaIR(contract as Contract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n });\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;;AA2CA,MAAM,iBAA+B,EACnC,eAAe,UAChB;AAED,MAAM,cAAc;;;;;AAMpB,SAAS,qBAAwD,OAAa;CAC5E,MAAM,SAAkC,EAAE;CAC1C,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,MAAM,EAC5C,IAAI,QAAQ,QAAQ,QAAQ,KAAA,GAC1B,OAAO,OAAO;MACT,IAAI,MAAM,QAAQ,IAAI,EAE3B,OAAO,OAAO,OAAO,OAAO,CAAC,GAAG,IAAI,CAAC;MAChC,IAAI,OAAO,QAAQ,UAExB,OAAO,OAAO,q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AM,OAAO,MAAM,UAAU,KAAK,UAAU,OAAO;GACnD;;EAEF,MAAM,OAAO,MAAM,UAAU,IAAI;;;;;ACjrBrC,SAAS,wBACP,qBACA;CACA,IAAI,CAAC,qBACH;CAEF,MAAM,aAAa,yBAAyB,oBAAoB;CAChE,QAAQ,UAIF;EACJ,IAAI,CAAC,MAAM,YAAY,OAAO,MAAM;EAOpC,IAAI,CAAC,MAAM,SAAS,OAAO,MAAM;EACjC,MAAM,QAAQ,WAAW,IAAI,MAAM,QAAQ;EAC3C,IAAI,CAAC,OAAO,kBAAkB,OAAO,MAAM;EAC3C,OAAO,MAAM,iBAAiB,MAAM;;;AAIxC,SAAgB,sBAAsB,KAAoB,QAA+B;CACvF,IAAI,IAAI,SAAS,YACf,OAAO,IAAI;CAEb,OAAO,qBAAqB,IAAI,OAAO,OAAO;;AAGhD,MAAM,2BACJ;CACE,GAAG;CACH,YAAY;EACV,cAAc,SAAmC;GAC/C,OAAO,gCAAgC;;EAEzC,aAAa,QAAQ;GACnB,OAAO,8BAA8B,OAAO;;EAE9C,iBAAiB,UAAU,qBAAqB;GAE9C,OAAO,mBAAmB,UAAyC;IACjE,qBAAqB;IACrB,GAAG,UAAU,oBAHE,wBAAwB,oBAGE,CAAC;IAC1C,eAAe;IAChB,CAAC;;EAEL;CACD,SAAmD;EACjD,OAAO;GACL,UAAU;GACV,UAAU;GACX;;;;;;CAMH,cAAc,SAAmC;EAC/C,OAAO,gCAAgC;;;;;;CAMzC,aAAa,QAAQ;EACnB,OAAO,8BAA8B,OAAO;;CAE/C"}
@@ -1,10 +1,9 @@
1
1
  import { i as quoteIdentifier } from "./sql-utils-CggjWNij.mjs";
2
2
  import { a as columnNullabilityCheck, c as qualifyTableName, i as columnHasNoDefaultCheck, r as columnExistsCheck, t as buildExpectedFormatType, u as tableIsEmptyCheck } from "./planner-sql-checks-DwZvGlV4.mjs";
3
- import { C as SetNotNullCall, S as SetDefaultCall, _ as DropIndexCall, a as AddUniqueCall, b as RawSqlCall, c as CreateExtensionCall, d as CreateTableCall, f as DataTransformCall, g as DropEnumTypeCall, h as DropDefaultCall, i as AddPrimaryKeyCall, l as CreateIndexCall, m as DropConstraintCall, n as AddEnumValuesCall, o as AlterColumnTypeCall, p as DropColumnCall, r as AddForeignKeyCall, s as CreateEnumTypeCall, t as AddColumnCall, u as CreateSchemaCall, v as DropNotNullCall, x as RenameTypeCall, y as DropTableCall } from "./op-factory-call-Bs3HWhvG.mjs";
3
+ import { C as SetNotNullCall, S as SetDefaultCall, _ as DropIndexCall, a as AddUniqueCall, b as RawSqlCall, d as CreateTableCall, f as DataTransformCall, g as DropEnumTypeCall, h as DropDefaultCall, i as AddPrimaryKeyCall, l as CreateIndexCall, m as DropConstraintCall, n as AddEnumValuesCall, o as AlterColumnTypeCall, p as DropColumnCall, r as AddForeignKeyCall, s as CreateEnumTypeCall, t as AddColumnCall, v as DropNotNullCall, x as RenameTypeCall, y as DropTableCall } from "./op-factory-call-DeaFxa8_.mjs";
4
4
  import { n as buildColumnDefaultSql, r as buildColumnTypeSql, t as buildAddColumnSql } from "./planner-ddl-builders-CLB7Umhh.mjs";
5
5
  import { n as resolveIdentityValue } from "./planner-identity-values-DTx0gePL.mjs";
6
6
  import { i as hasUniqueConstraint, n as hasForeignKey, t as buildSchemaLookupMap } from "./planner-schema-lookup-B1ags8ys.mjs";
7
- import { collectInitDependencies } from "@prisma-next/family-sql/control";
8
7
  import { ifDefined } from "@prisma-next/utils/defined";
9
8
  import { arraysEqual } from "@prisma-next/family-sql/schema-verify";
10
9
  import { notOk, ok } from "@prisma-next/utils/result";
@@ -282,38 +281,6 @@ const storageTypePlanCallStrategy = (issues, ctx) => {
282
281
  };
283
282
  };
284
283
  /**
285
- * Dispatches component-declared database dependencies. Replaces the
286
- * walk-schema `buildDatabaseDependencyOperations` path. Rather than consuming
287
- * `dependency_missing` issues (which only carry the id), this strategy
288
- * re-invokes `collectInitDependencies(frameworkComponents)` at plan time so
289
- * the handler has access to the structured `install` ops each component
290
- * declared — including arbitrary SQL launders — and dedupes by dependency id
291
- * plus per-op id.
292
- */
293
- const dependencyInstallCallStrategy = (issues, ctx) => {
294
- const installedIds = new Set(ctx.schema.dependencies.map((d) => d.id));
295
- const dependencies = sortDependencies(collectInitDependencies(ctx.frameworkComponents).filter(isPostgresPlannerDependency));
296
- const calls = [];
297
- const handledDependencyIds = /* @__PURE__ */ new Set();
298
- const seenOperationIds = /* @__PURE__ */ new Set();
299
- for (const dep of dependencies) {
300
- handledDependencyIds.add(dep.id);
301
- if (installedIds.has(dep.id)) continue;
302
- for (const installOp of dep.install) {
303
- if (seenOperationIds.has(installOp.id)) continue;
304
- seenOperationIds.add(installOp.id);
305
- calls.push(liftInstallOpToCall(installOp));
306
- }
307
- }
308
- const remaining = issues.filter((issue) => issue.kind !== "dependency_missing");
309
- if (calls.length === 0 && remaining.length === issues.length) return { kind: "no_match" };
310
- return {
311
- kind: "match",
312
- issues: remaining,
313
- calls
314
- };
315
- };
316
- /**
317
284
  * Handles `missing_column` issues for NOT NULL columns without a contract
318
285
  * default. Replaces the walk-schema `buildAddColumnItem` non-default branches.
319
286
  *
@@ -422,30 +389,6 @@ function canUseSharedTemporaryDefaultStrategy(options) {
422
389
  }
423
390
  return true;
424
391
  }
425
- function isPostgresPlannerDependency(dependency) {
426
- return dependency.install.every((operation) => operation.target.id === "postgres");
427
- }
428
- function sortDependencies(dependencies) {
429
- return [...dependencies].sort((a, b) => a.id.localeCompare(b.id));
430
- }
431
- /**
432
- * Lift a component install op into migration IR. Structured shapes — extension
433
- * and schema installs with predictable SQL — collapse to typed `*Call`
434
- * subclasses so the scaffolded migration authoring surface stays readable.
435
- * Everything else (arbitrary SQL) falls through to `RawSqlCall` as an escape
436
- * hatch.
437
- */
438
- /**
439
- * Component-declared install ops are wrapped as `RawSqlCall` so the
440
- * component's original `label`, `precheck`, `execute`, `postcheck`, and op
441
- * id are preserved verbatim. Structured conversion (to e.g.
442
- * `CreateExtensionCall`) would drop the precheck/postcheck pair and
443
- * change the DDL label, breaking walk-schema output parity. Classification
444
- * as `'dep'` happens in `classifyCall` via the underlying op's id prefix.
445
- */
446
- function liftInstallOpToCall(op) {
447
- return new RawSqlCall(op);
448
- }
449
392
  /**
450
393
  * Ordered list of Postgres planner strategies, shared by `migration plan`
451
394
  * and `db update` / `db init`. The issue planner runs each strategy in
@@ -461,8 +404,8 @@ function liftInstallOpToCall(op) {
461
404
  * - When `'data'` is not allowed (`db update` / `db init`), each data-safe
462
405
  * strategy short-circuits to `no_match`, leaving the issue for the
463
406
  * downstream walk-schema strategies (`storageTypePlanCallStrategy`,
464
- * `dependencyInstallCallStrategy`, `notNullAddColumnCallStrategy`) or the
465
- * `mapIssueToCall` default to handle with direct DDL.
407
+ * `notNullAddColumnCallStrategy`) or the `mapIssueToCall` default to handle
408
+ * with direct DDL.
466
409
  *
467
410
  * Order matters: data-safe strategies must run before the walk-schema
468
411
  * strategies on overlapping issue kinds (e.g. `enum_values_changed`,
@@ -474,13 +417,11 @@ const postgresPlannerStrategies = [
474
417
  typeChangeCallStrategy,
475
418
  nullableTighteningCallStrategy,
476
419
  storageTypePlanCallStrategy,
477
- dependencyInstallCallStrategy,
478
420
  notNullAddColumnCallStrategy
479
421
  ];
480
422
  //#endregion
481
423
  //#region src/core/migrations/issue-planner.ts
482
424
  const ISSUE_KIND_ORDER = {
483
- dependency_missing: 1,
484
425
  type_missing: 2,
485
426
  type_values_mismatch: 3,
486
427
  enum_values_changed: 3,
@@ -703,11 +644,6 @@ function mapIssueToCall(issue, ctx) {
703
644
  return notOk(issueConflict("unsupportedOperation", `Type "${issue.typeName}" uses codec "${typeInstance.codecId}" — only enum types are supported`));
704
645
  }
705
646
  case "type_values_mismatch": return notOk(issueConflict("unsupportedOperation", `Type "${issue.typeName ?? "unknown"}" values differ — type alteration not yet supported`));
706
- case "dependency_missing":
707
- if (!issue.dependencyId) return notOk(issueConflict("unsupportedOperation", "Dependency missing issue has no dependencyId"));
708
- if (issue.dependencyId.startsWith("ext:")) return ok([new CreateExtensionCall(issue.dependencyId.slice(4))]);
709
- if (issue.dependencyId.startsWith("schema:")) return ok([new CreateSchemaCall(issue.dependencyId.slice(7))]);
710
- return notOk(issueConflict("unsupportedOperation", `Unknown dependency type: ${issue.dependencyId}`));
711
647
  default: return notOk(issueConflict("unsupportedOperation", `Unhandled issue kind: ${issue.kind}`));
712
648
  }
713
649
  }
@@ -740,13 +676,9 @@ function classifyCall(call) {
740
676
  case "addUnique": return "unique";
741
677
  case "createIndex": return "index";
742
678
  case "addForeignKey": return "foreignKey";
743
- case "rawSql": {
744
- const op = call.op;
745
- if (op?.target?.details?.objectType === "type") return "dep";
746
- const id = typeof op?.id === "string" ? op.id : "";
747
- if (id.startsWith("extension.") || id.startsWith("schema.")) return "dep";
679
+ case "rawSql":
680
+ if (call.op?.target?.details?.objectType === "type") return "dep";
748
681
  return "alter";
749
- }
750
682
  default: return "alter";
751
683
  }
752
684
  }
@@ -761,10 +693,7 @@ const DEFAULT_POLICY = { allowedOperationClasses: [
761
693
  "data"
762
694
  ] };
763
695
  function emptySchemaIR() {
764
- return {
765
- tables: {},
766
- dependencies: []
767
- };
696
+ return { tables: {} };
768
697
  }
769
698
  function conflictKindForCall(call) {
770
699
  switch (call.factoryName) {
@@ -880,4 +809,4 @@ function planIssues(options) {
880
809
  //#endregion
881
810
  export { postgresPlannerStrategies as n, planIssues as t };
882
811
 
883
- //# sourceMappingURL=issue-planner-CiNmA4ls.mjs.map
812
+ //# sourceMappingURL=issue-planner-DQ6WJkad.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"issue-planner-DQ6WJkad.mjs","names":[],"sources":["../src/core/migrations/planner-target-details.ts","../src/core/migrations/planner-recipes.ts","../src/core/migrations/planner-strategies.ts","../src/core/migrations/issue-planner.ts"],"sourcesContent":["import { ifDefined } from '@prisma-next/utils/defined';\n\nexport type OperationClass =\n | 'dependency'\n | 'type'\n | 'table'\n | 'column'\n | 'primaryKey'\n | 'unique'\n | 'index'\n | 'foreignKey';\n\nexport interface PostgresPlanTargetDetails {\n readonly schema: string;\n readonly objectType: OperationClass;\n readonly name: string;\n readonly table?: string;\n}\n\nexport function buildTargetDetails(\n objectType: OperationClass,\n name: string,\n schema: string,\n table?: string,\n): PostgresPlanTargetDetails {\n return {\n schema,\n objectType,\n name,\n ...ifDefined('table', table),\n };\n}\n","import type { CodecControlHooks, SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { StorageColumn, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport { quoteIdentifier } from '../sql-utils';\nimport { buildAddColumnSql } from './planner-ddl-builders';\nimport {\n columnExistsCheck,\n columnHasNoDefaultCheck,\n columnNullabilityCheck,\n qualifyTableName,\n} from './planner-sql-checks';\nimport { buildTargetDetails, type PostgresPlanTargetDetails } from './planner-target-details';\n\nexport function buildAddColumnOperationIdentity(\n schema: string,\n tableName: string,\n columnName: string,\n): Pick<\n SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n 'id' | 'label' | 'summary' | 'target'\n> {\n return {\n id: `column.${tableName}.${columnName}`,\n label: `Add column ${columnName} to ${tableName}`,\n summary: `Adds column ${columnName} to table ${tableName}`,\n target: {\n id: 'postgres',\n details: buildTargetDetails('table', tableName, schema),\n },\n };\n}\n\nexport function buildAddNotNullColumnWithTemporaryDefaultOperation(options: {\n readonly schema: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly column: StorageColumn;\n readonly codecHooks: Map<string, CodecControlHooks>;\n readonly storageTypes: Record<string, StorageTypeInstance>;\n readonly temporaryDefault: string;\n}): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const { schema, tableName, columnName, column, codecHooks, storageTypes, temporaryDefault } =\n options;\n const qualified = qualifyTableName(schema, tableName);\n\n return {\n ...buildAddColumnOperationIdentity(schema, tableName, columnName),\n operationClass: 'additive',\n precheck: [\n {\n description: `ensure column \"${columnName}\" is missing`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName, exists: false }),\n },\n ],\n execute: [\n {\n description: `add column \"${columnName}\"`,\n sql: buildAddColumnSql(\n qualified,\n columnName,\n column,\n codecHooks,\n temporaryDefault,\n storageTypes,\n ),\n },\n {\n description: `drop temporary default from column \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified} ALTER COLUMN ${quoteIdentifier(columnName)} DROP DEFAULT`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName }),\n },\n {\n description: `verify column \"${columnName}\" is NOT NULL`,\n sql: columnNullabilityCheck({\n schema,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n },\n {\n description: `verify column \"${columnName}\" has no default after temporary default removal`,\n sql: columnHasNoDefaultCheck({ schema, table: tableName, column: columnName }),\n },\n ],\n };\n}\n","/**\n * Migration strategies.\n *\n * Each strategy examines the issue list, consumes issues it handles, and\n * returns the `PostgresOpFactoryCall[]` to address them. The issue planner\n * runs each strategy in order and routes whatever's left through\n * `mapIssueToCall`.\n *\n * The full ordered list is exported as `postgresPlannerStrategies` and is\n * used unchanged by both `migration plan` and `db update` / `db init`. The\n * two journeys differ only in `policy.allowedOperationClasses`:\n *\n * - When `'data'` is in the policy, data-safe strategies (NOT NULL backfill,\n * nullability tightening, unsafe type changes, enum shrink/rebuild) emit\n * `DataTransformCall` placeholders that the user fills in.\n * - When `'data'` is excluded, those strategies short-circuit so the\n * downstream walk-schema strategies (codec-hook type ops and temp-default\n * backfill) and `mapIssueToCall` defaults emit direct DDL instead.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlMigrationPlanOperation,\n} from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport type { SqlStorage, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport {\n AddColumnCall,\n AddEnumValuesCall,\n AlterColumnTypeCall,\n CreateEnumTypeCall,\n DataTransformCall,\n DropEnumTypeCall,\n type PostgresOpFactoryCall,\n RawSqlCall,\n RenameTypeCall,\n SetNotNullCall,\n} from './op-factory-call';\nimport {\n buildAddColumnSql,\n buildColumnDefaultSql,\n buildColumnTypeSql,\n} from './planner-ddl-builders';\nimport { resolveIdentityValue } from './planner-identity-values';\nimport {\n buildAddColumnOperationIdentity,\n buildAddNotNullColumnWithTemporaryDefaultOperation,\n} from './planner-recipes';\nimport { buildSchemaLookupMap, hasForeignKey, hasUniqueConstraint } from './planner-schema-lookup';\nimport {\n buildExpectedFormatType,\n columnExistsCheck,\n columnNullabilityCheck,\n qualifyTableName,\n tableIsEmptyCheck,\n} from './planner-sql-checks';\nimport { buildTargetDetails, type PostgresPlanTargetDetails } from './planner-target-details';\n\nconst REBUILD_SUFFIX = '__prisma_next_new';\n\n// ============================================================================\n// Strategy types\n// ============================================================================\n\n/**\n * Context passed to each migration strategy.\n *\n * Strategies read the source (`fromContract`), target (`toContract`), current\n * database state (`schema`), operation policy (`policy`), and component list\n * (`frameworkComponents`) to make planning decisions. `fromContract` is null\n * when no prior contract is available (e.g. `db update`, where the current\n * DB state is approximated via `schema`).\n */\nexport interface StrategyContext {\n readonly toContract: Contract<SqlStorage>;\n readonly fromContract: Contract<SqlStorage> | null;\n readonly schemaName: string;\n readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;\n readonly storageTypes: Readonly<Record<string, StorageTypeInstance>>;\n readonly schema: SqlSchemaIR;\n readonly policy: MigrationOperationPolicy;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}\n\n// ============================================================================\n// Call strategies (for issue planner)\n// ============================================================================\n\nexport type CallMigrationStrategy = (\n issues: readonly SchemaIssue[],\n context: StrategyContext,\n) =>\n | {\n kind: 'match';\n issues: readonly SchemaIssue[];\n calls: readonly PostgresOpFactoryCall[];\n /**\n * `true` for strategies that emit cohesive sequential recipes whose\n * calls must stay contiguous and in the returned order — e.g.\n * `enumChangeCallStrategy` (dataTransform → createEnumType →\n * dropEnumType), `notNullBackfillCallStrategy` (addColumn →\n * dataTransform → setNotNull). Defaults to `false`, which lets\n * `planIssues` hoist individual calls into their DDL sequencing bucket.\n */\n recipe?: boolean;\n }\n | { kind: 'no_match' };\n\nfunction buildColumnSpec(\n table: string,\n column: string,\n ctx: StrategyContext,\n overrides?: { nullable?: boolean },\n) {\n const col = ctx.toContract.storage.tables[table]?.columns[column];\n if (!col) throw new Error(`Column \"${table}\".\"${column}\" not found in destination contract`);\n const mutableHooks = ctx.codecHooks as Map<string, CodecControlHooks>;\n const mutableTypes = ctx.storageTypes as Record<string, StorageTypeInstance>;\n return {\n name: column,\n typeSql: buildColumnTypeSql(col, mutableHooks, mutableTypes),\n defaultSql: buildColumnDefaultSql(col.default, col),\n nullable: overrides?.nullable ?? col.nullable,\n };\n}\n\nfunction buildAlterTypeOptions(\n table: string,\n column: string,\n ctx: StrategyContext,\n using?: string,\n) {\n const col = ctx.toContract.storage.tables[table]?.columns[column];\n if (!col) throw new Error(`Column \"${table}\".\"${column}\" not found in destination contract`);\n const mutableHooks = ctx.codecHooks as Map<string, CodecControlHooks>;\n const mutableTypes = ctx.storageTypes as Record<string, StorageTypeInstance>;\n const qualifiedTargetType = buildColumnTypeSql(col, mutableHooks, mutableTypes, false);\n const formatTypeExpected = buildExpectedFormatType(col, mutableHooks, mutableTypes);\n return {\n qualifiedTargetType,\n formatTypeExpected,\n rawTargetTypeForLabel: qualifiedTargetType,\n ...(using !== undefined ? { using } : {}),\n };\n}\n\nexport const notNullBackfillCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n // `DataTransformCall` is operation class `'data'`. When the policy excludes\n // it (`db update` / `db init`), skip so `notNullAddColumnCallStrategy`\n // (temp-default backfill) or `mapIssueToCall` can take the issue.\n if (!ctx.policy.allowedOperationClasses.includes('data')) return { kind: 'no_match' };\n\n const matched: SchemaIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n for (const issue of issues) {\n if (issue.kind !== 'missing_column' || !issue.table || !issue.column) continue;\n\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column) continue;\n if (column.nullable === true || column.default !== undefined) continue;\n\n matched.push(issue);\n const spec = buildColumnSpec(issue.table, issue.column, ctx, { nullable: true });\n calls.push(\n new AddColumnCall(ctx.schemaName, issue.table, spec),\n new DataTransformCall(\n `backfill-${issue.table}-${issue.column}`,\n `backfill-${issue.table}-${issue.column}:check`,\n `backfill-${issue.table}-${issue.column}:run`,\n ),\n new SetNotNullCall(ctx.schemaName, issue.table, issue.column),\n );\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n recipe: true,\n };\n};\n\nconst SAFE_WIDENINGS = new Set(['int2→int4', 'int2→int8', 'int4→int8', 'float4→float8']);\n\nexport const typeChangeCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n // For unsafe widenings this strategy emits a `DataTransformCall` placeholder\n // (operation class `'data'`); when the policy excludes `'data'`\n // (`db update` / `db init`), skip those issues so `mapIssueToCall` can\n // emit a direct `ALTER COLUMN TYPE`. Safe widenings still flow through\n // here because the resulting `AlterColumnTypeCall` is `widening`-class.\n const dataAllowed = ctx.policy.allowedOperationClasses.includes('data');\n\n const matched: SchemaIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n for (const issue of issues) {\n if (issue.kind !== 'type_mismatch') continue;\n if (!issue.table || !issue.column) continue;\n const fromColumn = ctx.fromContract?.storage.tables[issue.table]?.columns[issue.column];\n const toColumn = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!fromColumn || !toColumn) continue;\n const fromType = fromColumn.nativeType;\n const toType = toColumn.nativeType;\n if (fromType === toType) continue;\n const isSafeWidening = SAFE_WIDENINGS.has(`${fromType}→${toType}`);\n if (!isSafeWidening && !dataAllowed) continue;\n matched.push(issue);\n const alterOpts = buildAlterTypeOptions(issue.table, issue.column, ctx);\n if (isSafeWidening) {\n calls.push(new AlterColumnTypeCall(ctx.schemaName, issue.table, issue.column, alterOpts));\n } else {\n calls.push(\n new DataTransformCall(\n `typechange-${issue.table}-${issue.column}`,\n `typechange-${issue.table}-${issue.column}:check`,\n `typechange-${issue.table}-${issue.column}:run`,\n ),\n new AlterColumnTypeCall(ctx.schemaName, issue.table, issue.column, alterOpts),\n );\n }\n }\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n recipe: true,\n };\n};\n\nexport const nullableTighteningCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n // `DataTransformCall` is operation class `'data'`. When the policy excludes\n // it (`db update` / `db init`), skip so `mapIssueToCall` emits a direct\n // `SET NOT NULL` instead.\n if (!ctx.policy.allowedOperationClasses.includes('data')) return { kind: 'no_match' };\n\n const matched: SchemaIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n for (const issue of issues) {\n if (issue.kind !== 'nullability_mismatch' || !issue.table || !issue.column) continue;\n\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column) continue;\n if (column.nullable === true) continue;\n\n matched.push(issue);\n calls.push(\n new DataTransformCall(\n `handle-nulls-${issue.table}-${issue.column}`,\n `handle-nulls-${issue.table}-${issue.column}:check`,\n `handle-nulls-${issue.table}-${issue.column}:run`,\n ),\n new SetNotNullCall(ctx.schemaName, issue.table, issue.column),\n );\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n recipe: true,\n };\n};\n\nfunction enumRebuildCallRecipe(\n typeName: string,\n ctx: StrategyContext,\n): readonly PostgresOpFactoryCall[] {\n const toType = ctx.toContract.storage.types?.[typeName];\n if (!toType) return [];\n const nativeType = toType.nativeType;\n const desiredValues = (toType.typeParams['values'] ?? []) as readonly string[];\n const tempName = `${nativeType}${REBUILD_SUFFIX}`;\n\n const columnRefs: { table: string; column: string }[] = [];\n for (const [tableName, table] of Object.entries(ctx.toContract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (column.typeRef === typeName) {\n columnRefs.push({ table: tableName, column: columnName });\n }\n }\n }\n\n return [\n new CreateEnumTypeCall(ctx.schemaName, tempName, desiredValues),\n ...columnRefs.map((ref) => {\n const using = `${ref.column}::text::${tempName}`;\n return new AlterColumnTypeCall(ctx.schemaName, ref.table, ref.column, {\n qualifiedTargetType: tempName,\n formatTypeExpected: tempName,\n rawTargetTypeForLabel: tempName,\n using,\n });\n }),\n new DropEnumTypeCall(ctx.schemaName, nativeType),\n new RenameTypeCall(ctx.schemaName, tempName, nativeType),\n ];\n}\n\nexport const enumChangeCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n // The shrink/rebuild branches emit a `DataTransformCall` placeholder or a\n // destructive rebuild that should be authored explicitly. When the policy\n // excludes `'data'` (`db update` / `db init`), skip the entire strategy so\n // `storageTypePlanCallStrategy` (codec-hook driven) takes over with the\n // dev-push enum behavior.\n if (!ctx.policy.allowedOperationClasses.includes('data')) return { kind: 'no_match' };\n\n const matched: SchemaIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n for (const issue of issues) {\n if (issue.kind !== 'enum_values_changed') continue;\n matched.push(issue);\n\n if (issue.removedValues.length > 0) {\n calls.push(\n new DataTransformCall(\n `migrate-${issue.typeName}-values`,\n `migrate-${issue.typeName}-values:check`,\n `migrate-${issue.typeName}-values:run`,\n ),\n ...enumRebuildCallRecipe(issue.typeName, ctx),\n );\n } else if (issue.addedValues.length === 0) {\n calls.push(...enumRebuildCallRecipe(issue.typeName, ctx));\n } else {\n const toType = ctx.toContract.storage.types?.[issue.typeName];\n if (toType) {\n calls.push(\n new AddEnumValuesCall(\n ctx.schemaName,\n issue.typeName,\n toType.nativeType,\n issue.addedValues,\n ),\n );\n }\n }\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n recipe: true,\n };\n};\n\n// ============================================================================\n// Walk-schema strategies (absorbed from the legacy planner)\n// ============================================================================\n\n/**\n * Dispatches storage types through their codec's `planTypeOperations` hook.\n * Replaces the walk-schema `buildStorageTypeOperations` path: the hook is\n * the authoritative source for codec-driven DDL (enum create/rebuild/add-\n * value, custom type creation, etc.).\n *\n * Runs after `enumChangeCallStrategy` so the structured enum path (value\n * add, rebuild recipe) gets first pick at `enum_values_changed` issues;\n * this strategy then handles remaining `type_missing` / `enum_values_changed`\n * issues for types whose hook produced at least one op.\n */\nexport const storageTypePlanCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n const storageTypes = ctx.toContract.storage.types ?? {};\n if (Object.keys(storageTypes).length === 0) return { kind: 'no_match' };\n\n const calls: PostgresOpFactoryCall[] = [];\n const handledTypeNames = new Set<string>();\n\n for (const [typeName, typeInstance] of Object.entries(storageTypes).sort(([a], [b]) =>\n a.localeCompare(b),\n )) {\n const hook = ctx.codecHooks.get(typeInstance.codecId);\n if (!hook?.planTypeOperations) continue;\n const planResult = hook.planTypeOperations({\n typeName,\n typeInstance,\n contract: ctx.toContract,\n schema: ctx.schema,\n schemaName: ctx.schemaName,\n policy: ctx.policy,\n });\n if (!planResult) continue;\n if (planResult.operations.length === 0) {\n handledTypeNames.add(typeName);\n continue;\n }\n handledTypeNames.add(typeName);\n for (const op of planResult.operations) {\n calls.push(\n new RawSqlCall({\n ...op,\n target: {\n id: op.target.id,\n details: buildTargetDetails('type', typeName, ctx.schemaName),\n },\n } as SqlMigrationPlanOperation<PostgresPlanTargetDetails>),\n );\n }\n }\n\n const remaining = issues.filter(\n (issue) =>\n !(\n (issue.kind === 'type_missing' || issue.kind === 'enum_values_changed') &&\n issue.typeName &&\n handledTypeNames.has(issue.typeName)\n ),\n );\n\n if (calls.length === 0 && remaining.length === issues.length) {\n return { kind: 'no_match' };\n }\n\n return { kind: 'match', issues: remaining, calls };\n};\n\n/**\n * Handles `missing_column` issues for NOT NULL columns without a contract\n * default. Replaces the walk-schema `buildAddColumnItem` non-default branches.\n *\n * Two shapes:\n * - Shared-temp-default safe: emit a single atomic composite op (add\n * nullable → backfill identity value → `SET NOT NULL` → `DROP DEFAULT`).\n * - Empty-table guarded: emit a hand-built op with a `tableIsEmptyCheck`\n * precheck so the failure message is \"table is not empty\" rather than the\n * raw PG NOT NULL violation.\n *\n * \"Normal\" missing_column cases (nullable or has a contract default) are left\n * for `mapIssueToCall`'s default `AddColumnCall` emission.\n */\nexport const notNullAddColumnCallStrategy: CallMigrationStrategy = (issues, ctx) => {\n const matched: SchemaIssue[] = [];\n const calls: PostgresOpFactoryCall[] = [];\n\n const schemaLookups = buildSchemaLookupMap(ctx.schema);\n\n const mutableCodecHooks = ctx.codecHooks as Map<string, CodecControlHooks>;\n const mutableStorageTypes = ctx.storageTypes as Record<string, StorageTypeInstance>;\n\n for (const issue of issues) {\n if (issue.kind !== 'missing_column' || !issue.table || !issue.column) continue;\n const contractTable = ctx.toContract.storage.tables[issue.table];\n const column = contractTable?.columns[issue.column];\n if (!column) continue;\n\n const notNull = column.nullable !== true;\n const hasDefault = column.default !== undefined;\n if (!notNull || hasDefault) continue;\n\n const schemaTable = ctx.schema.tables[issue.table];\n if (!schemaTable) continue;\n\n const temporaryDefault = resolveIdentityValue(column, mutableCodecHooks, mutableStorageTypes);\n const schemaLookup = schemaLookups.get(issue.table);\n const canUseSharedTempDefault =\n temporaryDefault !== null &&\n canUseSharedTemporaryDefaultStrategy({\n table: contractTable,\n schemaTable,\n schemaLookup,\n columnName: issue.column,\n });\n\n matched.push(issue);\n\n if (canUseSharedTempDefault && temporaryDefault !== null) {\n calls.push(\n new RawSqlCall(\n buildAddNotNullColumnWithTemporaryDefaultOperation({\n schema: ctx.schemaName,\n tableName: issue.table,\n columnName: issue.column,\n column,\n codecHooks: mutableCodecHooks,\n storageTypes: mutableStorageTypes,\n temporaryDefault,\n }),\n ),\n );\n continue;\n }\n\n const qualified = qualifyTableName(ctx.schemaName, issue.table);\n calls.push(\n new RawSqlCall({\n ...buildAddColumnOperationIdentity(ctx.schemaName, issue.table, issue.column),\n operationClass: 'additive',\n precheck: [\n {\n description: `ensure column \"${issue.column}\" is missing`,\n sql: columnExistsCheck({\n schema: ctx.schemaName,\n table: issue.table,\n column: issue.column,\n exists: false,\n }),\n },\n {\n description: `ensure table \"${issue.table}\" is empty before adding NOT NULL column without default`,\n sql: tableIsEmptyCheck(qualified),\n },\n ],\n execute: [\n {\n description: `add column \"${issue.column}\"`,\n sql: buildAddColumnSql(\n qualified,\n issue.column,\n column,\n mutableCodecHooks,\n undefined,\n mutableStorageTypes,\n ),\n },\n ],\n postcheck: [\n {\n description: `verify column \"${issue.column}\" exists`,\n sql: columnExistsCheck({\n schema: ctx.schemaName,\n table: issue.table,\n column: issue.column,\n }),\n },\n {\n description: `verify column \"${issue.column}\" is NOT NULL`,\n sql: columnNullabilityCheck({\n schema: ctx.schemaName,\n table: issue.table,\n column: issue.column,\n nullable: false,\n }),\n },\n ],\n }),\n );\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n calls,\n };\n};\n\n// ============================================================================\n// Strategy helpers\n// ============================================================================\n\nfunction canUseSharedTemporaryDefaultStrategy(options: {\n readonly table: NonNullable<Contract<SqlStorage>['storage']['tables'][string]>;\n readonly schemaTable: SqlSchemaIR['tables'][string];\n readonly schemaLookup: ReturnType<typeof buildSchemaLookupMap> extends ReadonlyMap<\n string,\n infer V\n >\n ? V | undefined\n : never;\n readonly columnName: string;\n}): boolean {\n const { table, schemaTable, schemaLookup, columnName } = options;\n\n if (table.primaryKey?.columns.includes(columnName) && !schemaTable.primaryKey) {\n return false;\n }\n\n for (const unique of table.uniques) {\n if (!unique.columns.includes(columnName)) continue;\n if (!schemaLookup || !hasUniqueConstraint(schemaLookup, unique.columns)) return false;\n }\n\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.constraint === false || !foreignKey.columns.includes(columnName)) continue;\n if (!schemaLookup || !hasForeignKey(schemaLookup, foreignKey)) return false;\n }\n\n return true;\n}\n\n/**\n * Ordered list of Postgres planner strategies, shared by `migration plan`\n * and `db update` / `db init`. The issue planner runs each strategy in\n * order, letting it consume any issues it handles, and routes whatever's\n * left through `mapIssueToCall`. Behavior diverges purely on\n * `policy.allowedOperationClasses`:\n *\n * - When `'data'` is allowed (`migration plan`), the data-safe strategies\n * (`enumChangeCallStrategy`, `notNullBackfillCallStrategy`,\n * `typeChangeCallStrategy`, `nullableTighteningCallStrategy`) consume their\n * matching issues and emit `DataTransformCall` placeholders or recipe ops.\n *\n * - When `'data'` is not allowed (`db update` / `db init`), each data-safe\n * strategy short-circuits to `no_match`, leaving the issue for the\n * downstream walk-schema strategies (`storageTypePlanCallStrategy`,\n * `notNullAddColumnCallStrategy`) or the `mapIssueToCall` default to handle\n * with direct DDL.\n *\n * Order matters: data-safe strategies must run before the walk-schema\n * strategies on overlapping issue kinds (e.g. `enum_values_changed`,\n * `missing_column` for NOT NULL) so they take priority when active.\n */\nexport const postgresPlannerStrategies: readonly CallMigrationStrategy[] = [\n enumChangeCallStrategy,\n notNullBackfillCallStrategy,\n typeChangeCallStrategy,\n nullableTighteningCallStrategy,\n storageTypePlanCallStrategy,\n notNullAddColumnCallStrategy,\n];\n","/**\n * Postgres migration planner.\n *\n * Takes schema issues (from verifySqlSchema) and emits migration IR\n * (`PostgresOpFactoryCall[]`). Strategies consume issues they recognize and\n * produce specialized call sequences (e.g. NOT NULL backfill →\n * addColumn(nullable) + dataTransform + setNotNull); remaining issues flow\n * through `mapIssueToCall` for the default case.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlPlannerConflict,\n SqlPlannerConflictLocation,\n} from '@prisma-next/family-sql/control';\nimport { arraysEqual } from '@prisma-next/family-sql/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport type {\n SqlStorage,\n StorageColumn,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport {\n AddColumnCall,\n AddForeignKeyCall,\n AddPrimaryKeyCall,\n AddUniqueCall,\n AlterColumnTypeCall,\n CreateEnumTypeCall,\n CreateIndexCall,\n CreateTableCall,\n DropColumnCall,\n DropConstraintCall,\n DropDefaultCall,\n DropIndexCall,\n DropNotNullCall,\n DropTableCall,\n type PostgresOpFactoryCall,\n SetDefaultCall,\n SetNotNullCall,\n} from './op-factory-call';\nimport type { ColumnSpec, ForeignKeySpec } from './operations/shared';\nimport { buildColumnDefaultSql, buildColumnTypeSql } from './planner-ddl-builders';\nimport { buildExpectedFormatType } from './planner-sql-checks';\nimport {\n type CallMigrationStrategy,\n postgresPlannerStrategies,\n type StrategyContext,\n} from './planner-strategies';\n\nexport type { CallMigrationStrategy, StrategyContext };\n\n// ============================================================================\n// Issue kind ordering (dependency order)\n// ============================================================================\n\nconst ISSUE_KIND_ORDER: Record<string, number> = {\n // Types first\n type_missing: 2,\n type_values_mismatch: 3,\n enum_values_changed: 3,\n\n // Drops (reconciliation — clear the way for creates)\n // FKs dropped first (they depend on other constraints)\n extra_foreign_key: 10,\n extra_unique_constraint: 11,\n extra_primary_key: 12,\n extra_index: 13,\n extra_default: 14,\n extra_column: 15,\n extra_table: 16,\n\n // Tables before columns\n missing_table: 20,\n\n // Columns before constraints\n missing_column: 30,\n\n // Reconciliation alters (on existing objects)\n type_mismatch: 40,\n nullability_mismatch: 41,\n default_missing: 42,\n default_mismatch: 43,\n\n // Constraints after columns exist\n primary_key_mismatch: 50,\n unique_constraint_mismatch: 51,\n index_mismatch: 52,\n foreign_key_mismatch: 60,\n};\n\nfunction issueOrder(issue: SchemaIssue): number {\n return ISSUE_KIND_ORDER[issue.kind] ?? 99;\n}\n\n// ============================================================================\n// Conflict helpers\n// ============================================================================\n\nfunction issueConflict(\n kind: SqlPlannerConflict['kind'],\n summary: string,\n location?: SqlPlannerConflict['location'],\n): SqlPlannerConflict {\n return {\n kind,\n summary,\n why: 'Use `migration new` to author a custom migration for this change.',\n ...(location ? { location } : {}),\n };\n}\n\nfunction isMissing(issue: SchemaIssue): boolean {\n if (issue.kind === 'enum_values_changed') return false;\n return issue.actual === undefined;\n}\n\n// ============================================================================\n// Issue planner\n// ============================================================================\n\nexport interface IssuePlannerOptions {\n readonly issues: readonly SchemaIssue[];\n readonly toContract: Contract<SqlStorage>;\n readonly fromContract: Contract<SqlStorage> | null;\n readonly schemaName: string;\n readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;\n readonly storageTypes: Readonly<Record<string, StorageTypeInstance>>;\n /**\n * Current database schema IR. Strategies read this to detect whether a\n * structure already exists (e.g. `buildSchemaLookupMap` for shared-temp-\n * default safety, extension dependency checks). Defaults to an empty schema\n * when omitted so the planner can still run over \"fresh DB\" contract\n * snapshots.\n */\n readonly schema?: SqlSchemaIR;\n /**\n * Operation-class policy. `planIssues` filters calls whose `operationClass`\n * is not in `policy.allowedOperationClasses` and surfaces them as conflicts\n * instead of emitting disallowed DDL. Defaults to additive-only.\n */\n readonly policy?: MigrationOperationPolicy;\n /**\n * Framework components participating in this composition. Available to\n * future strategies that may consult component metadata at plan time.\n */\n readonly frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n readonly strategies?: readonly CallMigrationStrategy[];\n}\n\nexport interface IssuePlannerValue {\n readonly calls: readonly PostgresOpFactoryCall[];\n}\n\nfunction toColumnSpec(\n name: string,\n column: StorageColumn,\n codecHooks: ReadonlyMap<string, CodecControlHooks>,\n storageTypes: Readonly<Record<string, StorageTypeInstance>>,\n): ColumnSpec {\n return {\n name,\n typeSql: buildColumnTypeSql(\n column,\n codecHooks as Map<string, CodecControlHooks>,\n storageTypes as Record<string, StorageTypeInstance>,\n ),\n defaultSql: buildColumnDefaultSql(column.default, column),\n nullable: column.nullable,\n };\n}\n\nfunction mapIssueToCall(\n issue: SchemaIssue,\n ctx: StrategyContext,\n): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {\n const { schemaName, codecHooks, storageTypes } = ctx;\n\n switch (issue.kind) {\n case 'missing_table': {\n if (!issue.table)\n return notOk(\n issueConflict('unsupportedOperation', 'Missing table issue has no table name'),\n );\n const contractTable = ctx.toContract.storage.tables[issue.table];\n if (!contractTable) {\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Table \"${issue.table}\" reported missing but not found in destination contract`,\n ),\n );\n }\n const columns: ColumnSpec[] = Object.entries(contractTable.columns).map(([name, column]) =>\n toColumnSpec(name, column, codecHooks, storageTypes),\n );\n const primaryKey = contractTable.primaryKey\n ? { columns: contractTable.primaryKey.columns }\n : undefined;\n const calls: PostgresOpFactoryCall[] = [\n new CreateTableCall(schemaName, issue.table, columns, primaryKey),\n ];\n for (const index of contractTable.indexes) {\n const indexName = index.name ?? `${issue.table}_${index.columns.join('_')}_idx`;\n const extras: { type?: string; options?: Record<string, unknown> } = {};\n if (index.type !== undefined) extras.type = index.type;\n if (index.options !== undefined) extras.options = index.options;\n calls.push(\n new CreateIndexCall(schemaName, issue.table, indexName, [...index.columns], extras),\n );\n }\n const explicitIndexColumnSets = new Set(\n contractTable.indexes.map((idx) => idx.columns.join(',')),\n );\n for (const fk of contractTable.foreignKeys) {\n if (fk.constraint) {\n const fkName = fk.name ?? `${issue.table}_${fk.columns.join('_')}_fkey`;\n const fkSpec: ForeignKeySpec = {\n name: fkName,\n columns: fk.columns,\n references: { table: fk.references.table, columns: fk.references.columns },\n ...(fk.onDelete !== undefined && { onDelete: fk.onDelete }),\n ...(fk.onUpdate !== undefined && { onUpdate: fk.onUpdate }),\n };\n calls.push(new AddForeignKeyCall(schemaName, issue.table, fkSpec));\n }\n if (fk.index && !explicitIndexColumnSets.has(fk.columns.join(','))) {\n const indexName = `${issue.table}_${fk.columns.join('_')}_idx`;\n calls.push(new CreateIndexCall(schemaName, issue.table, indexName, [...fk.columns]));\n }\n }\n for (const unique of contractTable.uniques) {\n const constraintName = unique.name ?? `${issue.table}_${unique.columns.join('_')}_key`;\n calls.push(new AddUniqueCall(schemaName, issue.table, constraintName, [...unique.columns]));\n }\n return ok(calls);\n }\n\n case 'missing_column':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Missing column issue has no table/column name'),\n );\n {\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column)\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Column \"${issue.table}\".\"${issue.column}\" not in destination contract`,\n ),\n );\n return ok([\n new AddColumnCall(\n schemaName,\n issue.table,\n toColumnSpec(issue.column, column, codecHooks, storageTypes),\n ),\n ]);\n }\n\n case 'default_missing':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Default missing issue has no table/column name'),\n );\n {\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column?.default) {\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Column \"${issue.table}\".\"${issue.column}\" has no default in contract`,\n ),\n );\n }\n const defaultSql = buildColumnDefaultSql(column.default, column);\n if (!defaultSql) return ok([]);\n return ok([new SetDefaultCall(schemaName, issue.table, issue.column, defaultSql)]);\n }\n\n case 'extra_table':\n if (!issue.table)\n return notOk(issueConflict('unsupportedOperation', 'Extra table issue has no table name'));\n return ok([new DropTableCall(schemaName, issue.table)]);\n\n case 'extra_column':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Extra column issue has no table/column name'),\n );\n return ok([new DropColumnCall(schemaName, issue.table, issue.column)]);\n\n case 'extra_index':\n if (!issue.table || !issue.indexOrConstraint)\n return notOk(\n issueConflict('unsupportedOperation', 'Extra index issue has no table/index name'),\n );\n return ok([new DropIndexCall(schemaName, issue.table, issue.indexOrConstraint)]);\n\n case 'extra_unique_constraint':\n case 'extra_foreign_key':\n case 'extra_primary_key': {\n if (!issue.table)\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n 'Extra constraint issue has no table/constraint name',\n ),\n );\n // `extra_primary_key` issues don't carry a constraint name — the\n // verifier only has the table. Fall back to `<table>_pkey`, matching\n // Postgres' default PK constraint naming and the old reconciliation\n // planner's behavior.\n const constraintName =\n issue.indexOrConstraint ??\n (issue.kind === 'extra_primary_key' ? `${issue.table}_pkey` : undefined);\n if (!constraintName)\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n 'Extra constraint issue has no table/constraint name',\n ),\n );\n const kindMap = {\n extra_unique_constraint: 'unique' as const,\n extra_foreign_key: 'foreignKey' as const,\n extra_primary_key: 'primaryKey' as const,\n };\n return ok([\n new DropConstraintCall(schemaName, issue.table, constraintName, kindMap[issue.kind]),\n ]);\n }\n\n case 'extra_default':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Extra default issue has no table/column name'),\n );\n return ok([new DropDefaultCall(schemaName, issue.table, issue.column)]);\n\n case 'nullability_mismatch': {\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('nullabilityConflict', 'Nullability mismatch has no table/column name'),\n );\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column)\n return notOk(\n issueConflict(\n 'nullabilityConflict',\n `Column \"${issue.table}\".\"${issue.column}\" not found in destination contract`,\n ),\n );\n return ok(\n column.nullable\n ? [new DropNotNullCall(schemaName, issue.table, issue.column)]\n : [new SetNotNullCall(schemaName, issue.table, issue.column)],\n );\n }\n\n case 'type_mismatch':\n if (!issue.table || !issue.column)\n return notOk(issueConflict('typeMismatch', 'Type mismatch has no table/column name'));\n {\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column)\n return notOk(\n issueConflict(\n 'typeMismatch',\n `Column \"${issue.table}\".\"${issue.column}\" not in destination contract`,\n ),\n );\n const hooksMap = codecHooks as Map<string, CodecControlHooks>;\n const typesMap = storageTypes as Record<string, StorageTypeInstance>;\n const qualifiedTargetType = buildColumnTypeSql(column, hooksMap, typesMap, false);\n const formatTypeExpected = buildExpectedFormatType(column, hooksMap, typesMap);\n return ok([\n new AlterColumnTypeCall(schemaName, issue.table, issue.column, {\n qualifiedTargetType,\n formatTypeExpected,\n rawTargetTypeForLabel: qualifiedTargetType,\n }),\n ]);\n }\n\n case 'default_mismatch':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Default mismatch has no table/column name'),\n );\n {\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column?.default) return ok([]);\n const defaultSql = buildColumnDefaultSql(column.default, column);\n if (!defaultSql) return ok([]);\n return ok([\n new SetDefaultCall(schemaName, issue.table, issue.column, defaultSql, 'widening'),\n ]);\n }\n\n case 'primary_key_mismatch':\n if (!issue.table)\n return notOk(issueConflict('indexIncompatible', 'Primary key issue has no table name'));\n if (isMissing(issue)) {\n const pk = ctx.toContract.storage.tables[issue.table]?.primaryKey;\n if (!pk)\n return notOk(\n issueConflict('indexIncompatible', `No primary key in contract for \"${issue.table}\"`),\n );\n const constraintName = pk.name ?? `${issue.table}_pkey`;\n return ok([new AddPrimaryKeyCall(schemaName, issue.table, constraintName, pk.columns)]);\n }\n return notOk(\n issueConflict(\n 'indexIncompatible',\n `Primary key on \"${issue.table}\" has different columns (expected: ${issue.expected}, actual: ${issue.actual})`,\n { table: issue.table },\n ),\n );\n\n case 'unique_constraint_mismatch':\n if (!issue.table)\n return notOk(\n issueConflict('indexIncompatible', 'Unique constraint issue has no table name'),\n );\n if (isMissing(issue) && issue.expected) {\n const columns = issue.expected.split(', ');\n const constraintName = `${issue.table}_${columns.join('_')}_key`;\n return ok([new AddUniqueCall(schemaName, issue.table, constraintName, columns)]);\n }\n return notOk(\n issueConflict(\n 'indexIncompatible',\n `Unique constraint on \"${issue.table}\" differs (expected: ${issue.expected}, actual: ${issue.actual})`,\n { table: issue.table },\n ),\n );\n\n case 'index_mismatch':\n if (!issue.table)\n return notOk(issueConflict('indexIncompatible', 'Index issue has no table name'));\n if (isMissing(issue) && issue.expected) {\n const columns = issue.expected.split(', ');\n const contractIndex = ctx.toContract.storage.tables[issue.table]?.indexes.find((idx) =>\n arraysEqual(idx.columns, columns),\n );\n const indexName = contractIndex?.name ?? `${issue.table}_${columns.join('_')}_idx`;\n const extras: { type?: string; options?: Record<string, unknown> } = {};\n if (contractIndex?.type !== undefined) extras.type = contractIndex.type;\n if (contractIndex?.options !== undefined) extras.options = contractIndex.options;\n return ok([new CreateIndexCall(schemaName, issue.table, indexName, columns, extras)]);\n }\n return notOk(\n issueConflict(\n 'indexIncompatible',\n `Index on \"${issue.table}\" differs (expected: ${issue.expected}, actual: ${issue.actual})`,\n { table: issue.table },\n ),\n );\n\n case 'foreign_key_mismatch':\n if (!issue.table)\n return notOk(issueConflict('foreignKeyConflict', 'Foreign key issue has no table name'));\n if (isMissing(issue) && issue.expected) {\n const arrowIdx = issue.expected.indexOf(' -> ');\n if (arrowIdx >= 0) {\n const columns = issue.expected.slice(0, arrowIdx).split(', ');\n const fkName = `${issue.table}_${columns.join('_')}_fkey`;\n const fk = ctx.toContract.storage.tables[issue.table]?.foreignKeys.find(\n (k) => k.columns.join(', ') === columns.join(', '),\n );\n if (fk) {\n const fkSpec: ForeignKeySpec = {\n name: fkName,\n columns: fk.columns,\n references: { table: fk.references.table, columns: fk.references.columns },\n ...(fk.onDelete !== undefined && { onDelete: fk.onDelete }),\n ...(fk.onUpdate !== undefined && { onUpdate: fk.onUpdate }),\n };\n return ok([new AddForeignKeyCall(schemaName, issue.table, fkSpec)]);\n }\n return notOk(\n issueConflict(\n 'foreignKeyConflict',\n `Foreign key on \"${issue.table}\" (${columns.join(', ')}) not found in destination contract`,\n { table: issue.table },\n ),\n );\n }\n }\n return notOk(\n issueConflict(\n 'foreignKeyConflict',\n `Foreign key on \"${issue.table}\" differs (expected: ${issue.expected}, actual: ${issue.actual})`,\n { table: issue.table },\n ),\n );\n\n case 'type_missing': {\n if (!issue.typeName)\n return notOk(issueConflict('unsupportedOperation', 'Type missing issue has no typeName'));\n const typeInstance = ctx.toContract.storage.types?.[issue.typeName];\n if (!typeInstance) {\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Type \"${issue.typeName}\" reported missing but not found in destination contract`,\n ),\n );\n }\n if (typeInstance.codecId.startsWith('pg/enum')) {\n const values = (typeInstance.typeParams['values'] ?? []) as readonly string[];\n return ok([new CreateEnumTypeCall(schemaName, typeInstance.nativeType, values)]);\n }\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Type \"${issue.typeName}\" uses codec \"${typeInstance.codecId}\" — only enum types are supported`,\n ),\n );\n }\n\n case 'type_values_mismatch':\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Type \"${issue.typeName ?? 'unknown'}\" values differ — type alteration not yet supported`,\n ),\n );\n\n default:\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Unhandled issue kind: ${(issue as SchemaIssue).kind}`,\n ),\n );\n }\n}\n\n/**\n * Classifies calls into dependency order categories for correct DDL sequencing.\n */\ntype CallCategory =\n | 'dep'\n | 'drop'\n | 'table'\n | 'column'\n | 'alter'\n | 'primaryKey'\n | 'unique'\n | 'index'\n | 'foreignKey';\n\n/**\n * Classifies calls into DDL sequencing buckets. The order matches the\n * legacy walk-schema planner's emission order so `db init` and `db update`\n * produce byte-identical plans for the shared shape (deps → drops → tables\n * → columns → alters → PKs → uniques → indexes → FKs).\n */\nfunction classifyCall(call: PostgresOpFactoryCall): CallCategory {\n switch (call.factoryName) {\n case 'createExtension':\n case 'createSchema':\n case 'createEnumType':\n case 'addEnumValues':\n case 'dropEnumType':\n case 'renameType':\n return 'dep';\n case 'dropTable':\n case 'dropColumn':\n case 'dropConstraint':\n case 'dropIndex':\n case 'dropDefault':\n return 'drop';\n case 'createTable':\n return 'table';\n case 'addColumn':\n return 'column';\n case 'alterColumnType':\n case 'setNotNull':\n case 'dropNotNull':\n case 'setDefault':\n return 'alter';\n case 'addPrimaryKey':\n return 'primaryKey';\n case 'addUnique':\n return 'unique';\n case 'createIndex':\n return 'index';\n case 'addForeignKey':\n return 'foreignKey';\n case 'rawSql': {\n // Type ops lifted through `RawSqlCall` by `storageTypePlanCallStrategy`\n // to preserve the codec-emitted label and precheck/postcheck.\n // Classification falls back to inspecting the underlying op's target\n // details (`objectType: 'type'`).\n const op = (\n call as {\n op?: {\n target?: { details?: { objectType?: string } };\n };\n }\n ).op;\n const objectType = op?.target?.details?.objectType;\n if (objectType === 'type') return 'dep';\n return 'alter';\n }\n default:\n return 'alter';\n }\n}\n\n/** Stable lexical key used to order issues within the same kind bucket. */\nfunction issueKey(issue: SchemaIssue): string {\n const table = 'table' in issue && typeof issue.table === 'string' ? issue.table : '';\n const column = 'column' in issue && typeof issue.column === 'string' ? issue.column : '';\n const name =\n 'indexOrConstraint' in issue && typeof issue.indexOrConstraint === 'string'\n ? issue.indexOrConstraint\n : '';\n return `${table}\\u0000${column}\\u0000${name}`;\n}\n\n// When no policy is explicitly supplied (test-only path; production callers\n// always pass one), allow every class so strategies that gate on\n// `'data'` (data-safe placeholders) still fire — the test is treated as\n// trusted. Filtering of actual emitted calls only runs when a policy was\n// explicitly provided (see `policyProvided` below).\nconst DEFAULT_POLICY: MigrationOperationPolicy = {\n allowedOperationClasses: ['additive', 'widening', 'destructive', 'data'],\n};\n\nfunction emptySchemaIR(): SqlSchemaIR {\n return { tables: {} };\n}\n\nfunction conflictKindForCall(call: PostgresOpFactoryCall): SqlPlannerConflict['kind'] {\n switch (call.factoryName) {\n case 'alterColumnType':\n return 'typeMismatch';\n case 'setNotNull':\n case 'dropNotNull':\n return 'nullabilityConflict';\n case 'addForeignKey':\n case 'dropConstraint':\n return 'foreignKeyConflict';\n case 'createIndex':\n case 'dropIndex':\n return 'indexIncompatible';\n default:\n return 'missingButNonAdditive';\n }\n}\n\nfunction locationForCall(call: PostgresOpFactoryCall): SqlPlannerConflict['location'] | undefined {\n // Most Postgres call classes expose `tableName`/`columnName`/`indexName`/\n // `constraintName` as readonly fields. We avoid `toOp()` here because a\n // `DataTransformCall` intentionally throws from `toOp`.\n const anyCall = call as unknown as {\n tableName?: string;\n columnName?: string;\n indexName?: string;\n constraintName?: string;\n typeName?: string;\n };\n const location: {\n table?: string;\n column?: string;\n index?: string;\n constraint?: string;\n type?: string;\n } = {};\n if (anyCall.tableName) location.table = anyCall.tableName;\n if (anyCall.columnName) location.column = anyCall.columnName;\n if (anyCall.indexName) location.index = anyCall.indexName;\n if (anyCall.constraintName) location.constraint = anyCall.constraintName;\n if (anyCall.typeName) location.type = anyCall.typeName;\n return Object.keys(location).length > 0 ? (location as SqlPlannerConflictLocation) : undefined;\n}\n\nfunction conflictForDisallowedCall(\n call: PostgresOpFactoryCall,\n allowed: readonly string[],\n): SqlPlannerConflict {\n const summary = `Operation \"${call.label}\" requires class \"${call.operationClass}\", but policy allows only: ${allowed.join(', ')}`;\n const location = locationForCall(call);\n return {\n kind: conflictKindForCall(call),\n summary,\n why: 'Use `migration new` to author a custom migration for this change.',\n ...(location ? { location } : {}),\n };\n}\n\nexport function planIssues(\n options: IssuePlannerOptions,\n): Result<IssuePlannerValue, readonly SqlPlannerConflict[]> {\n // When no policy is supplied, `planIssues` treats the call as trusted (the\n // caller — typically a test — has already vetted the issues). Only explicit\n // policies gate operation classes into conflicts.\n // `PostgresMigrationPlanner` always passes an explicit policy.\n const policyProvided = options.policy !== undefined;\n const policy = options.policy ?? DEFAULT_POLICY;\n const schema = options.schema ?? emptySchemaIR();\n const frameworkComponents = options.frameworkComponents ?? [];\n\n const context: StrategyContext = {\n toContract: options.toContract,\n fromContract: options.fromContract,\n schemaName: options.schemaName,\n codecHooks: options.codecHooks,\n storageTypes: options.storageTypes,\n schema,\n policy,\n frameworkComponents,\n };\n\n const strategies = options.strategies ?? postgresPlannerStrategies;\n\n let remaining = options.issues;\n const recipeCalls: PostgresOpFactoryCall[] = [];\n const bucketablePatternCalls: PostgresOpFactoryCall[] = [];\n\n for (const strategy of strategies) {\n const result = strategy(remaining, context);\n if (result.kind === 'match') {\n remaining = result.issues;\n if (result.recipe) {\n recipeCalls.push(...result.calls);\n } else {\n bucketablePatternCalls.push(...result.calls);\n }\n }\n }\n\n const sorted = [...remaining].sort((a, b) => {\n const kindDelta = issueOrder(a) - issueOrder(b);\n if (kindDelta !== 0) return kindDelta;\n const keyA = issueKey(a);\n const keyB = issueKey(b);\n return keyA < keyB ? -1 : keyA > keyB ? 1 : 0;\n });\n\n const defaultCalls: PostgresOpFactoryCall[] = [];\n const conflicts: SqlPlannerConflict[] = [];\n\n for (const issue of sorted) {\n const result = mapIssueToCall(issue, context);\n if (result.ok) {\n defaultCalls.push(...result.value);\n } else {\n conflicts.push(result.failure);\n }\n }\n\n // Policy gating: drop calls whose operation class is not allowed and\n // surface a conflict describing the disallowed op. Applies to both strategy\n // output and default-mapped output. Only active when the caller explicitly\n // supplied a policy — direct unit-test invocations (which pass no policy)\n // stay as pass-through and keep destructive recipe steps intact.\n const allowed = policy.allowedOperationClasses;\n let gatedDefault = defaultCalls;\n let gatedRecipe = recipeCalls;\n let gatedBucketable = bucketablePatternCalls;\n if (policyProvided) {\n const keepIfAllowed = (bucket: PostgresOpFactoryCall[]) => (call: PostgresOpFactoryCall) => {\n if (allowed.includes(call.operationClass)) {\n bucket.push(call);\n return;\n }\n conflicts.push(conflictForDisallowedCall(call, allowed));\n };\n const gatedDefaultBucket: PostgresOpFactoryCall[] = [];\n const gatedRecipeBucket: PostgresOpFactoryCall[] = [];\n const gatedBucketableBucket: PostgresOpFactoryCall[] = [];\n defaultCalls.forEach(keepIfAllowed(gatedDefaultBucket));\n recipeCalls.forEach(keepIfAllowed(gatedRecipeBucket));\n bucketablePatternCalls.forEach(keepIfAllowed(gatedBucketableBucket));\n gatedDefault = gatedDefaultBucket;\n gatedRecipe = gatedRecipeBucket;\n gatedBucketable = gatedBucketableBucket;\n }\n\n if (conflicts.length > 0) {\n return notOk(conflicts);\n }\n\n // Recipe strategies (`enumChangeCallStrategy`, `notNullBackfillCallStrategy`,\n // etc.) emit a cohesive sequence that must stay contiguous. They are\n // inserted at a single pattern slot. Non-recipe pattern strategies\n // (`dependencyInstallCallStrategy`, `storageTypePlanCallStrategy`,\n // `notNullAddColumnCallStrategy`) produce individually classifiable calls\n // that slot into DDL buckets alongside default-mapped calls.\n const combinedBucketable = [...gatedDefault, ...gatedBucketable];\n const byCategory = (cat: CallCategory) =>\n combinedBucketable.filter((c) => classifyCall(c) === cat);\n\n const calls: PostgresOpFactoryCall[] = [\n ...byCategory('dep'),\n ...byCategory('drop'),\n ...byCategory('table'),\n ...byCategory('column'),\n ...gatedRecipe,\n ...byCategory('alter'),\n ...byCategory('primaryKey'),\n ...byCategory('unique'),\n ...byCategory('index'),\n ...byCategory('foreignKey'),\n ];\n\n return ok({ calls });\n}\n"],"mappings":";;;;;;;;;;AAmBA,SAAgB,mBACd,YACA,MACA,QACA,OAC2B;CAC3B,OAAO;EACL;EACA;EACA;EACA,GAAG,UAAU,SAAS,MAAM;EAC7B;;;;AClBH,SAAgB,gCACd,QACA,WACA,YAIA;CACA,OAAO;EACL,IAAI,UAAU,UAAU,GAAG;EAC3B,OAAO,cAAc,WAAW,MAAM;EACtC,SAAS,eAAe,WAAW,YAAY;EAC/C,QAAQ;GACN,IAAI;GACJ,SAAS,mBAAmB,SAAS,WAAW,OAAO;GACxD;EACF;;AAGH,SAAgB,mDAAmD,SAQV;CACvD,MAAM,EAAE,QAAQ,WAAW,YAAY,QAAQ,YAAY,cAAc,qBACvE;CACF,MAAM,YAAY,iBAAiB,QAAQ,UAAU;CAErD,OAAO;EACL,GAAG,gCAAgC,QAAQ,WAAW,WAAW;EACjE,gBAAgB;EAChB,UAAU,CACR;GACE,aAAa,kBAAkB,WAAW;GAC1C,KAAK,kBAAkB;IAAE;IAAQ,OAAO;IAAW,QAAQ;IAAY,QAAQ;IAAO,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CASzB,MAAM,qBAAqB,CAAC,GAAG,cAAc,GAAG,gBAAgB;CAChE,MAAM,cAAc,QAClB,mBAAmB,QAAQ,MAAM,aAAa,EAAE,KAAK,IAAI;CAe3D,OAAO,GAAG,EAAE,OAAA;EAZV,GAAG,WAAW,MAAM;EACpB,GAAG,WAAW,OAAO;EACrB,GAAG,WAAW,QAAQ;EACtB,GAAG,WAAW,SAAS;EACvB,GAAG;EACH,GAAG,WAAW,QAAQ;EACtB,GAAG,WAAW,aAAa;EAC3B,GAAG,WAAW,SAAS;EACvB,GAAG,WAAW,QAAQ;EACtB,GAAG,WAAW,aAAa;EAGZ,EAAE,CAAC"}
@@ -1,4 +1,4 @@
1
- import { b as PostgresOpFactoryCall } from "./op-factory-call-BUhxZuUA.mjs";
1
+ import { b as PostgresOpFactoryCall } from "./op-factory-call-UFpUPJL6.mjs";
2
2
  import { CodecControlHooks, MigrationOperationPolicy, SqlPlannerConflict } from "@prisma-next/family-sql/control";
3
3
  import { Result } from "@prisma-next/utils/result";
4
4
  import { SchemaIssue } from "@prisma-next/framework-components/control";
@@ -67,9 +67,8 @@ interface IssuePlannerOptions {
67
67
  */
68
68
  readonly policy?: MigrationOperationPolicy;
69
69
  /**
70
- * Framework components participating in this composition. Used by the
71
- * dependency-install strategy to dispatch `databaseDependencies.init` at
72
- * plan time.
70
+ * Framework components participating in this composition. Available to
71
+ * future strategies that may consult component metadata at plan time.
73
72
  */
74
73
  readonly frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
75
74
  readonly strategies?: readonly CallMigrationStrategy[];
@@ -1 +1 @@
1
- {"version":3,"file":"issue-planner.d.mts","names":[],"sources":["../src/core/migrations/planner-strategies.ts","../src/core/migrations/issue-planner.ts"],"mappings":";;;;;;;;;;;;;;;;;;;UAgFiB,eAAA;EAAA,SACN,UAAA,EAAY,QAAA,CAAS,UAAA;EAAA,SACrB,YAAA,EAAc,QAAA,CAAS,UAAA;EAAA,SACvB,UAAA;EAAA,SACA,UAAA,EAAY,WAAA,SAAoB,iBAAA;EAAA,SAChC,YAAA,EAAc,QAAA,CAAS,MAAA,SAAe,mBAAA;EAAA,SACtC,MAAA,EAAQ,WAAA;EAAA,SACR,MAAA,EAAQ,wBAAA;EAAA,SACR,mBAAA,EAAqB,aAAA,CAAc,8BAAA;AAAA;AAAA,KAOlC,qBAAA,IACV,MAAA,WAAiB,WAAA,IACjB,OAAA,EAAS,eAAA;EAGL,IAAA;EACA,MAAA,WAAiB,WAAA;EACjB,KAAA,WAAgB,qBAAA;EAdsD;AAO5E;;;;;;;EAgBM,MAAA;AAAA;EAEA,IAAA;AAAA;;;UCiBW,mBAAA;EAAA,SACN,MAAA,WAAiB,WAAA;EAAA,SACjB,UAAA,EAAY,QAAA,CAAS,UAAA;EAAA,SACrB,YAAA,EAAc,QAAA,CAAS,UAAA;EAAA,SACvB,UAAA;EAAA,SACA,UAAA,EAAY,WAAA,SAAoB,iBAAA;EAAA,SAChC,YAAA,EAAc,QAAA,CAAS,MAAA,SAAe,mBAAA;EDhDJ;;;;;;;EAAA,SCwDlC,MAAA,GAAS,WAAA;ED7DT;;;;;EAAA,SCmEA,MAAA,GAAS,wBAAA;EDjEc;;;;;EAAA,SCuEvB,mBAAA,GAAsB,aAAA,CAAc,8BAAA;EAAA,SACpC,UAAA,YAAsB,qBAAA;AAAA;AAAA,UAGhB,iBAAA;EAAA,SACN,KAAA,WAAgB,qBAAA;AAAA;AAAA,iBAqjBX,UAAA,CACd,OAAA,EAAS,mBAAA,GACR,MAAA,CAAO,iBAAA,WAA4B,kBAAA"}
1
+ {"version":3,"file":"issue-planner.d.mts","names":[],"sources":["../src/core/migrations/planner-strategies.ts","../src/core/migrations/issue-planner.ts"],"mappings":";;;;;;;;;;;;;;;;;;;UA6EiB,eAAA;EAAA,SACN,UAAA,EAAY,QAAA,CAAS,UAAA;EAAA,SACrB,YAAA,EAAc,QAAA,CAAS,UAAA;EAAA,SACvB,UAAA;EAAA,SACA,UAAA,EAAY,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