@prisma-next/target-sqlite 0.8.0 → 0.9.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"control.d.mts","names":[],"sources":["../src/core/control-target.ts"],"mappings":";;;;cA4BM,6BAAA,EAA+B,0BAAA,WAAqC,uBAAA"}
1
+ {"version":3,"file":"control.d.mts","names":[],"sources":["../src/core/control-target.ts"],"mappings":";;;;cAkCM,6BAAA,EAA+B,0BAAA,WAAqC,uBAAA"}
package/dist/control.mjs CHANGED
@@ -1,15 +1,17 @@
1
1
  import { t as sqliteTargetDescriptorMeta } from "./descriptor-meta-CE2Kbn9b.mjs";
2
2
  import { t as parseSqliteDefault } from "./default-normalizer-3Fccw7yw.mjs";
3
3
  import { t as normalizeSqliteNativeType } from "./native-type-normalizer-BlN5XfD-.mjs";
4
- import { d as renderDefaultLiteral } from "./tables-D84zfPZI.mjs";
5
- import { n as createSqliteMigrationPlanner } from "./planner-A7dqS0u6.mjs";
4
+ import { d as renderDefaultLiteral } from "./tables-DGRRJasz.mjs";
5
+ import { n as createSqliteMigrationPlanner } from "./planner-CKzXAj4i.mjs";
6
6
  import { a as buildLedgerInsertStatement, c as ensureMarkerTableStatement, i as MARKER_TABLE_NAME, l as readMarkerStatement, o as buildWriteMarkerStatements, s as ensureLedgerTableStatement } from "./statement-builders-Dne-LkAV.mjs";
7
7
  import { contractToSchemaIR, runnerFailure, runnerSuccess } from "@prisma-next/family-sql/control";
8
+ import { SqlStorage } from "@prisma-next/sql-contract/types";
8
9
  import { verifySqlSchema } from "@prisma-next/family-sql/schema-verify";
9
10
  import { notOk, ok, okVoid } from "@prisma-next/utils/result";
10
11
  import { ifDefined } from "@prisma-next/utils/defined";
11
12
  import { APP_SPACE_ID } from "@prisma-next/framework-components/control";
12
13
  import { parseContractMarkerRow } from "@prisma-next/family-sql/verify";
14
+ import { SqlContractSerializerBase, SqlSchemaVerifierBase } from "@prisma-next/family-sql/ir";
13
15
  //#region src/core/migrations/runner.ts
14
16
  function createSqliteMigrationRunner(family) {
15
17
  return new SqliteMigrationRunner(family);
@@ -396,7 +398,43 @@ var SqliteMigrationRunner = class {
396
398
  }
397
399
  };
398
400
  //#endregion
401
+ //#region src/core/sqlite-contract-serializer.ts
402
+ /**
403
+ * SQLite target `ContractSerializer` concretion. Mirrors the Postgres
404
+ * shape: inherits the full SQL-family deserialization pipeline. Today's
405
+ * SQLite contract shape is the family-shared shape; no target-specific
406
+ * polymorphic `storage.types` factories are registered yet.
407
+ *
408
+ * `serializeContract` falls through to the family-base default —
409
+ * SQLite's contract is JSON-clean today. Once target-only fields land
410
+ * (e.g. per-target derived storage fields) this is the home for
411
+ * stripping them from the persisted envelope.
412
+ */
413
+ var SqliteContractSerializer = class extends SqlContractSerializerBase {
414
+ constructor() {
415
+ super(/* @__PURE__ */ new Map());
416
+ }
417
+ };
418
+ //#endregion
419
+ //#region src/core/sqlite-schema-verifier.ts
420
+ /**
421
+ * SQLite target `SchemaVerifier` concretion. Mirrors the Postgres
422
+ * shape: hooks return the empty list pending the call-site migration
423
+ * that routes the existing verifier behaviour through the SPI.
424
+ */
425
+ var SqliteSchemaVerifier = class extends SqlSchemaVerifierBase {
426
+ verifyCommonSqlSchema(_options) {
427
+ return [];
428
+ }
429
+ verifyTargetExtensions(_options) {
430
+ return [];
431
+ }
432
+ };
433
+ //#endregion
399
434
  //#region src/core/control-target.ts
435
+ function isSqlContract(contract) {
436
+ return contract === null || contract.storage instanceof SqlStorage;
437
+ }
400
438
  function sqliteRenderDefault(def, _column) {
401
439
  if (def.kind === "function") {
402
440
  if (def.expression === "now()") return "datetime('now')";
@@ -406,6 +444,8 @@ function sqliteRenderDefault(def, _column) {
406
444
  }
407
445
  const sqliteControlTargetDescriptor = {
408
446
  ...sqliteTargetDescriptorMeta,
447
+ contractSerializer: new SqliteContractSerializer(),
448
+ schemaVerifier: new SqliteSchemaVerifier(),
409
449
  migrations: {
410
450
  createPlanner(_family) {
411
451
  return createSqliteMigrationPlanner();
@@ -414,6 +454,7 @@ const sqliteControlTargetDescriptor = {
414
454
  return createSqliteMigrationRunner(family);
415
455
  },
416
456
  contractToSchema(contract, _frameworkComponents) {
457
+ if (!isSqlContract(contract)) throw new Error("sqliteControlTargetDescriptor.contractToSchema received a non-SQL contract; expected Contract<SqlStorage>");
417
458
  return contractToSchemaIR(contract, {
418
459
  annotationNamespace: "sqlite",
419
460
  renderDefault: sqliteRenderDefault
@@ -1 +1 @@
1
- {"version":3,"file":"control.mjs","names":[],"sources":["../src/core/migrations/runner.ts","../src/core/control-target.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 ContractMarkerRow, parseContractMarkerRow } from '@prisma-next/family-sql/verify';\nimport type { ControlDriverInstance } from '@prisma-next/framework-components/control';\nimport { APP_SPACE_ID } from '@prisma-next/framework-components/control';\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 { parseSqliteDefault } from '../default-normalizer';\nimport { normalizeSqliteNativeType } from '../native-type-normalizer';\nimport type { SqlitePlanTargetDetails } from './planner-target-details';\nimport {\n buildLedgerInsertStatement,\n buildWriteMarkerStatements,\n ensureLedgerTableStatement,\n ensureMarkerTableStatement,\n MARKER_TABLE_NAME,\n readMarkerStatement,\n type SqlStatement,\n} from './statement-builders';\n\nexport function createSqliteMigrationRunner(\n family: SqlControlFamilyInstance,\n): SqlMigrationRunner<SqlitePlanTargetDetails> {\n return new SqliteMigrationRunner(family);\n}\n\nclass SqliteMigrationRunner implements SqlMigrationRunner<SqlitePlanTargetDetails> {\n constructor(private readonly family: SqlControlFamilyInstance) {}\n\n async execute(\n options: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const driver = options.driver;\n\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 // SQLite recreate-table drops and rebuilds the table. If foreign_keys is ON,\n // dropping a referenced parent cascade-deletes child rows; we must disable FK\n // enforcement for the duration of the migration and validate integrity before\n // committing. PRAGMA foreign_keys is a no-op inside a transaction, so toggle\n // around BEGIN/COMMIT.\n const fkWasEnabled = await this.readForeignKeysEnabled(driver);\n if (fkWasEnabled) {\n await driver.query('PRAGMA foreign_keys = OFF');\n }\n\n try {\n await this.beginExclusiveTransaction(driver);\n let committed = false;\n try {\n const result = await this.executeOnConnection(options);\n if (!result.ok) return result;\n\n if (fkWasEnabled) {\n const fkIntegrityCheck = await this.verifyForeignKeyIntegrity(driver);\n if (!fkIntegrityCheck.ok) return fkIntegrityCheck;\n }\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 } finally {\n if (fkWasEnabled) {\n await driver.query('PRAGMA foreign_keys = ON');\n }\n }\n }\n\n /**\n * Apply the plan against an already-open connection without managing\n * the transaction lifecycle. The caller owns BEGIN/COMMIT/ROLLBACK\n * and any connection-level setup (FK pragma toggle, FK integrity\n * check). Used by the per-space runner orchestration to fan out\n * across contract spaces inside one outer transaction.\n */\n async executeOnConnection(\n options: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\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\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 const ensureResult = await this.ensureControlTables(driver);\n if (!ensureResult.ok) return ensureResult;\n const existingMarker = await this.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\n let operationsExecuted: number;\n let executedOperations: readonly SqlMigrationPlanOperation<SqlitePlanTargetDetails>[];\n\n if (skipOperations) {\n operationsExecuted = 0;\n executedOperations = [];\n } else {\n const applyResult = await this.applyPlan(driver, options);\n if (!applyResult.ok) return applyResult;\n operationsExecuted = applyResult.value.operationsExecuted;\n executedOperations = applyResult.value.executedOperations;\n }\n\n if (space === APP_SPACE_ID) {\n const schemaIR = await this.family.introspect({\n driver,\n contract: options.destinationContract,\n });\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: parseSqliteDefault,\n normalizeNativeType: normalizeSqliteNativeType,\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 // Self-edge no-op detection: see Postgres runner for the rationale\n // (kept symmetric across both targets).\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 = isSelfEdge && operationsExecuted === 0 && incomingIsSubsetOfExisting;\n\n if (!isSelfEdgeNoOp) {\n await this.upsertMarker(driver, options, existingMarker, space);\n await this.recordLedgerEntry(driver, options, existingMarker, executedOperations);\n }\n\n return runnerSuccess({\n operationsPlanned: options.plan.operations.length,\n operationsExecuted,\n });\n }\n\n async executeAcrossSpaces(options: {\n readonly driver: ControlDriverInstance<'sql', string>;\n readonly perSpaceOptions: ReadonlyArray<\n SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>\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 // FK pragma toggle and the FK integrity check both span the outer\n // transaction — see `execute(...)` for the full rationale.\n const fkWasEnabled = await this.readForeignKeysEnabled(driver);\n if (fkWasEnabled) {\n await driver.query('PRAGMA foreign_keys = OFF');\n }\n\n try {\n await this.beginExclusiveTransaction(driver);\n let committed = false;\n try {\n const perSpaceResults: Array<{\n space: string;\n value: SqlMigrationRunnerSuccessValue;\n }> = [];\n let lastProcessedSpace: string | undefined;\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 lastProcessedSpace = space;\n }\n\n if (fkWasEnabled) {\n const fkIntegrityCheck = await this.verifyForeignKeyIntegrity(driver);\n if (!fkIntegrityCheck.ok) {\n // Post-loop integrity violations cannot be attributed to a\n // single per-space step (the cumulative effect of all\n // applied plans was needed to reveal the broken\n // reference). Surface the last successfully-applied space\n // so operators can investigate from the most recent\n // migration first.\n return notOk({\n ...fkIntegrityCheck.failure,\n failingSpace: lastProcessedSpace ?? APP_SPACE_ID,\n });\n }\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 } finally {\n if (fkWasEnabled) {\n await driver.query('PRAGMA foreign_keys = ON');\n }\n }\n }\n\n private async readForeignKeysEnabled(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n ): Promise<boolean> {\n const result = await driver.query<{ foreign_keys: number }>('PRAGMA foreign_keys');\n const row = result.rows[0];\n return row?.foreign_keys === 1;\n }\n\n private async verifyForeignKeyIntegrity(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const result = await driver.query<Record<string, unknown>>('PRAGMA foreign_key_check');\n if (result.rows.length === 0) {\n return okVoid();\n }\n return runnerFailure(\n 'FOREIGN_KEY_VIOLATION',\n `Foreign key integrity check failed after migration: ${result.rows.length} violation(s).`,\n {\n why: 'PRAGMA foreign_key_check reported violations after applying recreate-table operations.',\n meta: { violations: result.rows },\n },\n );\n }\n\n private async applyPlan(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>,\n ): Promise<\n Result<\n {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<SqlitePlanTargetDetails>[];\n },\n SqlMigrationRunnerFailure\n >\n > {\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false;\n const runPostchecks = checks?.postchecks !== false;\n const runIdempotency = checks?.idempotencyChecks !== false;\n\n let operationsExecuted = 0;\n const executedOperations: Array<SqlMigrationPlanOperation<SqlitePlanTargetDetails>> = [];\n\n for (const operation of options.plan.operations) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n if (runPostchecks && runIdempotency) {\n const postcheckAlreadySatisfied = await this.expectationsAreSatisfied(\n driver,\n operation.postcheck,\n );\n if (postcheckAlreadySatisfied) {\n executedOperations.push(this.createSkipRecord(operation));\n continue;\n }\n }\n\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 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<SqlitePlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\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 rebuilding the table into the per-space\n // shape. 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<SqlitePlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const tableInfo = await driver.query<{ name: string }>(\n `PRAGMA table_info(\"${MARKER_TABLE_NAME}\")`,\n );\n if (tableInfo.rows.length === 0) {\n return okVoid();\n }\n const columns = new Set(tableInfo.rows.map((row) => row.name));\n if (columns.has('space')) {\n return okVoid();\n }\n return runnerFailure(\n 'LEGACY_MARKER_SHAPE',\n `Legacy marker-table shape detected on ${MARKER_TABLE_NAME} (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 \\`${MARKER_TABLE_NAME}\\` and re-run \\`dbInit\\` to reinitialise from a clean baseline.`,\n {\n meta: {\n table: MARKER_TABLE_NAME,\n columns: [...columns].sort(),\n },\n },\n );\n }\n\n private async readMarker(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n space: string,\n ): Promise<ContractMarkerRecord | null> {\n const stmt = readMarkerStatement(space);\n try {\n const result = await driver.query<ContractMarkerRow>(stmt.sql, stmt.params);\n const row = result.rows[0];\n if (!row) return null;\n // SQLite stores arrays as JSON-encoded TEXT (no native array type), so\n // the driver returns `invariants` as a string. Decode before delegating\n // to the shared row schema, which expects `string[]`.\n const invariants =\n typeof row.invariants === 'string'\n ? (JSON.parse(row.invariants) as unknown)\n : row.invariants;\n return parseContractMarkerRow({ ...row, invariants });\n } catch (error) {\n // Table might not exist yet\n if (error instanceof Error && error.message.includes('no such table')) {\n return null;\n }\n throw error;\n }\n }\n\n private async runExpectationSteps(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<SqlitePlanTargetDetails>,\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<SqlitePlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<SqlitePlanTargetDetails>,\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 const message = error instanceof Error ? error.message : String(error);\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n },\n },\n );\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 === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n if (lower === 'true' || lower === '1') return true;\n if (lower === 'false' || lower === '0') return false;\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['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 createSkipRecord(\n operation: SqlMigrationPlanOperation<SqlitePlanTargetDetails>,\n ): SqlMigrationPlanOperation<SqlitePlanTargetDetails> {\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,\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: Object.freeze([...operation.postcheck]),\n meta: Object.freeze({\n ...(operation.meta ?? {}),\n runner: Object.freeze({ skipped: true, reason: 'postcheck_pre_satisfied' }),\n }),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) return false;\n if (marker.storageHash !== plan.destination.storageHash) return false;\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<SqlitePlanTargetDetails>[],\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<SqlitePlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n return okVoid();\n }\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n { meta: { expectedOriginStorageHash: origin.storageHash } },\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<SqlitePlanTargetDetails>['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<SqlitePlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n space: string,\n ): Promise<void> {\n // SQLite has no native array type, so we can't merge invariants in SQL\n // the way Postgres does. Merge client-side under the runner's\n // BEGIN EXCLUSIVE — sort + dedupe so the JSON-encoded value is stable.\n const merged = new Set<string>(existingMarker?.invariants ?? []);\n for (const inv of options.plan.providedInvariants) merged.add(inv);\n const invariants = Array.from(merged).sort();\n const writeStatements = buildWriteMarkerStatements({\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,\n });\n const statement = existingMarker ? writeStatements.update : writeStatements.insert;\n await this.executeStatement(driver, statement);\n }\n\n private async recordLedgerEntry(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n executedOperations: readonly SqlMigrationPlanOperation<SqlitePlanTargetDetails>[],\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 beginExclusiveTransaction(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN EXCLUSIVE');\n }\n\n private async commitTransaction(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['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 } from '@prisma-next/family-sql/control';\nimport type {\n ControlTargetInstance,\n MigrationPlanner,\n MigrationRunner,\n} from '@prisma-next/framework-components/control';\nimport type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport { sqliteTargetDescriptorMeta } from './descriptor-meta';\nimport { createSqliteMigrationPlanner } from './migrations/planner';\nimport { renderDefaultLiteral } from './migrations/planner-ddl-builders';\nimport type { SqlitePlanTargetDetails } from './migrations/planner-target-details';\nimport { createSqliteMigrationRunner } from './migrations/runner';\n\nfunction sqliteRenderDefault(def: ColumnDefault, _column: StorageColumn): string {\n if (def.kind === 'function') {\n if (def.expression === 'now()') {\n return \"datetime('now')\";\n }\n return def.expression;\n }\n return renderDefaultLiteral(def.value);\n}\n\nconst sqliteControlTargetDescriptor: SqlControlTargetDescriptor<'sqlite', SqlitePlanTargetDetails> =\n {\n ...sqliteTargetDescriptorMeta,\n migrations: {\n createPlanner(_family: SqlControlFamilyInstance): MigrationPlanner<'sql', 'sqlite'> {\n return createSqliteMigrationPlanner();\n },\n createRunner(family) {\n return createSqliteMigrationRunner(family) as MigrationRunner<'sql', 'sqlite'>;\n },\n contractToSchema(contract, _frameworkComponents) {\n return contractToSchemaIR(contract as Contract<SqlStorage> | null, {\n annotationNamespace: 'sqlite',\n renderDefault: sqliteRenderDefault,\n });\n },\n },\n create(): ControlTargetInstance<'sql', 'sqlite'> {\n return {\n familyId: 'sql',\n targetId: 'sqlite',\n };\n },\n createPlanner(_family: SqlControlFamilyInstance) {\n return createSqliteMigrationPlanner();\n },\n createRunner(family) {\n return createSqliteMigrationRunner(family);\n },\n };\n\nexport default sqliteControlTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;;AAmCA,SAAgB,4BACd,QAC6C;CAC7C,OAAO,IAAI,sBAAsB,OAAO;;AAG1C,IAAM,wBAAN,MAAmF;CACpD;CAA7B,YAAY,QAAmD;EAAlC,KAAA,SAAA;;CAE7B,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EAC/C,OAAO,8BAA8B;;CAEvC,aAAa,QAAQ;EACnB,OAAO,4BAA4B,OAAO;;CAE7C"}
1
+ {"version":3,"file":"control.mjs","names":[],"sources":["../src/core/migrations/runner.ts","../src/core/sqlite-contract-serializer.ts","../src/core/sqlite-schema-verifier.ts","../src/core/control-target.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 ContractMarkerRow, parseContractMarkerRow } from '@prisma-next/family-sql/verify';\nimport type { ControlDriverInstance } from '@prisma-next/framework-components/control';\nimport { APP_SPACE_ID } from '@prisma-next/framework-components/control';\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 { parseSqliteDefault } from '../default-normalizer';\nimport { normalizeSqliteNativeType } from '../native-type-normalizer';\nimport type { SqlitePlanTargetDetails } from './planner-target-details';\nimport {\n buildLedgerInsertStatement,\n buildWriteMarkerStatements,\n ensureLedgerTableStatement,\n ensureMarkerTableStatement,\n MARKER_TABLE_NAME,\n readMarkerStatement,\n type SqlStatement,\n} from './statement-builders';\n\nexport function createSqliteMigrationRunner(\n family: SqlControlFamilyInstance,\n): SqlMigrationRunner<SqlitePlanTargetDetails> {\n return new SqliteMigrationRunner(family);\n}\n\nclass SqliteMigrationRunner implements SqlMigrationRunner<SqlitePlanTargetDetails> {\n constructor(private readonly family: SqlControlFamilyInstance) {}\n\n async execute(\n options: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const driver = options.driver;\n\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 // SQLite recreate-table drops and rebuilds the table. If foreign_keys is ON,\n // dropping a referenced parent cascade-deletes child rows; we must disable FK\n // enforcement for the duration of the migration and validate integrity before\n // committing. PRAGMA foreign_keys is a no-op inside a transaction, so toggle\n // around BEGIN/COMMIT.\n const fkWasEnabled = await this.readForeignKeysEnabled(driver);\n if (fkWasEnabled) {\n await driver.query('PRAGMA foreign_keys = OFF');\n }\n\n try {\n await this.beginExclusiveTransaction(driver);\n let committed = false;\n try {\n const result = await this.executeOnConnection(options);\n if (!result.ok) return result;\n\n if (fkWasEnabled) {\n const fkIntegrityCheck = await this.verifyForeignKeyIntegrity(driver);\n if (!fkIntegrityCheck.ok) return fkIntegrityCheck;\n }\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 } finally {\n if (fkWasEnabled) {\n await driver.query('PRAGMA foreign_keys = ON');\n }\n }\n }\n\n /**\n * Apply the plan against an already-open connection without managing\n * the transaction lifecycle. The caller owns BEGIN/COMMIT/ROLLBACK\n * and any connection-level setup (FK pragma toggle, FK integrity\n * check). Used by the per-space runner orchestration to fan out\n * across contract spaces inside one outer transaction.\n */\n async executeOnConnection(\n options: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\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\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 const ensureResult = await this.ensureControlTables(driver);\n if (!ensureResult.ok) return ensureResult;\n const existingMarker = await this.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\n let operationsExecuted: number;\n let executedOperations: readonly SqlMigrationPlanOperation<SqlitePlanTargetDetails>[];\n\n if (skipOperations) {\n operationsExecuted = 0;\n executedOperations = [];\n } else {\n const applyResult = await this.applyPlan(driver, options);\n if (!applyResult.ok) return applyResult;\n operationsExecuted = applyResult.value.operationsExecuted;\n executedOperations = applyResult.value.executedOperations;\n }\n\n if (space === APP_SPACE_ID) {\n const schemaIR = await this.family.introspect({\n driver,\n contract: options.destinationContract,\n });\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: parseSqliteDefault,\n normalizeNativeType: normalizeSqliteNativeType,\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 // Self-edge no-op detection: see Postgres runner for the rationale\n // (kept symmetric across both targets).\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 = isSelfEdge && operationsExecuted === 0 && incomingIsSubsetOfExisting;\n\n if (!isSelfEdgeNoOp) {\n await this.upsertMarker(driver, options, existingMarker, space);\n await this.recordLedgerEntry(driver, options, existingMarker, executedOperations);\n }\n\n return runnerSuccess({\n operationsPlanned: options.plan.operations.length,\n operationsExecuted,\n });\n }\n\n async executeAcrossSpaces(options: {\n readonly driver: ControlDriverInstance<'sql', string>;\n readonly perSpaceOptions: ReadonlyArray<\n SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>\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 // FK pragma toggle and the FK integrity check both span the outer\n // transaction — see `execute(...)` for the full rationale.\n const fkWasEnabled = await this.readForeignKeysEnabled(driver);\n if (fkWasEnabled) {\n await driver.query('PRAGMA foreign_keys = OFF');\n }\n\n try {\n await this.beginExclusiveTransaction(driver);\n let committed = false;\n try {\n const perSpaceResults: Array<{\n space: string;\n value: SqlMigrationRunnerSuccessValue;\n }> = [];\n let lastProcessedSpace: string | undefined;\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 lastProcessedSpace = space;\n }\n\n if (fkWasEnabled) {\n const fkIntegrityCheck = await this.verifyForeignKeyIntegrity(driver);\n if (!fkIntegrityCheck.ok) {\n // Post-loop integrity violations cannot be attributed to a\n // single per-space step (the cumulative effect of all\n // applied plans was needed to reveal the broken\n // reference). Surface the last successfully-applied space\n // so operators can investigate from the most recent\n // migration first.\n return notOk({\n ...fkIntegrityCheck.failure,\n failingSpace: lastProcessedSpace ?? APP_SPACE_ID,\n });\n }\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 } finally {\n if (fkWasEnabled) {\n await driver.query('PRAGMA foreign_keys = ON');\n }\n }\n }\n\n private async readForeignKeysEnabled(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n ): Promise<boolean> {\n const result = await driver.query<{ foreign_keys: number }>('PRAGMA foreign_keys');\n const row = result.rows[0];\n return row?.foreign_keys === 1;\n }\n\n private async verifyForeignKeyIntegrity(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const result = await driver.query<Record<string, unknown>>('PRAGMA foreign_key_check');\n if (result.rows.length === 0) {\n return okVoid();\n }\n return runnerFailure(\n 'FOREIGN_KEY_VIOLATION',\n `Foreign key integrity check failed after migration: ${result.rows.length} violation(s).`,\n {\n why: 'PRAGMA foreign_key_check reported violations after applying recreate-table operations.',\n meta: { violations: result.rows },\n },\n );\n }\n\n private async applyPlan(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>,\n ): Promise<\n Result<\n {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<SqlitePlanTargetDetails>[];\n },\n SqlMigrationRunnerFailure\n >\n > {\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false;\n const runPostchecks = checks?.postchecks !== false;\n const runIdempotency = checks?.idempotencyChecks !== false;\n\n let operationsExecuted = 0;\n const executedOperations: Array<SqlMigrationPlanOperation<SqlitePlanTargetDetails>> = [];\n\n for (const operation of options.plan.operations) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n if (runPostchecks && runIdempotency) {\n const postcheckAlreadySatisfied = await this.expectationsAreSatisfied(\n driver,\n operation.postcheck,\n );\n if (postcheckAlreadySatisfied) {\n executedOperations.push(this.createSkipRecord(operation));\n continue;\n }\n }\n\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 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<SqlitePlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\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 rebuilding the table into the per-space\n // shape. 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<SqlitePlanTargetDetails>['driver'],\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n const tableInfo = await driver.query<{ name: string }>(\n `PRAGMA table_info(\"${MARKER_TABLE_NAME}\")`,\n );\n if (tableInfo.rows.length === 0) {\n return okVoid();\n }\n const columns = new Set(tableInfo.rows.map((row) => row.name));\n if (columns.has('space')) {\n return okVoid();\n }\n return runnerFailure(\n 'LEGACY_MARKER_SHAPE',\n `Legacy marker-table shape detected on ${MARKER_TABLE_NAME} (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 \\`${MARKER_TABLE_NAME}\\` and re-run \\`dbInit\\` to reinitialise from a clean baseline.`,\n {\n meta: {\n table: MARKER_TABLE_NAME,\n columns: [...columns].sort(),\n },\n },\n );\n }\n\n private async readMarker(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n space: string,\n ): Promise<ContractMarkerRecord | null> {\n const stmt = readMarkerStatement(space);\n try {\n const result = await driver.query<ContractMarkerRow>(stmt.sql, stmt.params);\n const row = result.rows[0];\n if (!row) return null;\n // SQLite stores arrays as JSON-encoded TEXT (no native array type), so\n // the driver returns `invariants` as a string. Decode before delegating\n // to the shared row schema, which expects `string[]`.\n const invariants =\n typeof row.invariants === 'string'\n ? (JSON.parse(row.invariants) as unknown)\n : row.invariants;\n return parseContractMarkerRow({ ...row, invariants });\n } catch (error) {\n // Table might not exist yet\n if (error instanceof Error && error.message.includes('no such table')) {\n return null;\n }\n throw error;\n }\n }\n\n private async runExpectationSteps(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<SqlitePlanTargetDetails>,\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<SqlitePlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<SqlitePlanTargetDetails>,\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 const message = error instanceof Error ? error.message : String(error);\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n },\n },\n );\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 === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n if (lower === 'true' || lower === '1') return true;\n if (lower === 'false' || lower === '0') return false;\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['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 createSkipRecord(\n operation: SqlMigrationPlanOperation<SqlitePlanTargetDetails>,\n ): SqlMigrationPlanOperation<SqlitePlanTargetDetails> {\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,\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: Object.freeze([...operation.postcheck]),\n meta: Object.freeze({\n ...(operation.meta ?? {}),\n runner: Object.freeze({ skipped: true, reason: 'postcheck_pre_satisfied' }),\n }),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) return false;\n if (marker.storageHash !== plan.destination.storageHash) return false;\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<SqlitePlanTargetDetails>[],\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<SqlitePlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n return okVoid();\n }\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n { meta: { expectedOriginStorageHash: origin.storageHash } },\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<SqlitePlanTargetDetails>['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<SqlitePlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n space: string,\n ): Promise<void> {\n // SQLite has no native array type, so we can't merge invariants in SQL\n // the way Postgres does. Merge client-side under the runner's\n // BEGIN EXCLUSIVE — sort + dedupe so the JSON-encoded value is stable.\n const merged = new Set<string>(existingMarker?.invariants ?? []);\n for (const inv of options.plan.providedInvariants) merged.add(inv);\n const invariants = Array.from(merged).sort();\n const writeStatements = buildWriteMarkerStatements({\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,\n });\n const statement = existingMarker ? writeStatements.update : writeStatements.insert;\n await this.executeStatement(driver, statement);\n }\n\n private async recordLedgerEntry(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n executedOperations: readonly SqlMigrationPlanOperation<SqlitePlanTargetDetails>[],\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 beginExclusiveTransaction(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN EXCLUSIVE');\n }\n\n private async commitTransaction(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: SqlMigrationRunnerExecuteOptions<SqlitePlanTargetDetails>['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 { Contract } from '@prisma-next/contract/types';\nimport { SqlContractSerializerBase } from '@prisma-next/family-sql/ir';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\n\n/**\n * SQLite target `ContractSerializer` concretion. Mirrors the Postgres\n * shape: inherits the full SQL-family deserialization pipeline. Today's\n * SQLite contract shape is the family-shared shape; no target-specific\n * polymorphic `storage.types` factories are registered yet.\n *\n * `serializeContract` falls through to the family-base default —\n * SQLite's contract is JSON-clean today. Once target-only fields land\n * (e.g. per-target derived storage fields) this is the home for\n * stripping them from the persisted envelope.\n */\nexport class SqliteContractSerializer extends SqlContractSerializerBase<Contract<SqlStorage>> {\n constructor() {\n super(new Map());\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { SqlSchemaVerifierBase } from '@prisma-next/family-sql/ir';\nimport type { SchemaIssue, SchemaVerifyOptions } from '@prisma-next/framework-components/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\n\n/**\n * SQLite target `SchemaVerifier` concretion. Mirrors the Postgres\n * shape: hooks return the empty list pending the call-site migration\n * that routes the existing verifier behaviour through the SPI.\n */\nexport class SqliteSchemaVerifier extends SqlSchemaVerifierBase<Contract<SqlStorage>, SqlSchemaIR> {\n protected verifyCommonSqlSchema(\n _options: SchemaVerifyOptions<Contract<SqlStorage>, SqlSchemaIR>,\n ): readonly SchemaIssue[] {\n return [];\n }\n\n protected verifyTargetExtensions(\n _options: SchemaVerifyOptions<Contract<SqlStorage>, SqlSchemaIR>,\n ): readonly SchemaIssue[] {\n return [];\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 } from '@prisma-next/family-sql/control';\nimport type {\n ControlTargetInstance,\n MigrationPlanner,\n MigrationRunner,\n} from '@prisma-next/framework-components/control';\nimport { SqlStorage, type StorageColumn } from '@prisma-next/sql-contract/types';\nimport { sqliteTargetDescriptorMeta } from './descriptor-meta';\nimport { createSqliteMigrationPlanner } from './migrations/planner';\nimport { renderDefaultLiteral } from './migrations/planner-ddl-builders';\nimport type { SqlitePlanTargetDetails } from './migrations/planner-target-details';\nimport { createSqliteMigrationRunner } from './migrations/runner';\nimport { SqliteContractSerializer } from './sqlite-contract-serializer';\nimport { SqliteSchemaVerifier } from './sqlite-schema-verifier';\n\nfunction isSqlContract(contract: Contract | null): contract is Contract<SqlStorage> | null {\n return contract === null || contract.storage instanceof SqlStorage;\n}\n\nfunction sqliteRenderDefault(def: ColumnDefault, _column: StorageColumn): string {\n if (def.kind === 'function') {\n if (def.expression === 'now()') {\n return \"datetime('now')\";\n }\n return def.expression;\n }\n return renderDefaultLiteral(def.value);\n}\n\nconst sqliteControlTargetDescriptor: SqlControlTargetDescriptor<'sqlite', SqlitePlanTargetDetails> =\n {\n ...sqliteTargetDescriptorMeta,\n contractSerializer: new SqliteContractSerializer(),\n schemaVerifier: new SqliteSchemaVerifier(),\n migrations: {\n createPlanner(_family: SqlControlFamilyInstance): MigrationPlanner<'sql', 'sqlite'> {\n return createSqliteMigrationPlanner();\n },\n createRunner(family) {\n return createSqliteMigrationRunner(family) as MigrationRunner<'sql', 'sqlite'>;\n },\n contractToSchema(contract, _frameworkComponents) {\n // The framework SPI types `contract` as the generic\n // `Contract | null`. Any contract reaching the sqlite\n // target descriptor is SQL-family by construction (the\n // family contract resolver would have refused to bind a\n // sqlite target otherwise); the `isSqlContract` predicate\n // encodes that invariant at runtime + narrows the generic\n // to `Contract<SqlStorage>` without a blind cast.\n if (!isSqlContract(contract)) {\n throw new Error(\n 'sqliteControlTargetDescriptor.contractToSchema received a non-SQL contract; expected Contract<SqlStorage>',\n );\n }\n return contractToSchemaIR(contract, {\n annotationNamespace: 'sqlite',\n renderDefault: sqliteRenderDefault,\n });\n },\n },\n create(): ControlTargetInstance<'sql', 'sqlite'> {\n return {\n familyId: 'sql',\n targetId: 'sqlite',\n };\n },\n createPlanner(_family: SqlControlFamilyInstance) {\n return createSqliteMigrationPlanner();\n },\n createRunner(family) {\n return createSqliteMigrationRunner(family);\n },\n };\n\nexport default sqliteControlTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;;;;AAmCA,SAAgB,4BACd,QAC6C;CAC7C,OAAO,IAAI,sBAAsB,OAAO;;AAG1C,IAAM,wBAAN,MAAmF;CACpD;CAA7B,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AqB,IAAI,MAAM;;AAGxC,MAAM,gCACJ;CACE,GAAG;CACH,oBAAoB,IAAI,0BAA0B;CAClD,gBAAgB,IAAI,sBAAsB;CAC1C,YAAY;EACV,cAAc,SAAsE;GAClF,OAAO,8BAA8B;;EAEvC,aAAa,QAAQ;GACnB,OAAO,4BAA4B,OAAO;;EAE5C,iBAAiB,UAAU,sBAAsB;GAQ/C,IAAI,CAAC,cAAc,SAAS,EAC1B,MAAM,IAAI,MACR,4GACD;GAEH,OAAO,mBAAmB,UAAU;IAClC,qBAAqB;IACrB,eAAe;IAChB,CAAC;;EAEL;CACD,SAAiD;EAC/C,OAAO;GACL,UAAU;GACV,UAAU;GACX;;CAEH,cAAc,SAAmC;EAC/C,OAAO,8BAA8B;;CAEvC,aAAa,QAAQ;EACnB,OAAO,4BAA4B,OAAO;;CAE7C"}
@@ -1,5 +1,5 @@
1
1
  import { t as buildTargetDetails } from "./planner-target-details-Bm71XPKb.mjs";
2
- import { a as recreateTable, f as addColumn, i as dropTable, m as step, o as createIndex, p as dropColumn, r as createTable, s as dropIndex } from "./tables-D84zfPZI.mjs";
2
+ import { a as recreateTable, f as addColumn, i as dropTable, m as step, o as createIndex, p as dropColumn, r as createTable, s as dropIndex } from "./tables-DGRRJasz.mjs";
3
3
  import { t as SqliteMigration } from "./sqlite-migration-BBJktVVw.mjs";
4
4
  import { placeholder } from "@prisma-next/errors/migration";
5
5
  import { MigrationCLI } from "@prisma-next/cli/migration-cli";
@@ -1,4 +1,4 @@
1
- import { a as recreateTable, f as addColumn, i as dropTable, o as createIndex, p as dropColumn, r as createTable, s as dropIndex } from "./tables-D84zfPZI.mjs";
1
+ import { a as recreateTable, f as addColumn, i as dropTable, o as createIndex, p as dropColumn, r as createTable, s as dropIndex } from "./tables-DGRRJasz.mjs";
2
2
  import { errorUnfilledPlaceholder } from "@prisma-next/errors/migration";
3
3
  import { TsExpression, jsonToTsSource } from "@prisma-next/ts-render";
4
4
  //#region src/core/migrations/op-factory-call.ts
@@ -276,4 +276,4 @@ var RawSqlCall = class extends SqliteOpFactoryCallNode {
276
276
  //#endregion
277
277
  export { DropColumnCall as a, RawSqlCall as c, DataTransformCall as i, RecreateTableCall as l, CreateIndexCall as n, DropIndexCall as o, CreateTableCall as r, DropTableCall as s, AddColumnCall as t };
278
278
 
279
- //# sourceMappingURL=op-factory-call-DRKKURAO.mjs.map
279
+ //# sourceMappingURL=op-factory-call-BRp16Nsr.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"op-factory-call-DRKKURAO.mjs","names":[],"sources":["../src/core/migrations/op-factory-call.ts"],"sourcesContent":["/**\n * SQLite migration IR: one concrete `*Call` class per pure factory under\n * `operations/`, plus a shared `SqliteOpFactoryCallNode` abstract base.\n *\n * Each call class carries fully-resolved literal arguments (flat\n * `SqliteColumnSpec` / `SqliteTableSpec` etc.) — codec / `typeRef` / default\n * expansion happens upstream in the issue-planner / strategies, mirroring\n * the Postgres `ColumnSpec` pattern. As a result, `toOp()` and\n * `renderTypeScript()` both pass the same flat data through; the rendered\n * TypeScript scaffold is fully self-contained and does not need access to a\n * `storageTypes` map at runtime.\n */\n\nimport { errorUnfilledPlaceholder } from '@prisma-next/errors/migration';\nimport type {\n MigrationOperationClass,\n SqlMigrationPlanOperation,\n} from '@prisma-next/family-sql/control';\nimport type { OpFactoryCall as FrameworkOpFactoryCall } from '@prisma-next/framework-components/control';\nimport { type ImportRequirement, jsonToTsSource, TsExpression } from '@prisma-next/ts-render';\nimport { addColumn, dropColumn } from './operations/columns';\nimport { createIndex, dropIndex } from './operations/indexes';\nimport type { SqliteColumnSpec, SqliteIndexSpec, SqliteTableSpec } from './operations/shared';\nimport { createTable, dropTable, recreateTable } from './operations/tables';\nimport type { SqlitePlanTargetDetails } from './planner-target-details';\n\ntype Op = SqlMigrationPlanOperation<SqlitePlanTargetDetails>;\n\nconst TARGET_MIGRATION_MODULE = '@prisma-next/target-sqlite/migration';\n\nabstract class SqliteOpFactoryCallNode extends TsExpression implements FrameworkOpFactoryCall {\n abstract readonly factoryName: string;\n abstract readonly operationClass: MigrationOperationClass;\n abstract readonly label: string;\n abstract toOp(): Op;\n\n importRequirements(): readonly ImportRequirement[] {\n return [{ moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: this.factoryName }];\n }\n\n protected freeze(): void {\n Object.freeze(this);\n }\n}\n\n// ============================================================================\n// Table\n// ============================================================================\n\nexport class CreateTableCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'createTable' as const;\n readonly operationClass = 'additive' as const;\n readonly tableName: string;\n readonly spec: SqliteTableSpec;\n readonly label: string;\n\n constructor(tableName: string, spec: SqliteTableSpec) {\n super();\n this.tableName = tableName;\n this.spec = spec;\n this.label = `Create table ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return createTable(this.tableName, this.spec);\n }\n\n renderTypeScript(): string {\n return `createTable(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.spec)})`;\n }\n}\n\nexport class DropTableCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'dropTable' as const;\n readonly operationClass = 'destructive' as const;\n readonly tableName: string;\n readonly label: string;\n\n constructor(tableName: string) {\n super();\n this.tableName = tableName;\n this.label = `Drop table ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropTable(this.tableName);\n }\n\n renderTypeScript(): string {\n return `dropTable(${jsonToTsSource(this.tableName)})`;\n }\n}\n\nexport class RecreateTableCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'recreateTable' as const;\n readonly operationClass: MigrationOperationClass;\n readonly tableName: string;\n readonly contractTable: SqliteTableSpec;\n readonly schemaColumnNames: readonly string[];\n readonly indexes: readonly SqliteIndexSpec[];\n readonly summary: string;\n readonly postchecks: readonly { readonly description: string; readonly sql: string }[];\n readonly label: string;\n\n constructor(args: {\n tableName: string;\n contractTable: SqliteTableSpec;\n schemaColumnNames: readonly string[];\n indexes: readonly SqliteIndexSpec[];\n summary: string;\n postchecks: readonly { readonly description: string; readonly sql: string }[];\n operationClass: MigrationOperationClass;\n }) {\n super();\n this.tableName = args.tableName;\n this.contractTable = args.contractTable;\n this.schemaColumnNames = args.schemaColumnNames;\n this.indexes = args.indexes;\n this.summary = args.summary;\n this.postchecks = args.postchecks;\n this.operationClass = args.operationClass;\n this.label = `Recreate table ${args.tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return recreateTable({\n tableName: this.tableName,\n contractTable: this.contractTable,\n schemaColumnNames: this.schemaColumnNames,\n indexes: this.indexes,\n summary: this.summary,\n postchecks: this.postchecks,\n operationClass: this.operationClass,\n });\n }\n\n renderTypeScript(): string {\n const args = {\n tableName: this.tableName,\n contractTable: this.contractTable,\n schemaColumnNames: this.schemaColumnNames,\n indexes: this.indexes,\n summary: this.summary,\n postchecks: this.postchecks,\n operationClass: this.operationClass,\n };\n return `recreateTable(${jsonToTsSource(args)})`;\n }\n}\n\n// ============================================================================\n// Column\n// ============================================================================\n\nexport class AddColumnCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'addColumn' as const;\n readonly operationClass = 'additive' as const;\n readonly tableName: string;\n readonly columnName: string;\n readonly column: SqliteColumnSpec;\n readonly label: string;\n\n constructor(tableName: string, column: SqliteColumnSpec) {\n super();\n this.tableName = tableName;\n this.columnName = column.name;\n this.column = column;\n this.label = `Add column ${column.name} on ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return addColumn(this.tableName, this.column);\n }\n\n renderTypeScript(): string {\n return `addColumn(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.column)})`;\n }\n}\n\nexport class DropColumnCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'dropColumn' as const;\n readonly operationClass = 'destructive' as const;\n readonly tableName: string;\n readonly columnName: string;\n readonly label: string;\n\n constructor(tableName: string, columnName: string) {\n super();\n this.tableName = tableName;\n this.columnName = columnName;\n this.label = `Drop column ${columnName} on ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropColumn(this.tableName, this.columnName);\n }\n\n renderTypeScript(): string {\n return `dropColumn(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.columnName)})`;\n }\n}\n\n// ============================================================================\n// Index\n// ============================================================================\n\nexport class CreateIndexCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'createIndex' as const;\n readonly operationClass = 'additive' as const;\n readonly tableName: string;\n readonly indexName: string;\n readonly columns: readonly string[];\n readonly label: string;\n\n constructor(tableName: string, indexName: string, columns: readonly string[]) {\n super();\n this.tableName = tableName;\n this.indexName = indexName;\n this.columns = columns;\n this.label = `Create index ${indexName} on ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return createIndex(this.tableName, this.indexName, this.columns);\n }\n\n renderTypeScript(): string {\n return `createIndex(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.indexName)}, ${jsonToTsSource(this.columns)})`;\n }\n}\n\nexport class DropIndexCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'dropIndex' as const;\n readonly operationClass = 'destructive' as const;\n readonly tableName: string;\n readonly indexName: string;\n readonly label: string;\n\n constructor(tableName: string, indexName: string) {\n super();\n this.tableName = tableName;\n this.indexName = indexName;\n this.label = `Drop index ${indexName} on ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropIndex(this.tableName, this.indexName);\n }\n\n renderTypeScript(): string {\n return `dropIndex(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.indexName)})`;\n }\n}\n\n// ============================================================================\n// Data transform\n// ============================================================================\n\n/**\n * A planner-generated data-transform stub. The current default strategy\n * (`nullabilityTighteningBackfillStrategy`) emits one of these with a\n * backfill-flavored `id`/`label` when the policy allows `'data'` and the\n * contract tightens a column's nullability, but the op itself is generic —\n * any future strategy that needs a placeholder data step can construct one\n * with its own id/label.\n *\n * `toOp()` always throws `PN-MIG-2001`: the planner cannot lower a stubbed\n * transform to a runtime op — the user must edit the rendered\n * `migration.ts` and re-emit.\n */\nexport class DataTransformCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'dataTransform' as const;\n readonly operationClass = 'data' as const;\n readonly id: string;\n readonly label: string;\n readonly tableName: string;\n readonly columnName: string;\n\n constructor(id: string, label: string, tableName: string, columnName: string) {\n super();\n this.id = id;\n this.label = label;\n this.tableName = tableName;\n this.columnName = columnName;\n this.freeze();\n }\n\n toOp(): Op {\n throw errorUnfilledPlaceholder(this.label);\n }\n\n renderTypeScript(): string {\n const slot = `${this.tableName}-${this.columnName}-backfill-sql`;\n return [\n 'dataTransform({',\n ` id: ${jsonToTsSource(this.id)},`,\n ` label: ${jsonToTsSource(this.label)},`,\n ` table: ${jsonToTsSource(this.tableName)},`,\n ` description: ${jsonToTsSource(`Backfill NULL ${this.columnName} values in ${this.tableName}`)},`,\n ` run: () => placeholder(${jsonToTsSource(slot)}),`,\n '})',\n ].join('\\n');\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [\n { moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: this.factoryName },\n { moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: 'placeholder' },\n ];\n }\n}\n\n// ============================================================================\n// Raw SQL\n// ============================================================================\n\n/**\n * Laundered pre-built operation. Mirrors Postgres's `RawSqlCall`: wraps an\n * already-materialized `SqlMigrationPlanOperation` (typically produced by a\n * SQL-family helper or a codec lifecycle hook) so the planner can carry it\n * alongside structured call IR. `toOp()` returns the stored op unchanged;\n * `renderTypeScript()` emits `rawSql({...})` with the op serialized as a\n * JSON literal — round-tripping requires every field on the op to be\n * JSON-serializable (no closures).\n */\nexport class RawSqlCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'rawSql' as const;\n readonly operationClass: MigrationOperationClass;\n readonly label: string;\n readonly op: Op;\n\n constructor(op: Op) {\n super();\n this.op = op;\n this.label = op.label;\n this.operationClass = op.operationClass;\n this.freeze();\n }\n\n toOp(): Op {\n return this.op;\n }\n\n renderTypeScript(): string {\n return `rawSql(${jsonToTsSource(this.op)})`;\n }\n}\n\n// ============================================================================\n// Union\n// ============================================================================\n\nexport type SqliteOpFactoryCall =\n | CreateTableCall\n | DropTableCall\n | RecreateTableCall\n | AddColumnCall\n | DropColumnCall\n | CreateIndexCall\n | DropIndexCall\n | DataTransformCall\n | RawSqlCall;\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAM,0BAA0B;AAEhC,IAAe,0BAAf,cAA+C,aAA+C;CAM5F,qBAAmD;EACjD,OAAO,CAAC;GAAE,iBAAiB;GAAyB,QAAQ,KAAK;GAAa,CAAC;;CAGjF,SAAyB;EACvB,OAAO,OAAO,KAAK;;;AAQvB,IAAa,kBAAb,cAAqC,wBAAwB;CAC3D,cAAuB;CACvB,iBAA0B;CAC1B;CACA;CACA;CAEA,YAAY,WAAmB,MAAuB;EACpD,OAAO;EACP,KAAK,YAAY;EACjB,KAAK,OAAO;EACZ,KAAK,QAAQ,gBAAgB;EAC7B,KAAK,QAAQ;;CAGf,OAAW;EACT,OAAO,YAAY,KAAK,WAAW,KAAK,KAAK;;CAG/C,mBAA2B;EACzB,OAAO,eAAe,eAAe,KAAK,UAAU,CAAC,IAAI,eAAe,KAAK,KAAK,CAAC;;;AAIvF,IAAa,gBAAb,cAAmC,wBAAwB;CACzD,cAAuB;CACvB,iBAA0B;CAC1B;CACA;CAEA,YAAY,WAAmB;EAC7B,OAAO;EACP,KAAK,YAAY;EACjB,KAAK,QAAQ,cAAc;EAC3B,KAAK,QAAQ;;CAGf,OAAW;EACT,OAAO,UAAU,KAAK,UAAU;;CAGlC,mBAA2B;EACzB,OAAO,aAAa,eAAe,KAAK,UAAU,CAAC;;;AAIvD,IAAa,oBAAb,cAAuC,wBAAwB;CAC7D,cAAuB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,MAQT;EACD,OAAO;EACP,KAAK,YAAY,KAAK;EACtB,KAAK,gBAAgB,KAAK;EAC1B,KAAK,oBAAoB,KAAK;EAC9B,KAAK,UAAU,KAAK;EACpB,KAAK,UAAU,KAAK;EACpB,KAAK,aAAa,KAAK;EACvB,KAAK,iBAA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BAAkB,eAAe,iBAAiB,KAAK,WAAW,aAAa,KAAK,YAAY,CAAC;GACjG,4BAA4B,eAAe,KAAK,CAAC;GACjD;GACD,CAAC,KAAK,KAAK;;CAGd,qBAA4D;EAC1D,OAAO,CACL;GAAE,iBAAiB;GAAyB,QAAQ,KAAK;GAAa,EACtE;GAAE,iBAAiB;GAAyB,QAAQ;GAAe,CACpE;;;;;;;;;;;;AAiBL,IAAa,aAAb,cAAgC,wBAAwB;CACtD,cAAuB;CACvB;CACA;CACA;CAEA,YAAY,IAAQ;EAClB,OAAO;EACP,KAAK,KAAK;EACV,KAAK,QAAQ,GAAG;EAChB,KAAK,iBAAiB,GAAG;EACzB,KAAK,QAAQ;;CAGf,OAAW;EACT,OAAO,KAAK;;CAGd,mBAA2B;EACzB,OAAO,UAAU,eAAe,KAAK,GAAG,CAAC"}
1
+ {"version":3,"file":"op-factory-call-BRp16Nsr.mjs","names":[],"sources":["../src/core/migrations/op-factory-call.ts"],"sourcesContent":["/**\n * SQLite migration IR: one concrete `*Call` class per pure factory under\n * `operations/`, plus a shared `SqliteOpFactoryCallNode` abstract base.\n *\n * Each call class carries fully-resolved literal arguments (flat\n * `SqliteColumnSpec` / `SqliteTableSpec` etc.) — codec / `typeRef` / default\n * expansion happens upstream in the issue-planner / strategies, mirroring\n * the Postgres `ColumnSpec` pattern. As a result, `toOp()` and\n * `renderTypeScript()` both pass the same flat data through; the rendered\n * TypeScript scaffold is fully self-contained and does not need access to a\n * `storageTypes` map at runtime.\n */\n\nimport { errorUnfilledPlaceholder } from '@prisma-next/errors/migration';\nimport type {\n MigrationOperationClass,\n SqlMigrationPlanOperation,\n} from '@prisma-next/family-sql/control';\nimport type { OpFactoryCall as FrameworkOpFactoryCall } from '@prisma-next/framework-components/control';\nimport { type ImportRequirement, jsonToTsSource, TsExpression } from '@prisma-next/ts-render';\nimport { addColumn, dropColumn } from './operations/columns';\nimport { createIndex, dropIndex } from './operations/indexes';\nimport type { SqliteColumnSpec, SqliteIndexSpec, SqliteTableSpec } from './operations/shared';\nimport { createTable, dropTable, recreateTable } from './operations/tables';\nimport type { SqlitePlanTargetDetails } from './planner-target-details';\n\ntype Op = SqlMigrationPlanOperation<SqlitePlanTargetDetails>;\n\nconst TARGET_MIGRATION_MODULE = '@prisma-next/target-sqlite/migration';\n\nabstract class SqliteOpFactoryCallNode extends TsExpression implements FrameworkOpFactoryCall {\n abstract readonly factoryName: string;\n abstract readonly operationClass: MigrationOperationClass;\n abstract readonly label: string;\n abstract toOp(): Op;\n\n importRequirements(): readonly ImportRequirement[] {\n return [{ moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: this.factoryName }];\n }\n\n protected freeze(): void {\n Object.freeze(this);\n }\n}\n\n// ============================================================================\n// Table\n// ============================================================================\n\nexport class CreateTableCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'createTable' as const;\n readonly operationClass = 'additive' as const;\n readonly tableName: string;\n readonly spec: SqliteTableSpec;\n readonly label: string;\n\n constructor(tableName: string, spec: SqliteTableSpec) {\n super();\n this.tableName = tableName;\n this.spec = spec;\n this.label = `Create table ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return createTable(this.tableName, this.spec);\n }\n\n renderTypeScript(): string {\n return `createTable(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.spec)})`;\n }\n}\n\nexport class DropTableCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'dropTable' as const;\n readonly operationClass = 'destructive' as const;\n readonly tableName: string;\n readonly label: string;\n\n constructor(tableName: string) {\n super();\n this.tableName = tableName;\n this.label = `Drop table ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropTable(this.tableName);\n }\n\n renderTypeScript(): string {\n return `dropTable(${jsonToTsSource(this.tableName)})`;\n }\n}\n\nexport class RecreateTableCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'recreateTable' as const;\n readonly operationClass: MigrationOperationClass;\n readonly tableName: string;\n readonly contractTable: SqliteTableSpec;\n readonly schemaColumnNames: readonly string[];\n readonly indexes: readonly SqliteIndexSpec[];\n readonly summary: string;\n readonly postchecks: readonly { readonly description: string; readonly sql: string }[];\n readonly label: string;\n\n constructor(args: {\n tableName: string;\n contractTable: SqliteTableSpec;\n schemaColumnNames: readonly string[];\n indexes: readonly SqliteIndexSpec[];\n summary: string;\n postchecks: readonly { readonly description: string; readonly sql: string }[];\n operationClass: MigrationOperationClass;\n }) {\n super();\n this.tableName = args.tableName;\n this.contractTable = args.contractTable;\n this.schemaColumnNames = args.schemaColumnNames;\n this.indexes = args.indexes;\n this.summary = args.summary;\n this.postchecks = args.postchecks;\n this.operationClass = args.operationClass;\n this.label = `Recreate table ${args.tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return recreateTable({\n tableName: this.tableName,\n contractTable: this.contractTable,\n schemaColumnNames: this.schemaColumnNames,\n indexes: this.indexes,\n summary: this.summary,\n postchecks: this.postchecks,\n operationClass: this.operationClass,\n });\n }\n\n renderTypeScript(): string {\n const args = {\n tableName: this.tableName,\n contractTable: this.contractTable,\n schemaColumnNames: this.schemaColumnNames,\n indexes: this.indexes,\n summary: this.summary,\n postchecks: this.postchecks,\n operationClass: this.operationClass,\n };\n return `recreateTable(${jsonToTsSource(args)})`;\n }\n}\n\n// ============================================================================\n// Column\n// ============================================================================\n\nexport class AddColumnCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'addColumn' as const;\n readonly operationClass = 'additive' as const;\n readonly tableName: string;\n readonly columnName: string;\n readonly column: SqliteColumnSpec;\n readonly label: string;\n\n constructor(tableName: string, column: SqliteColumnSpec) {\n super();\n this.tableName = tableName;\n this.columnName = column.name;\n this.column = column;\n this.label = `Add column ${column.name} on ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return addColumn(this.tableName, this.column);\n }\n\n renderTypeScript(): string {\n return `addColumn(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.column)})`;\n }\n}\n\nexport class DropColumnCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'dropColumn' as const;\n readonly operationClass = 'destructive' as const;\n readonly tableName: string;\n readonly columnName: string;\n readonly label: string;\n\n constructor(tableName: string, columnName: string) {\n super();\n this.tableName = tableName;\n this.columnName = columnName;\n this.label = `Drop column ${columnName} on ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropColumn(this.tableName, this.columnName);\n }\n\n renderTypeScript(): string {\n return `dropColumn(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.columnName)})`;\n }\n}\n\n// ============================================================================\n// Index\n// ============================================================================\n\nexport class CreateIndexCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'createIndex' as const;\n readonly operationClass = 'additive' as const;\n readonly tableName: string;\n readonly indexName: string;\n readonly columns: readonly string[];\n readonly label: string;\n\n constructor(tableName: string, indexName: string, columns: readonly string[]) {\n super();\n this.tableName = tableName;\n this.indexName = indexName;\n this.columns = columns;\n this.label = `Create index ${indexName} on ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return createIndex(this.tableName, this.indexName, this.columns);\n }\n\n renderTypeScript(): string {\n return `createIndex(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.indexName)}, ${jsonToTsSource(this.columns)})`;\n }\n}\n\nexport class DropIndexCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'dropIndex' as const;\n readonly operationClass = 'destructive' as const;\n readonly tableName: string;\n readonly indexName: string;\n readonly label: string;\n\n constructor(tableName: string, indexName: string) {\n super();\n this.tableName = tableName;\n this.indexName = indexName;\n this.label = `Drop index ${indexName} on ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropIndex(this.tableName, this.indexName);\n }\n\n renderTypeScript(): string {\n return `dropIndex(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.indexName)})`;\n }\n}\n\n// ============================================================================\n// Data transform\n// ============================================================================\n\n/**\n * A planner-generated data-transform stub. The current default strategy\n * (`nullabilityTighteningBackfillStrategy`) emits one of these with a\n * backfill-flavored `id`/`label` when the policy allows `'data'` and the\n * contract tightens a column's nullability, but the op itself is generic —\n * any future strategy that needs a placeholder data step can construct one\n * with its own id/label.\n *\n * `toOp()` always throws `PN-MIG-2001`: the planner cannot lower a stubbed\n * transform to a runtime op — the user must edit the rendered\n * `migration.ts` and re-emit.\n */\nexport class DataTransformCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'dataTransform' as const;\n readonly operationClass = 'data' as const;\n readonly id: string;\n readonly label: string;\n readonly tableName: string;\n readonly columnName: string;\n\n constructor(id: string, label: string, tableName: string, columnName: string) {\n super();\n this.id = id;\n this.label = label;\n this.tableName = tableName;\n this.columnName = columnName;\n this.freeze();\n }\n\n toOp(): Op {\n throw errorUnfilledPlaceholder(this.label);\n }\n\n renderTypeScript(): string {\n const slot = `${this.tableName}-${this.columnName}-backfill-sql`;\n return [\n 'dataTransform({',\n ` id: ${jsonToTsSource(this.id)},`,\n ` label: ${jsonToTsSource(this.label)},`,\n ` table: ${jsonToTsSource(this.tableName)},`,\n ` description: ${jsonToTsSource(`Backfill NULL ${this.columnName} values in ${this.tableName}`)},`,\n ` run: () => placeholder(${jsonToTsSource(slot)}),`,\n '})',\n ].join('\\n');\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [\n { moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: this.factoryName },\n { moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: 'placeholder' },\n ];\n }\n}\n\n// ============================================================================\n// Raw SQL\n// ============================================================================\n\n/**\n * Laundered pre-built operation. Mirrors Postgres's `RawSqlCall`: wraps an\n * already-materialized `SqlMigrationPlanOperation` (typically produced by a\n * SQL-family helper or a codec lifecycle hook) so the planner can carry it\n * alongside structured call IR. `toOp()` returns the stored op unchanged;\n * `renderTypeScript()` emits `rawSql({...})` with the op serialized as a\n * JSON literal — round-tripping requires every field on the op to be\n * JSON-serializable (no closures).\n */\nexport class RawSqlCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'rawSql' as const;\n readonly operationClass: MigrationOperationClass;\n readonly label: string;\n readonly op: Op;\n\n constructor(op: Op) {\n super();\n this.op = op;\n this.label = op.label;\n this.operationClass = op.operationClass;\n this.freeze();\n }\n\n toOp(): Op {\n return this.op;\n }\n\n renderTypeScript(): string {\n return `rawSql(${jsonToTsSource(this.op)})`;\n }\n}\n\n// ============================================================================\n// Union\n// ============================================================================\n\nexport type SqliteOpFactoryCall =\n | CreateTableCall\n | DropTableCall\n | RecreateTableCall\n | AddColumnCall\n | DropColumnCall\n | CreateIndexCall\n | DropIndexCall\n | DataTransformCall\n | RawSqlCall;\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAM,0BAA0B;AAEhC,IAAe,0BAAf,cAA+C,aAA+C;CAM5F,qBAAmD;EACjD,OAAO,CAAC;GAAE,iBAAiB;GAAyB,QAAQ,KAAK;GAAa,CAAC;;CAGjF,SAAyB;EACvB,OAAO,OAAO,KAAK;;;AAQvB,IAAa,kBAAb,cAAqC,wBAAwB;CAC3D,cAAuB;CACvB,iBAA0B;CAC1B;CACA;CACA;CAEA,YAAY,WAAmB,MAAuB;EACpD,OAAO;EACP,KAAK,YAAY;EACjB,KAAK,OAAO;EACZ,KAAK,QAAQ,gBAAgB;EAC7B,KAAK,QAAQ;;CAGf,OAAW;EACT,OAAO,YAAY,KAAK,WAAW,KAAK,KAAK;;CAG/C,mBAA2B;EACzB,OAAO,eAAe,eAAe,KAAK,UAAU,CAAC,IAAI,eAAe,KAAK,KAAK,CAAC;;;AAIvF,IAAa,gBAAb,cAAmC,wBAAwB;CACzD,cAAuB;CACvB,iBAA0B;CAC1B;CACA;CAEA,YAAY,WAAmB;EAC7B,OAAO;EACP,KAAK,YAAY;EACjB,KAAK,QAAQ,cAAc;EAC3B,KAAK,QAAQ;;CAGf,OAAW;EACT,OAAO,UAAU,KAAK,UAAU;;CAGlC,mBAA2B;EACzB,OAAO,aAAa,eAAe,KAAK,UAAU,CAAC;;;AAIvD,IAAa,oBAAb,cAAuC,wBAAwB;CAC7D,cAAuB;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;EACT,MAAM,yBAAyB,KAAK,MAAM;;CAG5C,mBAA2B;EACzB,MAAM,OAAO,GAAG,KAAK,UAAU,GAAG,KAAK,WAAW;EAClD,OAAO;GACL;GACA,SAAS,eAAe,KAAK,GAAG,CAAC;GACjC,YAAY,eAAe,KAAK,MAAM,CAAC;GACvC,YAAY,eAAe,KAAK,UAAU,CAAC;GAC3C,kBAAkB,eAAe,iBAAiB,KAAK,WAAW,aAAa,KAAK,YAAY,CAAC;GACjG,4BAA4B,eAAe,KAAK,CAAC;GACjD;GACD,CAAC,KAAK,KAAK;;CAGd,qBAA4D;EAC1D,OAAO,CACL;GAAE,iBAAiB;GAAyB,QAAQ,KAAK;GAAa,EACtE;GAAE,iBAAiB;GAAyB,QAAQ;GAAe,CACpE;;;;;;;;;;;;AAiBL,IAAa,aAAb,cAAgC,wBAAwB;CACtD,cAAuB;CACvB;CACA;CACA;CAEA,YAAY,IAAQ;EAClB,OAAO;EACP,KAAK,KAAK;EACV,KAAK,QAAQ,GAAG;EAChB,KAAK,iBAAiB,GAAG;EACzB,KAAK,QAAQ;;CAGf,OAAW;EACT,OAAO,KAAK;;CAGd,mBAA2B;EACzB,OAAO,UAAU,eAAe,KAAK,GAAG,CAAC"}
@@ -1,2 +1,2 @@
1
- import { a as DropColumnCall, c as RawSqlCall, i as DataTransformCall, l as RecreateTableCall, n as CreateIndexCall, o as DropIndexCall, r as CreateTableCall, s as DropTableCall, t as AddColumnCall } from "./op-factory-call-DRKKURAO.mjs";
1
+ import { a as DropColumnCall, c as RawSqlCall, i as DataTransformCall, l as RecreateTableCall, n as CreateIndexCall, o as DropIndexCall, r as CreateTableCall, s as DropTableCall, t as AddColumnCall } from "./op-factory-call-BRp16Nsr.mjs";
2
2
  export { AddColumnCall, CreateIndexCall, CreateTableCall, DataTransformCall, DropColumnCall, DropIndexCall, DropTableCall, RawSqlCall, RecreateTableCall };
@@ -1,7 +1,7 @@
1
1
  import { t as parseSqliteDefault } from "./default-normalizer-3Fccw7yw.mjs";
2
2
  import { t as normalizeSqliteNativeType } from "./native-type-normalizer-BlN5XfD-.mjs";
3
- import { c as buildColumnDefaultSql, l as buildColumnTypeSql, n as buildRecreateSummary, t as buildRecreatePostchecks, u as isInlineAutoincrementPrimaryKey } from "./tables-D84zfPZI.mjs";
4
- import { a as DropColumnCall, i as DataTransformCall, l as RecreateTableCall, n as CreateIndexCall, o as DropIndexCall, r as CreateTableCall, s as DropTableCall, t as AddColumnCall } from "./op-factory-call-DRKKURAO.mjs";
3
+ import { c as buildColumnDefaultSql, l as buildColumnTypeSql, n as buildRecreateSummary, t as buildRecreatePostchecks, u as isInlineAutoincrementPrimaryKey } from "./tables-DGRRJasz.mjs";
4
+ import { a as DropColumnCall, i as DataTransformCall, l as RecreateTableCall, n as CreateIndexCall, o as DropIndexCall, r as CreateTableCall, s as DropTableCall, t as AddColumnCall } from "./op-factory-call-BRp16Nsr.mjs";
5
5
  import { n as CONTROL_TABLE_NAMES } from "./statement-builders-Dne-LkAV.mjs";
6
6
  import { t as TypeScriptRenderableSqliteMigration } from "./planner-produced-sqlite-migration-C_TzWbT0.mjs";
7
7
  import { extractCodecControlHooks, planFieldEventOperations, plannerFailure } from "@prisma-next/family-sql/control";
@@ -519,4 +519,4 @@ var SqliteMigrationPlanner = class {
519
519
  //#endregion
520
520
  export { createSqliteMigrationPlanner as n, SqliteMigrationPlanner as t };
521
521
 
522
- //# sourceMappingURL=planner-A7dqS0u6.mjs.map
522
+ //# sourceMappingURL=planner-CKzXAj4i.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"planner-CKzXAj4i.mjs","names":[],"sources":["../src/core/migrations/planner-strategies.ts","../src/core/migrations/issue-planner.ts","../src/core/migrations/planner.ts"],"sourcesContent":["/**\n * SQLite migration strategies.\n *\n * Each strategy examines the issue list, consumes issues it handles, and\n * returns the `SqliteOpFactoryCall[]` to address them. The issue planner\n * runs each strategy in order and routes whatever's left through\n * `mapIssueToCall`.\n *\n * SQLite has no enums, no data-safe backfill, and no component-declared\n * database dependencies. The only recipe that needs strategy-level\n * multi-issue consumption is `recreateTable` (added in a later phase), which\n * absorbs type/nullability/default/constraint mismatches for a given table\n * into a single recreate operation.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n MigrationOperationClass,\n MigrationOperationPolicy,\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 {\n PostgresEnumStorageEntry,\n SqlStorage,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { defaultIndexName } from '@prisma-next/sql-schema-ir/naming';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { toTableSpec } from './issue-planner';\nimport { DataTransformCall, RecreateTableCall, type SqliteOpFactoryCall } from './op-factory-call';\nimport type { SqliteIndexSpec } from './operations/shared';\nimport { buildRecreatePostchecks, buildRecreateSummary } from './operations/tables';\n\nexport interface StrategyContext {\n readonly toContract: Contract<SqlStorage>;\n readonly fromContract: Contract<SqlStorage> | null;\n readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;\n readonly storageTypes: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>;\n readonly schema: SqlSchemaIR;\n readonly policy: MigrationOperationPolicy;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}\n\nexport type CallMigrationStrategy = (\n issues: readonly SchemaIssue[],\n context: StrategyContext,\n) =>\n | {\n kind: 'match';\n issues: readonly SchemaIssue[];\n calls: readonly SqliteOpFactoryCall[];\n recipe?: boolean;\n }\n | { kind: 'no_match' };\n\n// ============================================================================\n// Recreate-table strategy\n// ============================================================================\n\nconst WIDENING_ISSUE_KINDS = new Set<SchemaIssue['kind']>(['default_mismatch', 'default_missing']);\n\nconst DESTRUCTIVE_ISSUE_KINDS = new Set<SchemaIssue['kind']>([\n 'extra_default',\n 'type_mismatch',\n 'primary_key_mismatch',\n 'foreign_key_mismatch',\n 'unique_constraint_mismatch',\n 'extra_foreign_key',\n 'extra_unique_constraint',\n 'extra_primary_key',\n]);\n\nfunction classifyIssue(issue: SchemaIssue): 'widening' | 'destructive' | null {\n if (issue.kind === 'enum_values_changed') return null;\n if (!issue.table) return null;\n if (issue.kind === 'nullability_mismatch') {\n // Relaxing (NOT NULL → nullable) is widening; tightening is destructive.\n return issue.expected === 'true' ? 'widening' : 'destructive';\n }\n if (WIDENING_ISSUE_KINDS.has(issue.kind)) return 'widening';\n if (DESTRUCTIVE_ISSUE_KINDS.has(issue.kind)) return 'destructive';\n return null;\n}\n\n/**\n * Groups recreate-eligible issues by table, decides per-table operation class\n * (destructive wins over widening), and emits one `RecreateTableCall` per\n * table. Returns unchanged-or-smaller issue list — issues the strategy\n * consumed are removed so `mapIssueToCall` doesn't double-handle them.\n */\nexport const recreateTableStrategy: CallMigrationStrategy = (issues, ctx) => {\n const byTable = new Map<string, { issues: SchemaIssue[]; hasDestructive: boolean }>();\n const consumed = new Set<SchemaIssue>();\n\n for (const issue of issues) {\n const cls = classifyIssue(issue);\n if (!cls) continue;\n if (issue.kind === 'enum_values_changed') continue;\n if (!issue.table) continue;\n const table = issue.table;\n const entry = byTable.get(table);\n if (entry) {\n entry.issues.push(issue);\n if (cls === 'destructive') entry.hasDestructive = true;\n } else {\n byTable.set(table, { issues: [issue], hasDestructive: cls === 'destructive' });\n }\n consumed.add(issue);\n }\n\n if (byTable.size === 0) return { kind: 'no_match' };\n\n const calls: SqliteOpFactoryCall[] = [];\n for (const [tableName, entry] of byTable) {\n const contractTable = ctx.toContract.storage.tables[tableName];\n const schemaTable = ctx.schema.tables[tableName];\n if (!contractTable || !schemaTable) continue;\n const operationClass: MigrationOperationClass = entry.hasDestructive\n ? 'destructive'\n : 'widening';\n\n // Flatten the contract table to a self-contained spec — the Call holds\n // pre-rendered SQL fragments only, no `StorageColumn` or `storageTypes`.\n const tableSpec = toTableSpec(contractTable, ctx.storageTypes);\n\n const seenIndexColumnKeys = new Set<string>();\n const indexes: SqliteIndexSpec[] = [];\n for (const idx of contractTable.indexes) {\n const key = idx.columns.join(',');\n if (seenIndexColumnKeys.has(key)) continue;\n seenIndexColumnKeys.add(key);\n indexes.push({\n name: idx.name ?? defaultIndexName(tableName, idx.columns),\n columns: idx.columns,\n });\n }\n for (const fk of contractTable.foreignKeys) {\n if (fk.index === false) continue;\n const key = fk.columns.join(',');\n if (seenIndexColumnKeys.has(key)) continue;\n seenIndexColumnKeys.add(key);\n indexes.push({\n name: defaultIndexName(tableName, fk.columns),\n columns: fk.columns,\n });\n }\n\n calls.push(\n new RecreateTableCall({\n tableName,\n contractTable: tableSpec,\n schemaColumnNames: Object.keys(schemaTable.columns),\n indexes,\n summary: buildRecreateSummary(tableName, entry.issues),\n postchecks: buildRecreatePostchecks(tableName, entry.issues, tableSpec),\n operationClass,\n }),\n );\n }\n\n return {\n kind: 'match',\n issues: issues.filter((i) => !consumed.has(i)),\n calls,\n recipe: true,\n };\n};\n\n// ============================================================================\n// Nullability-tightening backfill strategy\n// ============================================================================\n\n/**\n * When the policy allows `'data'` and the contract tightens one or more\n * columns from nullable to NOT NULL, emit a `DataTransformCall` stub per\n * tightened column. The user fills the backfill `UPDATE` in the rendered\n * `migration.ts` before the subsequent `RecreateTableCall` copies data into\n * the tightened schema (whose `INSERT INTO temp SELECT … FROM old` would\n * otherwise fail at runtime if any `NULL`s remain).\n *\n * Does NOT consume the tightening issue — `recreateTableStrategy` still\n * needs it to produce the actual recreate that enforces the NOT NULL at\n * the schema level. The backfill op and the recreate op end up in the\n * recipe slot in strategy order (backfill first, recreate second), which\n * matches the required execution order.\n *\n * Mirrors Postgres's `nullableTighteningCallStrategy` / `'data'`-class\n * gating. When `'data'` is not in the policy (the default `db update` /\n * `db init` path), the strategy short-circuits and the recreate alone\n * runs with its current destructive-class gating — preserving today's\n * behavior where a tightening blows up at runtime if NULLs are present.\n */\nexport const nullabilityTighteningBackfillStrategy: CallMigrationStrategy = (issues, ctx) => {\n if (!ctx.policy.allowedOperationClasses.includes('data')) {\n return { kind: 'no_match' };\n }\n\n const calls: SqliteOpFactoryCall[] = [];\n for (const issue of issues) {\n if (issue.kind !== 'nullability_mismatch') continue;\n if (!issue.table || !issue.column) continue;\n // Tightening only: `expected === 'true'` means the contract wants the\n // column nullable (relaxing from NOT NULL → nullable), which is safe and\n // needs no backfill.\n if (issue.expected === 'true') continue;\n\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column || column.nullable === true) continue;\n\n calls.push(\n new DataTransformCall(\n `data_migration.backfill-${issue.table}-${issue.column}`,\n `Backfill NULLs in \"${issue.table}\".\"${issue.column}\" before NOT NULL tightening`,\n issue.table,\n issue.column,\n ),\n );\n }\n\n if (calls.length === 0) return { kind: 'no_match' };\n\n return {\n kind: 'match',\n issues,\n calls,\n recipe: true,\n };\n};\n\nexport const sqlitePlannerStrategies: readonly CallMigrationStrategy[] = [\n nullabilityTighteningBackfillStrategy,\n recreateTableStrategy,\n];\n","/**\n * SQLite migration issue planner.\n *\n * Takes schema issues (from `verifySqlSchema`) and emits migration IR\n * (`SqliteOpFactoryCall[]`). Strategies consume issues they recognize and\n * produce specialized call sequences (e.g. recreateTableStrategy absorbs\n * type/nullability/default/constraint mismatches into a single recreate op);\n * remaining issues flow 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 type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport type {\n PostgresEnumStorageEntry,\n SqlStorage,\n StorageColumn,\n StorageTable,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { defaultIndexName } from '@prisma-next/sql-schema-ir/naming';\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 CreateIndexCall,\n CreateTableCall,\n DropColumnCall,\n DropIndexCall,\n DropTableCall,\n type SqliteOpFactoryCall,\n} from './op-factory-call';\nimport type {\n SqliteColumnSpec,\n SqliteForeignKeySpec,\n SqliteTableSpec,\n SqliteUniqueSpec,\n} from './operations/shared';\nimport {\n buildColumnDefaultSql,\n buildColumnTypeSql,\n isInlineAutoincrementPrimaryKey,\n} from './planner-ddl-builders';\nimport {\n type CallMigrationStrategy,\n type StrategyContext,\n sqlitePlannerStrategies,\n} from './planner-strategies';\nimport { CONTROL_TABLE_NAMES } from './statement-builders';\n\nexport type { CallMigrationStrategy, StrategyContext };\n\n// ============================================================================\n// Issue kind ordering (dependency order)\n// ============================================================================\n\nconst ISSUE_KIND_ORDER: Record<string, number> = {\n // Drops (reconciliation — clear the way for creates)\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\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// ============================================================================\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 conflictKindForIssue(issue: SchemaIssue): SqlPlannerConflict['kind'] {\n switch (issue.kind) {\n case 'type_mismatch':\n return 'typeMismatch';\n case 'nullability_mismatch':\n return 'nullabilityConflict';\n case 'primary_key_mismatch':\n case 'unique_constraint_mismatch':\n case 'index_mismatch':\n case 'extra_primary_key':\n case 'extra_unique_constraint':\n return 'indexIncompatible';\n case 'foreign_key_mismatch':\n case 'extra_foreign_key':\n return 'foreignKeyConflict';\n default:\n return 'missingButNonAdditive';\n }\n}\n\nfunction issueLocation(issue: SchemaIssue): SqlPlannerConflictLocation | undefined {\n if (issue.kind === 'enum_values_changed') return undefined;\n const location: {\n table?: string;\n column?: string;\n constraint?: string;\n } = {};\n if (issue.table) location.table = issue.table;\n if (issue.column) location.column = issue.column;\n if (issue.indexOrConstraint) location.constraint = issue.indexOrConstraint;\n return Object.keys(location).length > 0 ? (location as SqlPlannerConflictLocation) : undefined;\n}\n\nfunction conflictForDisallowedCall(\n call: SqliteOpFactoryCall,\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\nfunction conflictKindForCall(call: SqliteOpFactoryCall): SqlPlannerConflict['kind'] {\n switch (call.factoryName) {\n case 'createIndex':\n case 'dropIndex':\n return 'indexIncompatible';\n default:\n return 'missingButNonAdditive';\n }\n}\n\nfunction locationForCall(call: SqliteOpFactoryCall): SqlPlannerConflictLocation | undefined {\n const location: { table?: string; column?: string; index?: string } = {};\n if ('tableName' in call) location.table = call.tableName;\n if ('columnName' in call) location.column = call.columnName;\n if ('indexName' in call) location.index = call.indexName;\n return Object.keys(location).length > 0 ? (location as SqlPlannerConflictLocation) : undefined;\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// StorageTable / StorageColumn → flat SqliteTableSpec\n// ============================================================================\n\n/**\n * Resolves codec / `typeRef` / default rendering into a flat\n * `SqliteColumnSpec`. Mirrors Postgres's `toColumnSpec`. Once a column is\n * flattened, downstream Calls and operation factories never see\n * `StorageColumn` again — they deal in pre-rendered SQL fragments.\n */\nexport function toColumnSpec(\n name: string,\n column: StorageColumn,\n storageTypes: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>,\n inlineAutoincrementPrimaryKey = false,\n): SqliteColumnSpec {\n const typeSql = buildColumnTypeSql(\n column,\n storageTypes as Record<string, StorageTypeInstance | PostgresEnumStorageEntry>,\n );\n const defaultSql = buildColumnDefaultSql(column.default);\n return {\n name,\n typeSql,\n defaultSql,\n nullable: column.nullable,\n ...(inlineAutoincrementPrimaryKey ? { inlineAutoincrementPrimaryKey: true } : {}),\n };\n}\n\n/**\n * Flattens a `StorageTable` into a `SqliteTableSpec` ready for\n * `CreateTableCall` / `RecreateTableCall`. Sole-column AUTOINCREMENT\n * primary keys are detected here and marked on the column spec so the\n * renderer emits `INTEGER PRIMARY KEY AUTOINCREMENT` inline.\n */\nexport function toTableSpec(\n table: StorageTable,\n storageTypes: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>,\n): SqliteTableSpec {\n const columns: SqliteColumnSpec[] = Object.entries(table.columns).map(([name, column]) =>\n toColumnSpec(name, column, storageTypes, isInlineAutoincrementPrimaryKey(table, name)),\n );\n const uniques: SqliteUniqueSpec[] = table.uniques.map((u) => ({\n columns: u.columns,\n ...(u.name !== undefined ? { name: u.name } : {}),\n }));\n const foreignKeys: SqliteForeignKeySpec[] = table.foreignKeys.map((fk) => ({\n columns: fk.columns,\n references: { table: fk.references.table, columns: fk.references.columns },\n constraint: fk.constraint !== false,\n ...(fk.name !== undefined ? { name: fk.name } : {}),\n ...(fk.onDelete !== undefined ? { onDelete: fk.onDelete } : {}),\n ...(fk.onUpdate !== undefined ? { onUpdate: fk.onUpdate } : {}),\n }));\n return {\n columns,\n ...(table.primaryKey ? { primaryKey: { columns: table.primaryKey.columns } } : {}),\n uniques,\n foreignKeys,\n };\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 codecHooks: ReadonlyMap<string, CodecControlHooks>;\n readonly storageTypes: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>;\n readonly schema?: SqlSchemaIR;\n readonly policy?: MigrationOperationPolicy;\n readonly frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n readonly strategies?: readonly CallMigrationStrategy[];\n}\n\nexport interface IssuePlannerValue {\n readonly calls: readonly SqliteOpFactoryCall[];\n}\n\nconst DEFAULT_POLICY: MigrationOperationPolicy = {\n allowedOperationClasses: ['additive', 'widening', 'destructive', 'data'],\n};\n\nfunction emptySchemaIR(): SqlSchemaIR {\n return { tables: {} };\n}\n\n// ============================================================================\n// Issue → Call mapping (per-issue default path)\n// ============================================================================\n\nfunction mapIssueToCall(\n issue: SchemaIssue,\n ctx: StrategyContext,\n): Result<readonly SqliteOpFactoryCall[], SqlPlannerConflict> {\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 }\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 tableSpec = toTableSpec(contractTable, ctx.storageTypes);\n const calls: SqliteOpFactoryCall[] = [new CreateTableCall(issue.table, tableSpec)];\n const declaredIndexColumnKeys = new Set<string>();\n for (const index of contractTable.indexes) {\n const indexName = index.name ?? defaultIndexName(issue.table, index.columns);\n declaredIndexColumnKeys.add(index.columns.join(','));\n calls.push(new CreateIndexCall(issue.table, indexName, index.columns));\n }\n for (const fk of contractTable.foreignKeys) {\n if (fk.index === false) continue;\n if (declaredIndexColumnKeys.has(fk.columns.join(','))) continue;\n const indexName = defaultIndexName(issue.table, fk.columns);\n calls.push(new CreateIndexCall(issue.table, indexName, fk.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 }\n const contractTable = ctx.toContract.storage.tables[issue.table];\n const columnSpec = toColumnSpec(\n issue.column,\n column,\n ctx.storageTypes,\n contractTable ? isInlineAutoincrementPrimaryKey(contractTable, issue.column) : false,\n );\n return ok([new AddColumnCall(issue.table, columnSpec)]);\n }\n\n case 'index_mismatch': {\n if (!issue.table) {\n return notOk(issueConflict('indexIncompatible', 'Index issue has no table name'));\n }\n if (!isMissing(issue) || !issue.expected) {\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 const columns = issue.expected.split(', ');\n const contractTable = ctx.toContract.storage.tables[issue.table];\n if (!contractTable) {\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Table \"${issue.table}\" not found in destination contract`,\n ),\n );\n }\n // Use the explicit-index name if one is declared for these columns;\n // otherwise fall back to `defaultIndexName` (which is also what\n // `verifySqlSchema` synthesizes for FK-backing indexes). Whether the\n // missing index originates from `contractTable.indexes` or from an FK\n // with `index: true` doesn't change the emitted DDL.\n const explicitIndex = contractTable.indexes.find(\n (idx) => idx.columns.join(',') === columns.join(','),\n );\n const indexName = explicitIndex?.name ?? defaultIndexName(issue.table, columns);\n return ok([new CreateIndexCall(issue.table, indexName, columns)]);\n }\n\n case 'extra_table': {\n if (!issue.table) {\n return notOk(issueConflict('unsupportedOperation', 'Extra table issue has no table name'));\n }\n // Runner-owned control tables must never be dropped.\n if (CONTROL_TABLE_NAMES.has(issue.table)) return ok([]);\n return ok([new DropTableCall(issue.table)]);\n }\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 }\n return ok([new DropColumnCall(issue.table, issue.column)]);\n }\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 }\n return ok([new DropIndexCall(issue.table, issue.indexOrConstraint)]);\n }\n\n // SQLite has no enum types (capability `sql.enums: false`). The verifier\n // should never emit `enum_values_changed` against a SQLite schema, so if\n // we receive one it is a verifier bug — surface it as an explicit\n // conflict rather than silently dropping it.\n case 'enum_values_changed':\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n 'Received enum_values_changed against a SQLite schema (sql.enums: false) — verifier bug',\n ),\n );\n\n // Everything below is absorbed by recreateTableStrategy. If it falls\n // through here, policy or context didn't allow the recreate — surface as\n // a conflict.\n case 'type_mismatch':\n case 'nullability_mismatch':\n case 'default_mismatch':\n case 'default_missing':\n case 'extra_default':\n case 'primary_key_mismatch':\n case 'unique_constraint_mismatch':\n case 'foreign_key_mismatch':\n case 'extra_foreign_key':\n case 'extra_unique_constraint':\n case 'extra_primary_key':\n return notOk(issueConflict(conflictKindForIssue(issue), issue.message, issueLocation(issue)));\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// Call categorization for final emission order\n// ============================================================================\n\ntype CallCategory =\n | 'drop-column'\n | 'drop-index'\n | 'drop-table'\n | 'create-table'\n | 'add-column'\n | 'create-index';\n\nfunction classifyCall(call: SqliteOpFactoryCall): CallCategory | null {\n switch (call.factoryName) {\n case 'createTable':\n return 'create-table';\n case 'addColumn':\n return 'add-column';\n case 'createIndex':\n return 'create-index';\n case 'dropColumn':\n return 'drop-column';\n case 'dropIndex':\n return 'drop-index';\n case 'dropTable':\n return 'drop-table';\n // recreateTable goes into the recipe slot; return null for bucketable.\n case 'recreateTable':\n return null;\n default:\n return null;\n }\n}\n\n// ============================================================================\n// Top-level planIssues\n// ============================================================================\n\nexport function planIssues(\n options: IssuePlannerOptions,\n): Result<IssuePlannerValue, readonly SqlPlannerConflict[]> {\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 codecHooks: options.codecHooks,\n storageTypes: options.storageTypes,\n schema,\n policy,\n frameworkComponents,\n };\n\n const strategies = options.strategies ?? sqlitePlannerStrategies;\n\n let remaining = options.issues;\n const recipeCalls: SqliteOpFactoryCall[] = [];\n const bucketableCalls: SqliteOpFactoryCall[] = [];\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 bucketableCalls.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: SqliteOpFactoryCall[] = [];\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 for recipe + bucketable. Default-mapped calls for disallowed\n // classes never get here (they're surfaced as per-issue conflicts above).\n const allowed = policy.allowedOperationClasses;\n let gatedRecipe = recipeCalls;\n let gatedBucketable = bucketableCalls;\n let gatedDefault = defaultCalls;\n if (policyProvided) {\n const sink = (acc: SqliteOpFactoryCall[]) => (call: SqliteOpFactoryCall) => {\n if (allowed.includes(call.operationClass)) {\n acc.push(call);\n return;\n }\n conflicts.push(conflictForDisallowedCall(call, allowed));\n };\n const gatedRecipeBucket: SqliteOpFactoryCall[] = [];\n const gatedBucketableBucket: SqliteOpFactoryCall[] = [];\n const gatedDefaultBucket: SqliteOpFactoryCall[] = [];\n recipeCalls.forEach(sink(gatedRecipeBucket));\n bucketableCalls.forEach(sink(gatedBucketableBucket));\n defaultCalls.forEach(sink(gatedDefaultBucket));\n gatedRecipe = gatedRecipeBucket;\n gatedBucketable = gatedBucketableBucket;\n gatedDefault = gatedDefaultBucket;\n }\n\n if (conflicts.length > 0) {\n return notOk(conflicts);\n }\n\n // Final emission order matches the current monolithic planner:\n // create-table → add-column → create-index → recreate → drop-column → drop-index → drop-table\n const combined = [...gatedDefault, ...gatedBucketable];\n const byCategory = (cat: CallCategory) => combined.filter((c) => classifyCall(c) === cat);\n\n const calls: SqliteOpFactoryCall[] = [\n ...byCategory('create-table'),\n ...byCategory('add-column'),\n ...byCategory('create-index'),\n ...gatedRecipe,\n ...byCategory('drop-column'),\n ...byCategory('drop-index'),\n ...byCategory('drop-table'),\n ];\n\n return ok({ calls });\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlMigrationPlanner,\n SqlMigrationPlannerPlanOptions,\n SqlPlannerFailureResult,\n} from '@prisma-next/family-sql/control';\nimport {\n extractCodecControlHooks,\n planFieldEventOperations,\n plannerFailure,\n} from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationPlanner,\n MigrationScaffoldContext,\n SchemaIssue,\n} from '@prisma-next/framework-components/control';\nimport { parseSqliteDefault } from '../default-normalizer';\nimport { normalizeSqliteNativeType } from '../native-type-normalizer';\nimport { planIssues } from './issue-planner';\nimport {\n type SqliteMigrationDestinationInfo,\n TypeScriptRenderableSqliteMigration,\n} from './planner-produced-sqlite-migration';\nimport { sqlitePlannerStrategies } from './planner-strategies';\nimport type { SqlitePlanTargetDetails } from './planner-target-details';\n\nexport function createSqliteMigrationPlanner(): SqliteMigrationPlanner {\n return new SqliteMigrationPlanner();\n}\n\nexport type SqlitePlanResult =\n | { readonly kind: 'success'; readonly plan: TypeScriptRenderableSqliteMigration }\n | SqlPlannerFailureResult;\n\n/**\n * SQLite migration planner — a thin wrapper over `planIssues`.\n *\n * `plan()` verifies the live schema against the target contract (producing\n * `SchemaIssue[]`) and delegates to `planIssues` with the registered\n * strategies. Strategies absorb groups of related issues into composite\n * recipes (e.g. recreating a table to apply type/nullability/default/\n * constraint changes at once); anything not absorbed by a strategy flows\n * through `mapIssueToCall` in the issue planner as a one-off call.\n *\n * FK-backing indexes are surfaced by `verifySqlSchema`'s index expansion\n * (see `verify-sql-schema.ts:459-469`), so `mapIssueToCall` handles them\n * uniformly alongside user-declared indexes.\n */\nexport class SqliteMigrationPlanner\n implements SqlMigrationPlanner<SqlitePlanTargetDetails>, MigrationPlanner<'sql', 'sqlite'>\n{\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n /**\n * The \"from\" contract (state the planner assumes the database starts at),\n * or `null` for reconciliation flows.\n *\n * Typed as the framework `Contract | null` to satisfy the\n * `MigrationPlanner` interface contract; `planSql` narrows to the SQL\n * shape via `SqlMigrationPlannerPlanOptions`. Used to populate\n * `describe().from` on the produced plan as\n * `fromContract?.storage.storageHash ?? null`.\n */\n readonly fromContract: Contract | null;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n /**\n * Contract space this plan applies to. Stamped onto the produced\n * {@link TypeScriptRenderableSqliteMigration.spaceId} so the runner keys\n * the marker row by the right space.\n */\n readonly spaceId: string;\n }): SqlitePlanResult {\n return this.planSql(options as SqlMigrationPlannerPlanOptions);\n }\n\n emptyMigration(\n context: MigrationScaffoldContext,\n spaceId: string,\n ): TypeScriptRenderableSqliteMigration {\n return new TypeScriptRenderableSqliteMigration(\n [],\n {\n from: context.fromHash,\n to: context.toHash,\n },\n spaceId,\n );\n }\n\n private planSql(options: SqlMigrationPlannerPlanOptions): SqlitePlanResult {\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) return policyResult;\n\n const schemaIssues = this.collectSchemaIssues(options);\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n const storageTypes = options.contract.storage.types ?? {};\n\n const result = planIssues({\n issues: schemaIssues,\n toContract: options.contract,\n fromContract: options.fromContract,\n codecHooks,\n storageTypes,\n schema: options.schema,\n policy: options.policy,\n frameworkComponents: options.frameworkComponents,\n strategies: sqlitePlannerStrategies,\n });\n\n if (!result.ok) {\n return plannerFailure(result.failure);\n }\n\n // Codec lifecycle hook (T2.2): inline `onFieldEvent`-emitted ops after\n // structural DDL. Sub-spec § 5 fixes the ordering as\n // `structural → added → dropped → altered`, with within-group sorting by\n // `(tableName, fieldName)` deterministic for byte-stable re-emits.\n // Hook fires only at the application emitter — extension-space planning\n // (M2 R2) never reaches this helper.\n const fieldEventOps = planFieldEventOperations({\n priorContract: options.fromContract,\n newContract: options.contract,\n codecHooks,\n });\n // Codec-emitted calls already conform to `OpFactoryCall` — render +\n // toOp + importRequirements ride directly through the same emit path\n // as structural ops, no `RawSqlCall` wrap.\n const calls = [...result.value.calls, ...fieldEventOps];\n\n const destination: SqliteMigrationDestinationInfo = {\n storageHash: options.contract.storage.storageHash,\n ...(options.contract.profileHash !== undefined\n ? { profileHash: options.contract.profileHash }\n : {}),\n };\n\n return {\n kind: 'success' as const,\n plan: new TypeScriptRenderableSqliteMigration(\n calls,\n {\n from: options.fromContract?.storage.storageHash ?? null,\n to: options.contract.storage.storageHash,\n },\n options.spaceId,\n destination,\n ),\n };\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy): SqlPlannerFailureResult | null {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n\n private collectSchemaIssues(options: SqlMigrationPlannerPlanOptions): readonly SchemaIssue[] {\n const allowed = options.policy.allowedOperationClasses;\n const strict = allowed.includes('widening') || allowed.includes('destructive');\n const verifyResult = verifySqlSchema({\n contract: options.contract,\n schema: options.schema,\n strict,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parseSqliteDefault,\n normalizeNativeType: normalizeSqliteNativeType,\n });\n return verifyResult.schema.issues;\n }\n}\n"],"mappings":";;;;;;;;;;;AA6DA,MAAM,uBAAuB,IAAI,IAAyB,CAAC,oBAAoB,kBAAkB,CAAC;AAElG,MAAM,0BAA0B,IAAI,IAAyB;CAC3D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAS,cAAc,OAAuD;CAC5E,IAAI,MAAM,SAAS,uBAAuB,OAAO;CACjD,IAAI,CAAC,MAAM,OAAO,OAAO;CACzB,IAAI,MAAM,SAAS,wBAEjB,OAAO,MAAM,aAAa,SAAS,aAAa;CAElD,IAAI,qBAAqB,IAAI,MAAM,KAAK,EAAE,OAAO;CACjD,IAAI,wBAAwB,IAAI,MAAM,KAAK,EAAE,OAAO;CACpD,OAAO;;;;;;;;AAST,MAAa,yBAAgD,QAAQ,QAAQ;CAC3E,MAAM,0BAAU,IAAI,KAAiE;CACrF,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;GACtB;GACA;GACA,QAAQ,QAAQ;GAChB,QAAQ,QAAQ;GAChB,qBAAqB,QAAQ;GAC7B,YAAY;GACb,CAAC;EAEF,IAAI,CAAC,OAAO,IACV,OAAO,eAAe,OAAO,QAAQ;EASvC,MAAM,gBAAgB,yBAAyB;GAC7C,eAAe,QAAQ;GACvB,aAAa,QAAQ;GACrB;GACD,CAAC;EAIF,MAAM,QAAQ,CAAC,GAAG,OAAO,MAAM,OAAO,GAAG,cAAc;EAEvD,MAAM,cAA8C;GAClD,aAAa,QAAQ,SAAS,QAAQ;GACtC,GAAI,QAAQ,SAAS,gBAAgB,KAAA,IACjC,EAAE,aAAa,QAAQ,SAAS,aAAa,GAC7C,EAAE;GACP;EAED,OAAO;GACL,MAAM;GACN,MAAM,IAAI,oCACR,OACA;IACE,MAAM,QAAQ,cAAc,QAAQ,eAAe;IACnD,IAAI,QAAQ,SAAS,QAAQ;IAC9B,EACD,QAAQ,SACR,YACD;GACF;;CAGH,qBAA6B,QAAkE;EAC7F,IAAI,CAAC,OAAO,wBAAwB,SAAS,WAAW,EACtD,OAAO,eAAe,CACpB;GACE,MAAM;GACN,SAAS;GACT,KAAK;GACN,CACF,CAAC;EAEJ,OAAO;;CAGT,oBAA4B,SAAiE;EAC3F,MAAM,UAAU,QAAQ,OAAO;EAC/B,MAAM,SAAS,QAAQ,SAAS,WAAW,IAAI,QAAQ,SAAS,cAAc;EAU9E,OATqB,gBAAgB;GACnC,UAAU,QAAQ;GAClB,QAAQ,QAAQ;GAChB;GACA,sCAAsB,IAAI,KAAK;GAC/B,qBAAqB,QAAQ;GAC7B,kBAAkB;GAClB,qBAAqB;GACtB,CACkB,CAAC,OAAO"}
package/dist/planner.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { n as createSqliteMigrationPlanner, t as SqliteMigrationPlanner } from "./planner-A7dqS0u6.mjs";
1
+ import { n as createSqliteMigrationPlanner, t as SqliteMigrationPlanner } from "./planner-CKzXAj4i.mjs";
2
2
  export { SqliteMigrationPlanner, createSqliteMigrationPlanner };
@@ -1,6 +1,7 @@
1
1
  import { n as stripOuterParens } from "./default-normalizer-3Fccw7yw.mjs";
2
2
  import { n as escapeLiteral, r as quoteIdentifier } from "./sql-utils-DhevMgef.mjs";
3
3
  import { t as buildTargetDetails } from "./planner-target-details-Bm71XPKb.mjs";
4
+ import { isPostgresEnumStorageEntry } from "@prisma-next/sql-contract/types";
4
5
  //#region src/core/migrations/operations/shared.ts
5
6
  function step(description, sql) {
6
7
  return {
@@ -83,6 +84,15 @@ function dropColumn(tableName, columnName) {
83
84
  }
84
85
  //#endregion
85
86
  //#region src/core/migrations/planner-ddl-builders.ts
87
+ /**
88
+ * Low-level DDL fragment builders for SQLite migrations.
89
+ *
90
+ * These helpers consume `StorageColumn` (the contract shape, possibly with
91
+ * `typeRef`) and produce string fragments. They are called once per column
92
+ * at the call-construction boundary in `issue-planner.ts` / strategies to
93
+ * build flat `SqliteColumnSpec`s; the operation factories themselves never
94
+ * see `StorageColumn` or `storageTypes`.
95
+ */
86
96
  const SAFE_NATIVE_TYPE_PATTERN = /^[a-zA-Z][a-zA-Z0-9_ ]*$/;
87
97
  function assertSafeNativeType(nativeType) {
88
98
  if (!SAFE_NATIVE_TYPE_PATTERN.test(nativeType)) throw new Error(`Unsafe native type name in contract: "${nativeType}". Native type names must match /^[a-zA-Z][a-zA-Z0-9_ ]*\$/`);
@@ -148,6 +158,11 @@ function resolveColumnTypeMetadata(column, storageTypes) {
148
158
  if (!column.typeRef) return column;
149
159
  const referencedType = storageTypes[column.typeRef];
150
160
  if (!referencedType) throw new Error(`Storage type "${column.typeRef}" referenced by column is not defined in storage.types.`);
161
+ if (isPostgresEnumStorageEntry(referencedType)) return {
162
+ codecId: referencedType.codecId,
163
+ nativeType: referencedType.nativeType,
164
+ typeParams: { values: referencedType.values }
165
+ };
151
166
  return {
152
167
  codecId: referencedType.codecId,
153
168
  nativeType: referencedType.nativeType,
@@ -400,4 +415,4 @@ function buildRecreatePostchecks(tableName, issues, spec) {
400
415
  //#endregion
401
416
  export { recreateTable as a, buildColumnDefaultSql as c, renderDefaultLiteral as d, addColumn as f, dropTable as i, buildColumnTypeSql as l, step as m, buildRecreateSummary as n, createIndex as o, dropColumn as p, createTable as r, dropIndex as s, buildRecreatePostchecks as t, isInlineAutoincrementPrimaryKey as u };
402
417
 
403
- //# sourceMappingURL=tables-D84zfPZI.mjs.map
418
+ //# sourceMappingURL=tables-DGRRJasz.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tables-DGRRJasz.mjs","names":[],"sources":["../src/core/migrations/operations/shared.ts","../src/core/migrations/operations/columns.ts","../src/core/migrations/planner-ddl-builders.ts","../src/core/migrations/operations/indexes.ts","../src/core/migrations/operations/tables.ts"],"sourcesContent":["import type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { ReferentialAction } from '@prisma-next/sql-contract/types';\nimport { quoteIdentifier } from '../../sql-utils';\nimport type { SqlitePlanTargetDetails } from '../planner-target-details';\n\nexport type Op = SqlMigrationPlanOperation<SqlitePlanTargetDetails>;\n\nexport function step(description: string, sql: string): { description: string; sql: string } {\n return { description, sql };\n}\n\n/**\n * Flat, fully-resolved column shape consumed by `createTable`, `addColumn`,\n * and `recreateTable`. Codec / `typeRef` / default expansion happens at the\n * call-construction site (in the issue-planner / strategies) so the\n * operation factories deal only in pre-rendered SQL fragments — mirrors the\n * Postgres `ColumnSpec` pattern.\n *\n * - `typeSql` is the column's DDL type token (e.g. `\"INTEGER\"`, `\"TEXT\"`).\n * - `defaultSql` is the full `DEFAULT …` clause (or empty when there is no\n * default and when the column is rendered as `INTEGER PRIMARY KEY\n * AUTOINCREMENT`, since SQLite forbids a default on an autoincrement PK).\n * - `inlineAutoincrementPrimaryKey` directs the renderer to emit\n * `INTEGER PRIMARY KEY AUTOINCREMENT` inline and to skip the table-level\n * primary-key constraint for this column. SQLite-specific: the column\n * becomes an alias for `rowid` only when this exact form is used.\n */\nexport interface SqliteColumnSpec {\n readonly name: string;\n readonly typeSql: string;\n readonly defaultSql: string;\n readonly nullable: boolean;\n readonly inlineAutoincrementPrimaryKey?: boolean;\n}\n\nexport interface SqlitePrimaryKeySpec {\n readonly columns: readonly string[];\n}\n\nexport interface SqliteUniqueSpec {\n readonly columns: readonly string[];\n readonly name?: string;\n}\n\nexport interface SqliteForeignKeySpec {\n readonly columns: readonly string[];\n readonly references: {\n readonly table: string;\n readonly columns: readonly string[];\n };\n readonly name?: string;\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n readonly constraint: boolean;\n}\n\n/**\n * Flat shape of a contract table for DDL emission. Used by both\n * `createTable` (additive) and `recreateTable` (widening/destructive).\n */\nexport interface SqliteTableSpec {\n readonly columns: readonly SqliteColumnSpec[];\n readonly primaryKey?: SqlitePrimaryKeySpec;\n readonly uniques?: readonly SqliteUniqueSpec[];\n readonly foreignKeys?: readonly SqliteForeignKeySpec[];\n}\n\n/**\n * Index recreation spec for `recreateTable`. Both declared indexes and\n * FK-backing indexes flatten to the same shape; the planner dedupes by\n * column-set before constructing the call.\n */\nexport interface SqliteIndexSpec {\n readonly name: string;\n readonly columns: readonly string[];\n}\n\nconst REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string> = {\n noAction: 'NO ACTION',\n restrict: 'RESTRICT',\n cascade: 'CASCADE',\n setNull: 'SET NULL',\n setDefault: 'SET DEFAULT',\n};\n\n/**\n * Renders a single column's inline DDL fragment within a `CREATE TABLE`\n * statement. Honours the `inlineAutoincrementPrimaryKey` flag — SQLite\n * treats `INTEGER PRIMARY KEY AUTOINCREMENT` as a special form that aliases\n * `rowid`, and the column must not carry a `DEFAULT` or repeat `NOT NULL`.\n */\nexport function renderColumnDefinition(column: SqliteColumnSpec): string {\n const parts: string[] = [quoteIdentifier(column.name), column.typeSql];\n if (column.inlineAutoincrementPrimaryKey) {\n parts.push('PRIMARY KEY AUTOINCREMENT');\n } else {\n if (column.defaultSql) parts.push(column.defaultSql);\n if (!column.nullable) parts.push('NOT NULL');\n }\n return parts.join(' ');\n}\n\n/**\n * Renders an inline FOREIGN KEY constraint clause for a `CREATE TABLE`\n * body. Returns the empty string when `constraint` is false (the FK is\n * tracked at the contract level for index-creation purposes only and must\n * not produce DDL).\n */\nexport function renderForeignKeyClause(fk: SqliteForeignKeySpec): string {\n if (!fk.constraint) return '';\n const name = fk.name ? `CONSTRAINT ${quoteIdentifier(fk.name)} ` : '';\n let sql = `${name}FOREIGN KEY (${fk.columns.map(quoteIdentifier).join(', ')}) REFERENCES ${quoteIdentifier(fk.references.table)} (${fk.references.columns.map(quoteIdentifier).join(', ')})`;\n if (fk.onDelete !== undefined) {\n sql += ` ON DELETE ${REFERENTIAL_ACTION_SQL[fk.onDelete]}`;\n }\n if (fk.onUpdate !== undefined) {\n sql += ` ON UPDATE ${REFERENTIAL_ACTION_SQL[fk.onUpdate]}`;\n }\n return sql;\n}\n","import { escapeLiteral, quoteIdentifier } from '../../sql-utils';\nimport { buildTargetDetails } from '../planner-target-details';\nimport { type Op, type SqliteColumnSpec, step } from './shared';\n\nexport function addColumn(tableName: string, column: SqliteColumnSpec): Op {\n const parts = [\n `ALTER TABLE ${quoteIdentifier(tableName)}`,\n `ADD COLUMN ${quoteIdentifier(column.name)} ${column.typeSql}`,\n column.defaultSql,\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n const addSql = parts.join(' ');\n\n return {\n id: `column.${tableName}.${column.name}`,\n label: `Add column ${column.name} on ${tableName}`,\n summary: `Adds column ${column.name} on ${tableName}`,\n operationClass: 'additive',\n target: { id: 'sqlite', details: buildTargetDetails('column', column.name, tableName) },\n precheck: [\n step(\n `ensure column \"${column.name}\" is missing`,\n `SELECT COUNT(*) = 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(column.name)}'`,\n ),\n ],\n execute: [step(`add column \"${column.name}\"`, addSql)],\n postcheck: [\n step(\n `verify column \"${column.name}\" exists`,\n `SELECT COUNT(*) > 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(column.name)}'`,\n ),\n ],\n };\n}\n\nexport function dropColumn(tableName: string, columnName: string): Op {\n return {\n id: `dropColumn.${tableName}.${columnName}`,\n label: `Drop column ${columnName} on ${tableName}`,\n summary: `Drops column ${columnName} on ${tableName} which is not in the contract`,\n operationClass: 'destructive',\n target: { id: 'sqlite', details: buildTargetDetails('column', columnName, tableName) },\n precheck: [\n step(\n `ensure column \"${columnName}\" exists on \"${tableName}\"`,\n `SELECT COUNT(*) > 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(columnName)}'`,\n ),\n ],\n execute: [\n step(\n `drop column \"${columnName}\" from \"${tableName}\"`,\n `ALTER TABLE ${quoteIdentifier(tableName)} DROP COLUMN ${quoteIdentifier(columnName)}`,\n ),\n ],\n postcheck: [\n step(\n `verify column \"${columnName}\" is gone from \"${tableName}\"`,\n `SELECT COUNT(*) = 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(columnName)}'`,\n ),\n ],\n };\n}\n","/**\n * Low-level DDL fragment builders for SQLite migrations.\n *\n * These helpers consume `StorageColumn` (the contract shape, possibly with\n * `typeRef`) and produce string fragments. They are called once per column\n * at the call-construction boundary in `issue-planner.ts` / strategies to\n * build flat `SqliteColumnSpec`s; the operation factories themselves never\n * see `StorageColumn` or `storageTypes`.\n */\n\nimport {\n isPostgresEnumStorageEntry,\n type PostgresEnumStorageEntry,\n type StorageColumn,\n type StorageTable,\n type StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { escapeLiteral, quoteIdentifier } from '../sql-utils';\n\ntype SqliteColumnDefault = StorageColumn['default'];\n\nconst SAFE_NATIVE_TYPE_PATTERN = /^[a-zA-Z][a-zA-Z0-9_ ]*$/;\n\nfunction assertSafeNativeType(nativeType: string): void {\n if (!SAFE_NATIVE_TYPE_PATTERN.test(nativeType)) {\n throw new Error(\n `Unsafe native type name in contract: \"${nativeType}\". ` +\n 'Native type names must match /^[a-zA-Z][a-zA-Z0-9_ ]*$/',\n );\n }\n}\n\nfunction assertSafeDefaultExpression(expression: string): void {\n if (expression.includes(';') || /--|\\/\\*|\\bSELECT\\b/i.test(expression)) {\n throw new Error(\n `Unsafe default expression in contract: \"${expression}\". ` +\n 'Default expressions must not contain semicolons, SQL comment tokens, or subqueries.',\n );\n }\n}\n\n/**\n * Renders the column's DDL type token (e.g. `\"INTEGER\"`, `\"TEXT\"`).\n * Resolves `typeRef` against `storageTypes` and validates the resulting\n * native type against a safe-identifier pattern.\n */\nexport function buildColumnTypeSql(\n column: StorageColumn,\n storageTypes: Record<string, StorageTypeInstance | PostgresEnumStorageEntry> = {},\n): string {\n const resolved = resolveColumnTypeMetadata(column, storageTypes);\n assertSafeNativeType(resolved.nativeType);\n return resolved.nativeType.toUpperCase();\n}\n\n/**\n * Renders the column's `DEFAULT …` clause. Returns the empty string when\n * there is no default, and also when the default is `autoincrement()` —\n * SQLite encodes that as `INTEGER PRIMARY KEY AUTOINCREMENT` inline on the\n * column definition, not as a separate DEFAULT.\n */\nexport function buildColumnDefaultSql(columnDefault: SqliteColumnDefault | undefined): string {\n if (!columnDefault) return '';\n\n switch (columnDefault.kind) {\n case 'literal':\n return `DEFAULT ${renderDefaultLiteral(columnDefault.value)}`;\n case 'function': {\n if (columnDefault.expression === 'autoincrement()') return '';\n if (columnDefault.expression === 'now()') return \"DEFAULT (datetime('now'))\";\n assertSafeDefaultExpression(columnDefault.expression);\n return `DEFAULT (${columnDefault.expression})`;\n }\n }\n}\n\nexport function renderDefaultLiteral(value: unknown): string {\n if (value instanceof Date) {\n return `'${escapeLiteral(value.toISOString())}'`;\n }\n if (typeof value === 'string') {\n return `'${escapeLiteral(value)}'`;\n }\n if (typeof value === 'number' || typeof value === 'bigint') {\n return String(value);\n }\n if (typeof value === 'boolean') {\n return value ? '1' : '0';\n }\n if (value === null) {\n return 'NULL';\n }\n return `'${escapeLiteral(JSON.stringify(value))}'`;\n}\n\nexport function buildCreateIndexSql(\n tableName: string,\n indexName: string,\n columns: readonly string[],\n unique = false,\n): string {\n const uniqueKeyword = unique ? 'UNIQUE ' : '';\n return `CREATE ${uniqueKeyword}INDEX ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)} (${columns.map(quoteIdentifier).join(', ')})`;\n}\n\nexport function buildDropIndexSql(indexName: string): string {\n return `DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`;\n}\n\n/**\n * True when the column is rendered inline as `INTEGER PRIMARY KEY\n * AUTOINCREMENT`. Requires the column's default to be `autoincrement()` and\n * the column to be the sole member of the table's primary key — anything\n * else falls back to a separate PRIMARY KEY constraint with a default\n * AUTOINCREMENT semantics expressed elsewhere.\n */\nexport function isInlineAutoincrementPrimaryKey(table: StorageTable, columnName: string): boolean {\n if (table.primaryKey?.columns.length !== 1) return false;\n if (table.primaryKey.columns[0] !== columnName) return false;\n const column = table.columns[columnName];\n return column?.default?.kind === 'function' && column.default.expression === 'autoincrement()';\n}\n\ntype ResolvedColumnTypeMetadata = Pick<StorageColumn, 'nativeType' | 'codecId' | 'typeParams'>;\n\nfunction resolveColumnTypeMetadata(\n column: StorageColumn,\n storageTypes: Record<string, StorageTypeInstance | PostgresEnumStorageEntry>,\n): ResolvedColumnTypeMetadata {\n if (!column.typeRef) {\n return column;\n }\n const referencedType = storageTypes[column.typeRef];\n if (!referencedType) {\n throw new Error(\n `Storage type \"${column.typeRef}\" referenced by column is not defined in storage.types.`,\n );\n }\n if (isPostgresEnumStorageEntry(referencedType)) {\n return {\n codecId: referencedType.codecId,\n nativeType: referencedType.nativeType,\n typeParams: { values: referencedType.values } as Record<string, unknown>,\n };\n }\n return {\n codecId: referencedType.codecId,\n nativeType: referencedType.nativeType,\n typeParams: referencedType.typeParams,\n };\n}\n","import { escapeLiteral } from '../../sql-utils';\nimport { buildCreateIndexSql, buildDropIndexSql } from '../planner-ddl-builders';\nimport { buildTargetDetails } from '../planner-target-details';\nimport { type Op, step } from './shared';\n\nexport function createIndex(tableName: string, indexName: string, columns: readonly string[]): Op {\n return {\n id: `index.${tableName}.${indexName}`,\n label: `Create index ${indexName} on ${tableName}`,\n summary: `Creates index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: { id: 'sqlite', details: buildTargetDetails('index', indexName, tableName) },\n precheck: [\n step(\n `ensure index \"${indexName}\" is missing`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n execute: [\n step(`create index \"${indexName}\"`, buildCreateIndexSql(tableName, indexName, columns)),\n ],\n postcheck: [\n step(\n `verify index \"${indexName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n };\n}\n\nexport function dropIndex(tableName: string, indexName: string): Op {\n return {\n id: `dropIndex.${tableName}.${indexName}`,\n label: `Drop index ${indexName} on ${tableName}`,\n summary: `Drops index ${indexName} on ${tableName} which is not in the contract`,\n operationClass: 'destructive',\n target: { id: 'sqlite', details: buildTargetDetails('index', indexName, tableName) },\n precheck: [\n step(\n `ensure index \"${indexName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n execute: [step(`drop index \"${indexName}\"`, buildDropIndexSql(indexName))],\n postcheck: [\n step(\n `verify index \"${indexName}\" is gone`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n };\n}\n","import type { MigrationOperationClass } from '@prisma-next/family-sql/control';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport { stripOuterParens } from '../../default-normalizer';\nimport { escapeLiteral, quoteIdentifier } from '../../sql-utils';\nimport { buildCreateIndexSql } from '../planner-ddl-builders';\nimport { buildTargetDetails } from '../planner-target-details';\nimport {\n type Op,\n renderColumnDefinition,\n renderForeignKeyClause,\n type SqliteIndexSpec,\n type SqliteTableSpec,\n step,\n} from './shared';\n\n/**\n * Renders the body of a `CREATE TABLE <name> ( … )` statement from a flat\n * `SqliteTableSpec`. SQLite's `INTEGER PRIMARY KEY AUTOINCREMENT` form is\n * inline on the column; the table-level PRIMARY KEY clause is emitted only\n * when no column carries `inlineAutoincrementPrimaryKey`.\n */\nfunction renderCreateTableSql(tableName: string, spec: SqliteTableSpec): string {\n const columnDefs = spec.columns.map(renderColumnDefinition);\n\n const constraintDefs: string[] = [];\n const hasInlinePk = spec.columns.some((c) => c.inlineAutoincrementPrimaryKey);\n if (spec.primaryKey && !hasInlinePk) {\n constraintDefs.push(`PRIMARY KEY (${spec.primaryKey.columns.map(quoteIdentifier).join(', ')})`);\n }\n\n for (const u of spec.uniques ?? []) {\n const name = u.name ? `CONSTRAINT ${quoteIdentifier(u.name)} ` : '';\n constraintDefs.push(`${name}UNIQUE (${u.columns.map(quoteIdentifier).join(', ')})`);\n }\n\n for (const fk of spec.foreignKeys ?? []) {\n const clause = renderForeignKeyClause(fk);\n if (clause) constraintDefs.push(clause);\n }\n\n const allDefs = [...columnDefs, ...constraintDefs];\n return `CREATE TABLE ${quoteIdentifier(tableName)} (\\n ${allDefs.join(',\\n ')}\\n)`;\n}\n\nexport function createTable(tableName: string, spec: SqliteTableSpec): Op {\n return {\n id: `table.${tableName}`,\n label: `Create table ${tableName}`,\n summary: `Creates table ${tableName} with required columns`,\n operationClass: 'additive',\n target: { id: 'sqlite', details: buildTargetDetails('table', tableName) },\n precheck: [\n step(\n `ensure table \"${tableName}\" does not exist`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n execute: [step(`create table \"${tableName}\"`, renderCreateTableSql(tableName, spec))],\n postcheck: [\n step(\n `verify table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n };\n}\n\nexport function dropTable(tableName: string): Op {\n return {\n id: `dropTable.${tableName}`,\n label: `Drop table ${tableName}`,\n summary: `Drops table ${tableName} which is not in the contract`,\n operationClass: 'destructive',\n target: { id: 'sqlite', details: buildTargetDetails('table', tableName) },\n precheck: [\n step(\n `ensure table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n execute: [step(`drop table \"${tableName}\"`, `DROP TABLE ${quoteIdentifier(tableName)}`)],\n postcheck: [\n step(\n `verify table \"${tableName}\" is gone`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n };\n}\n\nexport interface RecreateTableArgs {\n readonly tableName: string;\n /** New (post-recreate) shape of the table. Same flat spec as `createTable`. */\n readonly contractTable: SqliteTableSpec;\n /**\n * Names of columns that exist in the live (pre-recreate) schema. Used to\n * compute the `INSERT INTO temp ... SELECT ... FROM old` column list — only\n * shared columns are copied, so dropped columns are left behind and added\n * columns come from defaults.\n */\n readonly schemaColumnNames: readonly string[];\n /**\n * Indexes (declared + FK-backing, deduped by column-set) to recreate after\n * the table has been replaced. The planner pre-merges these.\n */\n readonly indexes: readonly SqliteIndexSpec[];\n /** Human-readable summary of the change, built by the planner from issues. */\n readonly summary: string;\n /**\n * Per-issue postcheck steps appended after the structural postchecks. The\n * planner pre-builds these via `buildRecreatePostchecks` so the call IR\n * carries flat, serializable data only — no `SchemaIssue` references.\n */\n readonly postchecks: readonly { readonly description: string; readonly sql: string }[];\n readonly operationClass: MigrationOperationClass;\n}\n\nexport function recreateTable(args: RecreateTableArgs): Op {\n const {\n tableName,\n contractTable,\n schemaColumnNames,\n indexes,\n summary,\n postchecks,\n operationClass,\n } = args;\n const tempName = `_prisma_new_${tableName}`;\n const liveSet = new Set(schemaColumnNames);\n const sharedColumns = contractTable.columns.filter((c) => liveSet.has(c.name)).map((c) => c.name);\n const columnList = sharedColumns.map(quoteIdentifier).join(', ');\n\n const indexStatements = indexes.map((idx) => ({\n description: `recreate index \"${idx.name}\" on \"${tableName}\"`,\n sql: buildCreateIndexSql(tableName, idx.name, idx.columns),\n }));\n\n // If the contract retains no columns from the live table, an `INSERT INTO\n // tmp () SELECT FROM old` is invalid SQL — and would also be a no-op since\n // there's nothing to copy. Skip the copy step in that case; the new\n // (empty) table replaces the old one directly.\n const copyStep =\n sharedColumns.length > 0\n ? [\n step(\n `copy data from \"${tableName}\" to \"${tempName}\"`,\n `INSERT INTO ${quoteIdentifier(tempName)} (${columnList}) SELECT ${columnList} FROM ${quoteIdentifier(tableName)}`,\n ),\n ]\n : [];\n\n return {\n id: `recreateTable.${tableName}`,\n label: `Recreate table ${tableName}`,\n summary,\n operationClass,\n target: { id: 'sqlite', details: buildTargetDetails('table', tableName) },\n precheck: [\n step(\n `ensure table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n step(\n `ensure temp table \"${tempName}\" does not exist`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tempName)}'`,\n ),\n ],\n execute: [\n step(\n `create new table \"${tempName}\" with desired schema`,\n renderCreateTableSql(tempName, contractTable),\n ),\n ...copyStep,\n step(`drop old table \"${tableName}\"`, `DROP TABLE ${quoteIdentifier(tableName)}`),\n step(\n `rename \"${tempName}\" to \"${tableName}\"`,\n `ALTER TABLE ${quoteIdentifier(tempName)} RENAME TO ${quoteIdentifier(tableName)}`,\n ),\n ...indexStatements,\n ],\n postcheck: [\n step(\n `verify table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n step(\n `verify temp table \"${tempName}\" is gone`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tempName)}'`,\n ),\n ...postchecks,\n ],\n };\n}\n\n/**\n * Build a one-line summary of a recreate-table operation from the schema\n * issues that triggered it. Lives next to `recreateTable` so the planner\n * (which has the issues) can produce the same description the factory\n * used to build inline. Keeping the formatting target-side keeps\n * `RecreateTableCall` issue-free at the IR layer.\n */\nexport function buildRecreateSummary(tableName: string, issues: readonly SchemaIssue[]): string {\n const messages = issues.map((i) => i.message).join('; ');\n return `Recreates table ${tableName} to apply schema changes: ${messages}`;\n}\n\nconst COLUMN_LEVEL_ISSUE_KINDS = new Set<SchemaIssue['kind']>([\n 'nullability_mismatch',\n 'default_mismatch',\n 'default_missing',\n 'extra_default',\n 'type_mismatch',\n]);\n\nconst PK_ISSUE_KINDS = new Set<SchemaIssue['kind']>(['primary_key_mismatch', 'extra_primary_key']);\n\nconst UNIQUE_ISSUE_KINDS = new Set<SchemaIssue['kind']>([\n 'unique_constraint_mismatch',\n 'extra_unique_constraint',\n]);\n\nconst FK_ISSUE_KINDS = new Set<SchemaIssue['kind']>(['foreign_key_mismatch', 'extra_foreign_key']);\n\n/**\n * Returns the columns the contract expects as the table's primary key. Picks\n * up SQLite's inline `INTEGER PRIMARY KEY AUTOINCREMENT` form when no\n * explicit `primaryKey` clause is set on the spec.\n */\nfunction expectedPrimaryKeyColumns(spec: SqliteTableSpec): readonly string[] {\n if (spec.primaryKey) return spec.primaryKey.columns;\n const inlinePk = spec.columns.find((c) => c.inlineAutoincrementPrimaryKey);\n return inlinePk ? [inlinePk.name] : [];\n}\n\nfunction quoteSqlList(values: readonly string[]): string {\n return values.map((v) => `'${escapeLiteral(v)}'`).join(', ');\n}\n\n/**\n * Per-issue postchecks verifying the recreated table's shape against the\n * contract spec. Column-level issues (`nullability_mismatch`,\n * `default_mismatch`, …) emit one targeted check each; constraint-level\n * issues (`primary_key_mismatch`, `unique_constraint_mismatch`,\n * `foreign_key_mismatch`, plus their `extra_*` siblings) emit one\n * `pragma_*`-driven check per declared constraint in the contract spec, so\n * a recreated table with the right columns but the wrong PK / unique / FK\n * shape fails the postcheck instead of passing silently. Exported so the\n * planner can pre-build the list at construction time and\n * `RecreateTableCall` doesn't have to carry `SchemaIssue` objects through\n * to render time.\n */\nexport function buildRecreatePostchecks(\n tableName: string,\n issues: readonly SchemaIssue[],\n spec: SqliteTableSpec,\n): Array<{ description: string; sql: string }> {\n const checks: Array<{ description: string; sql: string }> = [];\n const t = escapeLiteral(tableName);\n const byName = new Map(spec.columns.map((c) => [c.name, c]));\n\n for (const issue of issues) {\n if (issue.kind === 'enum_values_changed') continue;\n if (!COLUMN_LEVEL_ISSUE_KINDS.has(issue.kind)) continue;\n if (!issue.column) continue;\n const c = escapeLiteral(issue.column);\n if (issue.kind === 'nullability_mismatch') {\n // `expected` carries the contract's nullable flag as a string. We only\n // emit a postcheck when the value is recognized — anything else\n // (case-folded, numeric coding, etc.) is left to the structural\n // verifier so a typo here can't silently invert the meaning.\n let wantNotNull: boolean | undefined;\n if (issue.expected === 'false') wantNotNull = true;\n else if (issue.expected === 'true') wantNotNull = false;\n if (wantNotNull !== undefined) {\n checks.push({\n description: `verify \"${issue.column}\" nullability on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND \"notnull\" = ${wantNotNull ? 1 : 0}`,\n });\n }\n }\n if (issue.kind === 'default_mismatch' || issue.kind === 'default_missing') {\n const colSpec = byName.get(issue.column);\n const expectedRaw = colSpec?.defaultSql.startsWith('DEFAULT ')\n ? // SQLite's pragma_table_info.dflt_value strips outer parens for\n // expression defaults (per the SQLite docs), so `(datetime('now'))`\n // is stored as `datetime('now')`. Strip them here so the postcheck\n // matches.\n stripOuterParens(colSpec.defaultSql.slice('DEFAULT '.length))\n : null;\n if (expectedRaw) {\n checks.push({\n description: `verify \"${issue.column}\" default on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND dflt_value = '${escapeLiteral(expectedRaw)}'`,\n });\n }\n }\n if (issue.kind === 'type_mismatch') {\n const colSpec = byName.get(issue.column);\n if (colSpec) {\n checks.push({\n description: `verify \"${issue.column}\" type on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND LOWER(type) = '${escapeLiteral(colSpec.typeSql.toLowerCase())}'`,\n });\n }\n }\n if (issue.kind === 'extra_default') {\n checks.push({\n description: `verify \"${issue.column}\" has no default on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND dflt_value IS NULL`,\n });\n }\n }\n\n // Constraint-level issues — emit one postcheck per declared constraint in\n // the contract spec when *any* issue of that kind fires, since recreate\n // rebuilds the entire table at once.\n const hasPkIssue = issues.some((i) => PK_ISSUE_KINDS.has(i.kind));\n const hasUniqueIssue = issues.some((i) => UNIQUE_ISSUE_KINDS.has(i.kind));\n const hasFkIssue = issues.some((i) => FK_ISSUE_KINDS.has(i.kind));\n\n if (hasPkIssue) {\n const pkColumns = expectedPrimaryKeyColumns(spec);\n // Verify pragma_table_info reports exactly these columns as PK members\n // (count + named membership); zero columns expected ⇒ no PK at all.\n const colCount = pkColumns.length;\n if (colCount === 0) {\n checks.push({\n description: `verify \"${tableName}\" has no primary key`,\n sql: `SELECT (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0) = 0`,\n });\n } else {\n checks.push({\n description: `verify primary key on \"${tableName}\"`,\n sql:\n `SELECT (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0) = ${colCount}` +\n ` AND (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0 AND name IN (${quoteSqlList(pkColumns)})) = ${colCount}`,\n });\n }\n }\n\n if (hasUniqueIssue) {\n for (const u of spec.uniques ?? []) {\n const colCount = u.columns.length;\n const description = u.name\n ? `verify unique constraint \"${u.name}\" on \"${tableName}\"`\n : `verify unique constraint (${u.columns.join(', ')}) on \"${tableName}\"`;\n // Match any unique index whose covered columns are exactly the expected\n // set. Order is intentionally not checked — SQLite's unique-index\n // identity is column-set, not column-sequence.\n checks.push({\n description,\n sql:\n `SELECT EXISTS (SELECT 1 FROM pragma_index_list('${t}') l` +\n ` WHERE l.\"unique\" = 1` +\n ` AND (SELECT COUNT(*) FROM pragma_index_info(l.name)) = ${colCount}` +\n ` AND (SELECT COUNT(*) FROM pragma_index_info(l.name) WHERE name IN (${quoteSqlList(u.columns)})) = ${colCount})`,\n });\n }\n }\n\n if (hasFkIssue) {\n for (const fk of spec.foreignKeys ?? []) {\n const refTable = escapeLiteral(fk.references.table);\n const colCount = fk.columns.length;\n // Build a `SUM(CASE WHEN (\"from\",\"to\") IN ((…)) …)` so the check works\n // for both single- and multi-column FKs without depending on FK row\n // ordering inside `pragma_foreign_key_list`.\n const tuples = fk.columns\n .map((from, i) => {\n const to = fk.references.columns[i] ?? from;\n return `('${escapeLiteral(from)}', '${escapeLiteral(to)}')`;\n })\n .join(', ');\n const description = `verify foreign key (${fk.columns.join(', ')}) → ${fk.references.table}(${fk.references.columns.join(', ')}) on \"${tableName}\"`;\n checks.push({\n description,\n sql:\n `SELECT EXISTS (SELECT 1 FROM pragma_foreign_key_list('${t}') f` +\n ` WHERE f.\"table\" = '${refTable}'` +\n ' GROUP BY f.id' +\n ` HAVING COUNT(*) = ${colCount}` +\n ` AND SUM(CASE WHEN (f.\"from\", f.\"to\") IN (${tuples}) THEN 1 ELSE 0 END) = ${colCount})`,\n });\n }\n }\n\n return checks;\n}\n"],"mappings":";;;;;AAOA,SAAgB,KAAK,aAAqB,KAAmD;CAC3F,OAAO;EAAE;EAAa;EAAK;;AAqE7B,MAAM,yBAA4D;CAChE,UAAU;CACV,UAAU;CACV,SAAS;CACT,SAAS;CACT,YAAY;CACb;;;;;;;AAQD,SAAgB,uBAAuB,QAAkC;CACvE,MAAM,QAAkB,CAAC,gBAAgB,OAAO,KAAK,EAAE,OAAO,QAAQ;CACtE,IAAI,OAAO,+BACT,MAAM,KAAK,4BAA4B;MAClC;EACL,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AO,KAAK;GACV;GACA,KACE,yDAAyD,EAAE,0BACpC,SAAS,oCAEV,SAAA,4CACuB,OAAO,yBAAyB,SAAS;GACzF,CAAC;;CAIN,OAAO"}
package/package.json CHANGED
@@ -1,30 +1,30 @@
1
1
  {
2
2
  "name": "@prisma-next/target-sqlite",
3
- "version": "0.8.0",
3
+ "version": "0.9.0-dev.1",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "dependencies": {
8
- "@prisma-next/cli": "0.8.0",
9
- "@prisma-next/contract": "0.8.0",
10
- "@prisma-next/errors": "0.8.0",
11
- "@prisma-next/family-sql": "0.8.0",
12
- "@prisma-next/framework-components": "0.8.0",
13
- "@prisma-next/migration-tools": "0.8.0",
14
- "@prisma-next/sql-contract": "0.8.0",
15
- "@prisma-next/sql-errors": "0.8.0",
16
- "@prisma-next/sql-relational-core": "0.8.0",
17
- "@prisma-next/sql-runtime": "0.8.0",
18
- "@prisma-next/sql-schema-ir": "0.8.0",
19
- "@prisma-next/ts-render": "0.8.0",
20
- "@prisma-next/utils": "0.8.0",
8
+ "@prisma-next/cli": "0.9.0-dev.1",
9
+ "@prisma-next/contract": "0.9.0-dev.1",
10
+ "@prisma-next/errors": "0.9.0-dev.1",
11
+ "@prisma-next/family-sql": "0.9.0-dev.1",
12
+ "@prisma-next/framework-components": "0.9.0-dev.1",
13
+ "@prisma-next/migration-tools": "0.9.0-dev.1",
14
+ "@prisma-next/sql-contract": "0.9.0-dev.1",
15
+ "@prisma-next/sql-errors": "0.9.0-dev.1",
16
+ "@prisma-next/sql-relational-core": "0.9.0-dev.1",
17
+ "@prisma-next/sql-runtime": "0.9.0-dev.1",
18
+ "@prisma-next/sql-schema-ir": "0.9.0-dev.1",
19
+ "@prisma-next/ts-render": "0.9.0-dev.1",
20
+ "@prisma-next/utils": "0.9.0-dev.1",
21
21
  "@standard-schema/spec": "1.1.0"
22
22
  },
23
23
  "devDependencies": {
24
- "@prisma-next/driver-sqlite": "0.8.0",
25
- "@prisma-next/test-utils": "0.8.0",
26
- "@prisma-next/tsconfig": "0.8.0",
27
- "@prisma-next/tsdown": "0.8.0",
24
+ "@prisma-next/driver-sqlite": "0.9.0-dev.1",
25
+ "@prisma-next/test-utils": "0.9.0-dev.1",
26
+ "@prisma-next/tsconfig": "0.9.0-dev.1",
27
+ "@prisma-next/tsdown": "0.9.0-dev.1",
28
28
  "tsdown": "0.22.0",
29
29
  "typescript": "5.9.3",
30
30
  "vitest": "4.1.5"
@@ -9,12 +9,18 @@ import type {
9
9
  MigrationPlanner,
10
10
  MigrationRunner,
11
11
  } from '@prisma-next/framework-components/control';
12
- import type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';
12
+ import { SqlStorage, type StorageColumn } from '@prisma-next/sql-contract/types';
13
13
  import { sqliteTargetDescriptorMeta } from './descriptor-meta';
14
14
  import { createSqliteMigrationPlanner } from './migrations/planner';
15
15
  import { renderDefaultLiteral } from './migrations/planner-ddl-builders';
16
16
  import type { SqlitePlanTargetDetails } from './migrations/planner-target-details';
17
17
  import { createSqliteMigrationRunner } from './migrations/runner';
18
+ import { SqliteContractSerializer } from './sqlite-contract-serializer';
19
+ import { SqliteSchemaVerifier } from './sqlite-schema-verifier';
20
+
21
+ function isSqlContract(contract: Contract | null): contract is Contract<SqlStorage> | null {
22
+ return contract === null || contract.storage instanceof SqlStorage;
23
+ }
18
24
 
19
25
  function sqliteRenderDefault(def: ColumnDefault, _column: StorageColumn): string {
20
26
  if (def.kind === 'function') {
@@ -29,6 +35,8 @@ function sqliteRenderDefault(def: ColumnDefault, _column: StorageColumn): string
29
35
  const sqliteControlTargetDescriptor: SqlControlTargetDescriptor<'sqlite', SqlitePlanTargetDetails> =
30
36
  {
31
37
  ...sqliteTargetDescriptorMeta,
38
+ contractSerializer: new SqliteContractSerializer(),
39
+ schemaVerifier: new SqliteSchemaVerifier(),
32
40
  migrations: {
33
41
  createPlanner(_family: SqlControlFamilyInstance): MigrationPlanner<'sql', 'sqlite'> {
34
42
  return createSqliteMigrationPlanner();
@@ -37,7 +45,19 @@ const sqliteControlTargetDescriptor: SqlControlTargetDescriptor<'sqlite', Sqlite
37
45
  return createSqliteMigrationRunner(family) as MigrationRunner<'sql', 'sqlite'>;
38
46
  },
39
47
  contractToSchema(contract, _frameworkComponents) {
40
- return contractToSchemaIR(contract as Contract<SqlStorage> | null, {
48
+ // The framework SPI types `contract` as the generic
49
+ // `Contract | null`. Any contract reaching the sqlite
50
+ // target descriptor is SQL-family by construction (the
51
+ // family contract resolver would have refused to bind a
52
+ // sqlite target otherwise); the `isSqlContract` predicate
53
+ // encodes that invariant at runtime + narrows the generic
54
+ // to `Contract<SqlStorage>` without a blind cast.
55
+ if (!isSqlContract(contract)) {
56
+ throw new Error(
57
+ 'sqliteControlTargetDescriptor.contractToSchema received a non-SQL contract; expected Contract<SqlStorage>',
58
+ );
59
+ }
60
+ return contractToSchemaIR(contract, {
41
61
  annotationNamespace: 'sqlite',
42
62
  renderDefault: sqliteRenderDefault,
43
63
  });
@@ -18,6 +18,7 @@ import type {
18
18
  import type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';
19
19
  import type { SchemaIssue } from '@prisma-next/framework-components/control';
20
20
  import type {
21
+ PostgresEnumStorageEntry,
21
22
  SqlStorage,
22
23
  StorageColumn,
23
24
  StorageTable,
@@ -203,10 +204,13 @@ function isMissing(issue: SchemaIssue): boolean {
203
204
  export function toColumnSpec(
204
205
  name: string,
205
206
  column: StorageColumn,
206
- storageTypes: Readonly<Record<string, StorageTypeInstance>>,
207
+ storageTypes: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>,
207
208
  inlineAutoincrementPrimaryKey = false,
208
209
  ): SqliteColumnSpec {
209
- const typeSql = buildColumnTypeSql(column, storageTypes as Record<string, StorageTypeInstance>);
210
+ const typeSql = buildColumnTypeSql(
211
+ column,
212
+ storageTypes as Record<string, StorageTypeInstance | PostgresEnumStorageEntry>,
213
+ );
210
214
  const defaultSql = buildColumnDefaultSql(column.default);
211
215
  return {
212
216
  name,
@@ -225,7 +229,7 @@ export function toColumnSpec(
225
229
  */
226
230
  export function toTableSpec(
227
231
  table: StorageTable,
228
- storageTypes: Readonly<Record<string, StorageTypeInstance>>,
232
+ storageTypes: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>,
229
233
  ): SqliteTableSpec {
230
234
  const columns: SqliteColumnSpec[] = Object.entries(table.columns).map(([name, column]) =>
231
235
  toColumnSpec(name, column, storageTypes, isInlineAutoincrementPrimaryKey(table, name)),
@@ -259,7 +263,7 @@ export interface IssuePlannerOptions {
259
263
  readonly toContract: Contract<SqlStorage>;
260
264
  readonly fromContract: Contract<SqlStorage> | null;
261
265
  readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;
262
- readonly storageTypes: Readonly<Record<string, StorageTypeInstance>>;
266
+ readonly storageTypes: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>;
263
267
  readonly schema?: SqlSchemaIR;
264
268
  readonly policy?: MigrationOperationPolicy;
265
269
  readonly frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
@@ -8,10 +8,12 @@
8
8
  * see `StorageColumn` or `storageTypes`.
9
9
  */
10
10
 
11
- import type {
12
- StorageColumn,
13
- StorageTable,
14
- StorageTypeInstance,
11
+ import {
12
+ isPostgresEnumStorageEntry,
13
+ type PostgresEnumStorageEntry,
14
+ type StorageColumn,
15
+ type StorageTable,
16
+ type StorageTypeInstance,
15
17
  } from '@prisma-next/sql-contract/types';
16
18
  import { escapeLiteral, quoteIdentifier } from '../sql-utils';
17
19
 
@@ -44,7 +46,7 @@ function assertSafeDefaultExpression(expression: string): void {
44
46
  */
45
47
  export function buildColumnTypeSql(
46
48
  column: StorageColumn,
47
- storageTypes: Record<string, StorageTypeInstance> = {},
49
+ storageTypes: Record<string, StorageTypeInstance | PostgresEnumStorageEntry> = {},
48
50
  ): string {
49
51
  const resolved = resolveColumnTypeMetadata(column, storageTypes);
50
52
  assertSafeNativeType(resolved.nativeType);
@@ -123,7 +125,7 @@ type ResolvedColumnTypeMetadata = Pick<StorageColumn, 'nativeType' | 'codecId' |
123
125
 
124
126
  function resolveColumnTypeMetadata(
125
127
  column: StorageColumn,
126
- storageTypes: Record<string, StorageTypeInstance>,
128
+ storageTypes: Record<string, StorageTypeInstance | PostgresEnumStorageEntry>,
127
129
  ): ResolvedColumnTypeMetadata {
128
130
  if (!column.typeRef) {
129
131
  return column;
@@ -134,6 +136,13 @@ function resolveColumnTypeMetadata(
134
136
  `Storage type "${column.typeRef}" referenced by column is not defined in storage.types.`,
135
137
  );
136
138
  }
139
+ if (isPostgresEnumStorageEntry(referencedType)) {
140
+ return {
141
+ codecId: referencedType.codecId,
142
+ nativeType: referencedType.nativeType,
143
+ typeParams: { values: referencedType.values } as Record<string, unknown>,
144
+ };
145
+ }
137
146
  return {
138
147
  codecId: referencedType.codecId,
139
148
  nativeType: referencedType.nativeType,
@@ -21,7 +21,11 @@ import type {
21
21
  } from '@prisma-next/family-sql/control';
22
22
  import type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';
23
23
  import type { SchemaIssue } from '@prisma-next/framework-components/control';
24
- import type { SqlStorage, StorageTypeInstance } from '@prisma-next/sql-contract/types';
24
+ import type {
25
+ PostgresEnumStorageEntry,
26
+ SqlStorage,
27
+ StorageTypeInstance,
28
+ } from '@prisma-next/sql-contract/types';
25
29
  import { defaultIndexName } from '@prisma-next/sql-schema-ir/naming';
26
30
  import type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';
27
31
  import { toTableSpec } from './issue-planner';
@@ -33,7 +37,7 @@ export interface StrategyContext {
33
37
  readonly toContract: Contract<SqlStorage>;
34
38
  readonly fromContract: Contract<SqlStorage> | null;
35
39
  readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;
36
- readonly storageTypes: Readonly<Record<string, StorageTypeInstance>>;
40
+ readonly storageTypes: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>;
37
41
  readonly schema: SqlSchemaIR;
38
42
  readonly policy: MigrationOperationPolicy;
39
43
  readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
@@ -0,0 +1,20 @@
1
+ import type { Contract } from '@prisma-next/contract/types';
2
+ import { SqlContractSerializerBase } from '@prisma-next/family-sql/ir';
3
+ import type { SqlStorage } from '@prisma-next/sql-contract/types';
4
+
5
+ /**
6
+ * SQLite target `ContractSerializer` concretion. Mirrors the Postgres
7
+ * shape: inherits the full SQL-family deserialization pipeline. Today's
8
+ * SQLite contract shape is the family-shared shape; no target-specific
9
+ * polymorphic `storage.types` factories are registered yet.
10
+ *
11
+ * `serializeContract` falls through to the family-base default —
12
+ * SQLite's contract is JSON-clean today. Once target-only fields land
13
+ * (e.g. per-target derived storage fields) this is the home for
14
+ * stripping them from the persisted envelope.
15
+ */
16
+ export class SqliteContractSerializer extends SqlContractSerializerBase<Contract<SqlStorage>> {
17
+ constructor() {
18
+ super(new Map());
19
+ }
20
+ }
@@ -0,0 +1,24 @@
1
+ import type { Contract } from '@prisma-next/contract/types';
2
+ import { SqlSchemaVerifierBase } from '@prisma-next/family-sql/ir';
3
+ import type { SchemaIssue, SchemaVerifyOptions } from '@prisma-next/framework-components/control';
4
+ import type { SqlStorage } from '@prisma-next/sql-contract/types';
5
+ import type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';
6
+
7
+ /**
8
+ * SQLite target `SchemaVerifier` concretion. Mirrors the Postgres
9
+ * shape: hooks return the empty list pending the call-site migration
10
+ * that routes the existing verifier behaviour through the SPI.
11
+ */
12
+ export class SqliteSchemaVerifier extends SqlSchemaVerifierBase<Contract<SqlStorage>, SqlSchemaIR> {
13
+ protected verifyCommonSqlSchema(
14
+ _options: SchemaVerifyOptions<Contract<SqlStorage>, SqlSchemaIR>,
15
+ ): readonly SchemaIssue[] {
16
+ return [];
17
+ }
18
+
19
+ protected verifyTargetExtensions(
20
+ _options: SchemaVerifyOptions<Contract<SqlStorage>, SqlSchemaIR>,
21
+ ): readonly SchemaIssue[] {
22
+ return [];
23
+ }
24
+ }
@@ -1 +0,0 @@
1
- {"version":3,"file":"planner-A7dqS0u6.mjs","names":[],"sources":["../src/core/migrations/planner-strategies.ts","../src/core/migrations/issue-planner.ts","../src/core/migrations/planner.ts"],"sourcesContent":["/**\n * SQLite migration strategies.\n *\n * Each strategy examines the issue list, consumes issues it handles, and\n * returns the `SqliteOpFactoryCall[]` to address them. The issue planner\n * runs each strategy in order and routes whatever's left through\n * `mapIssueToCall`.\n *\n * SQLite has no enums, no data-safe backfill, and no component-declared\n * database dependencies. The only recipe that needs strategy-level\n * multi-issue consumption is `recreateTable` (added in a later phase), which\n * absorbs type/nullability/default/constraint mismatches for a given table\n * into a single recreate operation.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n MigrationOperationClass,\n MigrationOperationPolicy,\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 { defaultIndexName } from '@prisma-next/sql-schema-ir/naming';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { toTableSpec } from './issue-planner';\nimport { DataTransformCall, RecreateTableCall, type SqliteOpFactoryCall } from './op-factory-call';\nimport type { SqliteIndexSpec } from './operations/shared';\nimport { buildRecreatePostchecks, buildRecreateSummary } from './operations/tables';\n\nexport interface StrategyContext {\n readonly toContract: Contract<SqlStorage>;\n readonly fromContract: Contract<SqlStorage> | null;\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\nexport type CallMigrationStrategy = (\n issues: readonly SchemaIssue[],\n context: StrategyContext,\n) =>\n | {\n kind: 'match';\n issues: readonly SchemaIssue[];\n calls: readonly SqliteOpFactoryCall[];\n recipe?: boolean;\n }\n | { kind: 'no_match' };\n\n// ============================================================================\n// Recreate-table strategy\n// ============================================================================\n\nconst WIDENING_ISSUE_KINDS = new Set<SchemaIssue['kind']>(['default_mismatch', 'default_missing']);\n\nconst DESTRUCTIVE_ISSUE_KINDS = new Set<SchemaIssue['kind']>([\n 'extra_default',\n 'type_mismatch',\n 'primary_key_mismatch',\n 'foreign_key_mismatch',\n 'unique_constraint_mismatch',\n 'extra_foreign_key',\n 'extra_unique_constraint',\n 'extra_primary_key',\n]);\n\nfunction classifyIssue(issue: SchemaIssue): 'widening' | 'destructive' | null {\n if (issue.kind === 'enum_values_changed') return null;\n if (!issue.table) return null;\n if (issue.kind === 'nullability_mismatch') {\n // Relaxing (NOT NULL → nullable) is widening; tightening is destructive.\n return issue.expected === 'true' ? 'widening' : 'destructive';\n }\n if (WIDENING_ISSUE_KINDS.has(issue.kind)) return 'widening';\n if (DESTRUCTIVE_ISSUE_KINDS.has(issue.kind)) return 'destructive';\n return null;\n}\n\n/**\n * Groups recreate-eligible issues by table, decides per-table operation class\n * (destructive wins over widening), and emits one `RecreateTableCall` per\n * table. Returns unchanged-or-smaller issue list — issues the strategy\n * consumed are removed so `mapIssueToCall` doesn't double-handle them.\n */\nexport const recreateTableStrategy: CallMigrationStrategy = (issues, ctx) => {\n const byTable = new Map<string, { issues: SchemaIssue[]; hasDestructive: boolean }>();\n const consumed = new Set<SchemaIssue>();\n\n for (const issue of issues) {\n const cls = classifyIssue(issue);\n if (!cls) continue;\n if (issue.kind === 'enum_values_changed') continue;\n if (!issue.table) continue;\n const table = issue.table;\n const entry = byTable.get(table);\n if (entry) {\n entry.issues.push(issue);\n if (cls === 'destructive') entry.hasDestructive = true;\n } else {\n byTable.set(table, { issues: [issue], hasDestructive: cls === 'destructive' });\n }\n consumed.add(issue);\n }\n\n if (byTable.size === 0) return { kind: 'no_match' };\n\n const calls: SqliteOpFactoryCall[] = [];\n for (const [tableName, entry] of byTable) {\n const contractTable = ctx.toContract.storage.tables[tableName];\n const schemaTable = ctx.schema.tables[tableName];\n if (!contractTable || !schemaTable) continue;\n const operationClass: MigrationOperationClass = entry.hasDestructive\n ? 'destructive'\n : 'widening';\n\n // Flatten the contract table to a self-contained spec — the Call holds\n // pre-rendered SQL fragments only, no `StorageColumn` or `storageTypes`.\n const tableSpec = toTableSpec(contractTable, ctx.storageTypes);\n\n const seenIndexColumnKeys = new Set<string>();\n const indexes: SqliteIndexSpec[] = [];\n for (const idx of contractTable.indexes) {\n const key = idx.columns.join(',');\n if (seenIndexColumnKeys.has(key)) continue;\n seenIndexColumnKeys.add(key);\n indexes.push({\n name: idx.name ?? defaultIndexName(tableName, idx.columns),\n columns: idx.columns,\n });\n }\n for (const fk of contractTable.foreignKeys) {\n if (fk.index === false) continue;\n const key = fk.columns.join(',');\n if (seenIndexColumnKeys.has(key)) continue;\n seenIndexColumnKeys.add(key);\n indexes.push({\n name: defaultIndexName(tableName, fk.columns),\n columns: fk.columns,\n });\n }\n\n calls.push(\n new RecreateTableCall({\n tableName,\n contractTable: tableSpec,\n schemaColumnNames: Object.keys(schemaTable.columns),\n indexes,\n summary: buildRecreateSummary(tableName, entry.issues),\n postchecks: buildRecreatePostchecks(tableName, entry.issues, tableSpec),\n operationClass,\n }),\n );\n }\n\n return {\n kind: 'match',\n issues: issues.filter((i) => !consumed.has(i)),\n calls,\n recipe: true,\n };\n};\n\n// ============================================================================\n// Nullability-tightening backfill strategy\n// ============================================================================\n\n/**\n * When the policy allows `'data'` and the contract tightens one or more\n * columns from nullable to NOT NULL, emit a `DataTransformCall` stub per\n * tightened column. The user fills the backfill `UPDATE` in the rendered\n * `migration.ts` before the subsequent `RecreateTableCall` copies data into\n * the tightened schema (whose `INSERT INTO temp SELECT … FROM old` would\n * otherwise fail at runtime if any `NULL`s remain).\n *\n * Does NOT consume the tightening issue — `recreateTableStrategy` still\n * needs it to produce the actual recreate that enforces the NOT NULL at\n * the schema level. The backfill op and the recreate op end up in the\n * recipe slot in strategy order (backfill first, recreate second), which\n * matches the required execution order.\n *\n * Mirrors Postgres's `nullableTighteningCallStrategy` / `'data'`-class\n * gating. When `'data'` is not in the policy (the default `db update` /\n * `db init` path), the strategy short-circuits and the recreate alone\n * runs with its current destructive-class gating — preserving today's\n * behavior where a tightening blows up at runtime if NULLs are present.\n */\nexport const nullabilityTighteningBackfillStrategy: CallMigrationStrategy = (issues, ctx) => {\n if (!ctx.policy.allowedOperationClasses.includes('data')) {\n return { kind: 'no_match' };\n }\n\n const calls: SqliteOpFactoryCall[] = [];\n for (const issue of issues) {\n if (issue.kind !== 'nullability_mismatch') continue;\n if (!issue.table || !issue.column) continue;\n // Tightening only: `expected === 'true'` means the contract wants the\n // column nullable (relaxing from NOT NULL → nullable), which is safe and\n // needs no backfill.\n if (issue.expected === 'true') continue;\n\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column || column.nullable === true) continue;\n\n calls.push(\n new DataTransformCall(\n `data_migration.backfill-${issue.table}-${issue.column}`,\n `Backfill NULLs in \"${issue.table}\".\"${issue.column}\" before NOT NULL tightening`,\n issue.table,\n issue.column,\n ),\n );\n }\n\n if (calls.length === 0) return { kind: 'no_match' };\n\n return {\n kind: 'match',\n issues,\n calls,\n recipe: true,\n };\n};\n\nexport const sqlitePlannerStrategies: readonly CallMigrationStrategy[] = [\n nullabilityTighteningBackfillStrategy,\n recreateTableStrategy,\n];\n","/**\n * SQLite migration issue planner.\n *\n * Takes schema issues (from `verifySqlSchema`) and emits migration IR\n * (`SqliteOpFactoryCall[]`). Strategies consume issues they recognize and\n * produce specialized call sequences (e.g. recreateTableStrategy absorbs\n * type/nullability/default/constraint mismatches into a single recreate op);\n * remaining issues flow 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 type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport type {\n SqlStorage,\n StorageColumn,\n StorageTable,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { defaultIndexName } from '@prisma-next/sql-schema-ir/naming';\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 CreateIndexCall,\n CreateTableCall,\n DropColumnCall,\n DropIndexCall,\n DropTableCall,\n type SqliteOpFactoryCall,\n} from './op-factory-call';\nimport type {\n SqliteColumnSpec,\n SqliteForeignKeySpec,\n SqliteTableSpec,\n SqliteUniqueSpec,\n} from './operations/shared';\nimport {\n buildColumnDefaultSql,\n buildColumnTypeSql,\n isInlineAutoincrementPrimaryKey,\n} from './planner-ddl-builders';\nimport {\n type CallMigrationStrategy,\n type StrategyContext,\n sqlitePlannerStrategies,\n} from './planner-strategies';\nimport { CONTROL_TABLE_NAMES } from './statement-builders';\n\nexport type { CallMigrationStrategy, StrategyContext };\n\n// ============================================================================\n// Issue kind ordering (dependency order)\n// ============================================================================\n\nconst ISSUE_KIND_ORDER: Record<string, number> = {\n // Drops (reconciliation — clear the way for creates)\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\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// ============================================================================\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 conflictKindForIssue(issue: SchemaIssue): SqlPlannerConflict['kind'] {\n switch (issue.kind) {\n case 'type_mismatch':\n return 'typeMismatch';\n case 'nullability_mismatch':\n return 'nullabilityConflict';\n case 'primary_key_mismatch':\n case 'unique_constraint_mismatch':\n case 'index_mismatch':\n case 'extra_primary_key':\n case 'extra_unique_constraint':\n return 'indexIncompatible';\n case 'foreign_key_mismatch':\n case 'extra_foreign_key':\n return 'foreignKeyConflict';\n default:\n return 'missingButNonAdditive';\n }\n}\n\nfunction issueLocation(issue: SchemaIssue): SqlPlannerConflictLocation | undefined {\n if (issue.kind === 'enum_values_changed') return undefined;\n const location: {\n table?: string;\n column?: string;\n constraint?: string;\n } = {};\n if (issue.table) location.table = issue.table;\n if (issue.column) location.column = issue.column;\n if (issue.indexOrConstraint) location.constraint = issue.indexOrConstraint;\n return Object.keys(location).length > 0 ? (location as SqlPlannerConflictLocation) : undefined;\n}\n\nfunction conflictForDisallowedCall(\n call: SqliteOpFactoryCall,\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\nfunction conflictKindForCall(call: SqliteOpFactoryCall): SqlPlannerConflict['kind'] {\n switch (call.factoryName) {\n case 'createIndex':\n case 'dropIndex':\n return 'indexIncompatible';\n default:\n return 'missingButNonAdditive';\n }\n}\n\nfunction locationForCall(call: SqliteOpFactoryCall): SqlPlannerConflictLocation | undefined {\n const location: { table?: string; column?: string; index?: string } = {};\n if ('tableName' in call) location.table = call.tableName;\n if ('columnName' in call) location.column = call.columnName;\n if ('indexName' in call) location.index = call.indexName;\n return Object.keys(location).length > 0 ? (location as SqlPlannerConflictLocation) : undefined;\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// StorageTable / StorageColumn → flat SqliteTableSpec\n// ============================================================================\n\n/**\n * Resolves codec / `typeRef` / default rendering into a flat\n * `SqliteColumnSpec`. Mirrors Postgres's `toColumnSpec`. Once a column is\n * flattened, downstream Calls and operation factories never see\n * `StorageColumn` again — they deal in pre-rendered SQL fragments.\n */\nexport function toColumnSpec(\n name: string,\n column: StorageColumn,\n storageTypes: Readonly<Record<string, StorageTypeInstance>>,\n inlineAutoincrementPrimaryKey = false,\n): SqliteColumnSpec {\n const typeSql = buildColumnTypeSql(column, storageTypes as Record<string, StorageTypeInstance>);\n const defaultSql = buildColumnDefaultSql(column.default);\n return {\n name,\n typeSql,\n defaultSql,\n nullable: column.nullable,\n ...(inlineAutoincrementPrimaryKey ? { inlineAutoincrementPrimaryKey: true } : {}),\n };\n}\n\n/**\n * Flattens a `StorageTable` into a `SqliteTableSpec` ready for\n * `CreateTableCall` / `RecreateTableCall`. Sole-column AUTOINCREMENT\n * primary keys are detected here and marked on the column spec so the\n * renderer emits `INTEGER PRIMARY KEY AUTOINCREMENT` inline.\n */\nexport function toTableSpec(\n table: StorageTable,\n storageTypes: Readonly<Record<string, StorageTypeInstance>>,\n): SqliteTableSpec {\n const columns: SqliteColumnSpec[] = Object.entries(table.columns).map(([name, column]) =>\n toColumnSpec(name, column, storageTypes, isInlineAutoincrementPrimaryKey(table, name)),\n );\n const uniques: SqliteUniqueSpec[] = table.uniques.map((u) => ({\n columns: u.columns,\n ...(u.name !== undefined ? { name: u.name } : {}),\n }));\n const foreignKeys: SqliteForeignKeySpec[] = table.foreignKeys.map((fk) => ({\n columns: fk.columns,\n references: { table: fk.references.table, columns: fk.references.columns },\n constraint: fk.constraint !== false,\n ...(fk.name !== undefined ? { name: fk.name } : {}),\n ...(fk.onDelete !== undefined ? { onDelete: fk.onDelete } : {}),\n ...(fk.onUpdate !== undefined ? { onUpdate: fk.onUpdate } : {}),\n }));\n return {\n columns,\n ...(table.primaryKey ? { primaryKey: { columns: table.primaryKey.columns } } : {}),\n uniques,\n foreignKeys,\n };\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 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 readonly strategies?: readonly CallMigrationStrategy[];\n}\n\nexport interface IssuePlannerValue {\n readonly calls: readonly SqliteOpFactoryCall[];\n}\n\nconst DEFAULT_POLICY: MigrationOperationPolicy = {\n allowedOperationClasses: ['additive', 'widening', 'destructive', 'data'],\n};\n\nfunction emptySchemaIR(): SqlSchemaIR {\n return { tables: {} };\n}\n\n// ============================================================================\n// Issue → Call mapping (per-issue default path)\n// ============================================================================\n\nfunction mapIssueToCall(\n issue: SchemaIssue,\n ctx: StrategyContext,\n): Result<readonly SqliteOpFactoryCall[], SqlPlannerConflict> {\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 }\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 tableSpec = toTableSpec(contractTable, ctx.storageTypes);\n const calls: SqliteOpFactoryCall[] = [new CreateTableCall(issue.table, tableSpec)];\n const declaredIndexColumnKeys = new Set<string>();\n for (const index of contractTable.indexes) {\n const indexName = index.name ?? defaultIndexName(issue.table, index.columns);\n declaredIndexColumnKeys.add(index.columns.join(','));\n calls.push(new CreateIndexCall(issue.table, indexName, index.columns));\n }\n for (const fk of contractTable.foreignKeys) {\n if (fk.index === false) continue;\n if (declaredIndexColumnKeys.has(fk.columns.join(','))) continue;\n const indexName = defaultIndexName(issue.table, fk.columns);\n calls.push(new CreateIndexCall(issue.table, indexName, fk.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 }\n const contractTable = ctx.toContract.storage.tables[issue.table];\n const columnSpec = toColumnSpec(\n issue.column,\n column,\n ctx.storageTypes,\n contractTable ? isInlineAutoincrementPrimaryKey(contractTable, issue.column) : false,\n );\n return ok([new AddColumnCall(issue.table, columnSpec)]);\n }\n\n case 'index_mismatch': {\n if (!issue.table) {\n return notOk(issueConflict('indexIncompatible', 'Index issue has no table name'));\n }\n if (!isMissing(issue) || !issue.expected) {\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 const columns = issue.expected.split(', ');\n const contractTable = ctx.toContract.storage.tables[issue.table];\n if (!contractTable) {\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Table \"${issue.table}\" not found in destination contract`,\n ),\n );\n }\n // Use the explicit-index name if one is declared for these columns;\n // otherwise fall back to `defaultIndexName` (which is also what\n // `verifySqlSchema` synthesizes for FK-backing indexes). Whether the\n // missing index originates from `contractTable.indexes` or from an FK\n // with `index: true` doesn't change the emitted DDL.\n const explicitIndex = contractTable.indexes.find(\n (idx) => idx.columns.join(',') === columns.join(','),\n );\n const indexName = explicitIndex?.name ?? defaultIndexName(issue.table, columns);\n return ok([new CreateIndexCall(issue.table, indexName, columns)]);\n }\n\n case 'extra_table': {\n if (!issue.table) {\n return notOk(issueConflict('unsupportedOperation', 'Extra table issue has no table name'));\n }\n // Runner-owned control tables must never be dropped.\n if (CONTROL_TABLE_NAMES.has(issue.table)) return ok([]);\n return ok([new DropTableCall(issue.table)]);\n }\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 }\n return ok([new DropColumnCall(issue.table, issue.column)]);\n }\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 }\n return ok([new DropIndexCall(issue.table, issue.indexOrConstraint)]);\n }\n\n // SQLite has no enum types (capability `sql.enums: false`). The verifier\n // should never emit `enum_values_changed` against a SQLite schema, so if\n // we receive one it is a verifier bug — surface it as an explicit\n // conflict rather than silently dropping it.\n case 'enum_values_changed':\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n 'Received enum_values_changed against a SQLite schema (sql.enums: false) — verifier bug',\n ),\n );\n\n // Everything below is absorbed by recreateTableStrategy. If it falls\n // through here, policy or context didn't allow the recreate — surface as\n // a conflict.\n case 'type_mismatch':\n case 'nullability_mismatch':\n case 'default_mismatch':\n case 'default_missing':\n case 'extra_default':\n case 'primary_key_mismatch':\n case 'unique_constraint_mismatch':\n case 'foreign_key_mismatch':\n case 'extra_foreign_key':\n case 'extra_unique_constraint':\n case 'extra_primary_key':\n return notOk(issueConflict(conflictKindForIssue(issue), issue.message, issueLocation(issue)));\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// Call categorization for final emission order\n// ============================================================================\n\ntype CallCategory =\n | 'drop-column'\n | 'drop-index'\n | 'drop-table'\n | 'create-table'\n | 'add-column'\n | 'create-index';\n\nfunction classifyCall(call: SqliteOpFactoryCall): CallCategory | null {\n switch (call.factoryName) {\n case 'createTable':\n return 'create-table';\n case 'addColumn':\n return 'add-column';\n case 'createIndex':\n return 'create-index';\n case 'dropColumn':\n return 'drop-column';\n case 'dropIndex':\n return 'drop-index';\n case 'dropTable':\n return 'drop-table';\n // recreateTable goes into the recipe slot; return null for bucketable.\n case 'recreateTable':\n return null;\n default:\n return null;\n }\n}\n\n// ============================================================================\n// Top-level planIssues\n// ============================================================================\n\nexport function planIssues(\n options: IssuePlannerOptions,\n): Result<IssuePlannerValue, readonly SqlPlannerConflict[]> {\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 codecHooks: options.codecHooks,\n storageTypes: options.storageTypes,\n schema,\n policy,\n frameworkComponents,\n };\n\n const strategies = options.strategies ?? sqlitePlannerStrategies;\n\n let remaining = options.issues;\n const recipeCalls: SqliteOpFactoryCall[] = [];\n const bucketableCalls: SqliteOpFactoryCall[] = [];\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 bucketableCalls.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: SqliteOpFactoryCall[] = [];\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 for recipe + bucketable. Default-mapped calls for disallowed\n // classes never get here (they're surfaced as per-issue conflicts above).\n const allowed = policy.allowedOperationClasses;\n let gatedRecipe = recipeCalls;\n let gatedBucketable = bucketableCalls;\n let gatedDefault = defaultCalls;\n if (policyProvided) {\n const sink = (acc: SqliteOpFactoryCall[]) => (call: SqliteOpFactoryCall) => {\n if (allowed.includes(call.operationClass)) {\n acc.push(call);\n return;\n }\n conflicts.push(conflictForDisallowedCall(call, allowed));\n };\n const gatedRecipeBucket: SqliteOpFactoryCall[] = [];\n const gatedBucketableBucket: SqliteOpFactoryCall[] = [];\n const gatedDefaultBucket: SqliteOpFactoryCall[] = [];\n recipeCalls.forEach(sink(gatedRecipeBucket));\n bucketableCalls.forEach(sink(gatedBucketableBucket));\n defaultCalls.forEach(sink(gatedDefaultBucket));\n gatedRecipe = gatedRecipeBucket;\n gatedBucketable = gatedBucketableBucket;\n gatedDefault = gatedDefaultBucket;\n }\n\n if (conflicts.length > 0) {\n return notOk(conflicts);\n }\n\n // Final emission order matches the current monolithic planner:\n // create-table → add-column → create-index → recreate → drop-column → drop-index → drop-table\n const combined = [...gatedDefault, ...gatedBucketable];\n const byCategory = (cat: CallCategory) => combined.filter((c) => classifyCall(c) === cat);\n\n const calls: SqliteOpFactoryCall[] = [\n ...byCategory('create-table'),\n ...byCategory('add-column'),\n ...byCategory('create-index'),\n ...gatedRecipe,\n ...byCategory('drop-column'),\n ...byCategory('drop-index'),\n ...byCategory('drop-table'),\n ];\n\n return ok({ calls });\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlMigrationPlanner,\n SqlMigrationPlannerPlanOptions,\n SqlPlannerFailureResult,\n} from '@prisma-next/family-sql/control';\nimport {\n extractCodecControlHooks,\n planFieldEventOperations,\n plannerFailure,\n} from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationPlanner,\n MigrationScaffoldContext,\n SchemaIssue,\n} from '@prisma-next/framework-components/control';\nimport { parseSqliteDefault } from '../default-normalizer';\nimport { normalizeSqliteNativeType } from '../native-type-normalizer';\nimport { planIssues } from './issue-planner';\nimport {\n type SqliteMigrationDestinationInfo,\n TypeScriptRenderableSqliteMigration,\n} from './planner-produced-sqlite-migration';\nimport { sqlitePlannerStrategies } from './planner-strategies';\nimport type { SqlitePlanTargetDetails } from './planner-target-details';\n\nexport function createSqliteMigrationPlanner(): SqliteMigrationPlanner {\n return new SqliteMigrationPlanner();\n}\n\nexport type SqlitePlanResult =\n | { readonly kind: 'success'; readonly plan: TypeScriptRenderableSqliteMigration }\n | SqlPlannerFailureResult;\n\n/**\n * SQLite migration planner — a thin wrapper over `planIssues`.\n *\n * `plan()` verifies the live schema against the target contract (producing\n * `SchemaIssue[]`) and delegates to `planIssues` with the registered\n * strategies. Strategies absorb groups of related issues into composite\n * recipes (e.g. recreating a table to apply type/nullability/default/\n * constraint changes at once); anything not absorbed by a strategy flows\n * through `mapIssueToCall` in the issue planner as a one-off call.\n *\n * FK-backing indexes are surfaced by `verifySqlSchema`'s index expansion\n * (see `verify-sql-schema.ts:459-469`), so `mapIssueToCall` handles them\n * uniformly alongside user-declared indexes.\n */\nexport class SqliteMigrationPlanner\n implements SqlMigrationPlanner<SqlitePlanTargetDetails>, MigrationPlanner<'sql', 'sqlite'>\n{\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n /**\n * The \"from\" contract (state the planner assumes the database starts at),\n * or `null` for reconciliation flows.\n *\n * Typed as the framework `Contract | null` to satisfy the\n * `MigrationPlanner` interface contract; `planSql` narrows to the SQL\n * shape via `SqlMigrationPlannerPlanOptions`. Used to populate\n * `describe().from` on the produced plan as\n * `fromContract?.storage.storageHash ?? null`.\n */\n readonly fromContract: Contract | null;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n /**\n * Contract space this plan applies to. Stamped onto the produced\n * {@link TypeScriptRenderableSqliteMigration.spaceId} so the runner keys\n * the marker row by the right space.\n */\n readonly spaceId: string;\n }): SqlitePlanResult {\n return this.planSql(options as SqlMigrationPlannerPlanOptions);\n }\n\n emptyMigration(\n context: MigrationScaffoldContext,\n spaceId: string,\n ): TypeScriptRenderableSqliteMigration {\n return new TypeScriptRenderableSqliteMigration(\n [],\n {\n from: context.fromHash,\n to: context.toHash,\n },\n spaceId,\n );\n }\n\n private planSql(options: SqlMigrationPlannerPlanOptions): SqlitePlanResult {\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) return policyResult;\n\n const schemaIssues = this.collectSchemaIssues(options);\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n const storageTypes = options.contract.storage.types ?? {};\n\n const result = planIssues({\n issues: schemaIssues,\n toContract: options.contract,\n fromContract: options.fromContract,\n codecHooks,\n storageTypes,\n schema: options.schema,\n policy: options.policy,\n frameworkComponents: options.frameworkComponents,\n strategies: sqlitePlannerStrategies,\n });\n\n if (!result.ok) {\n return plannerFailure(result.failure);\n }\n\n // Codec lifecycle hook (T2.2): inline `onFieldEvent`-emitted ops after\n // structural DDL. Sub-spec § 5 fixes the ordering as\n // `structural → added → dropped → altered`, with within-group sorting by\n // `(tableName, fieldName)` deterministic for byte-stable re-emits.\n // Hook fires only at the application emitter — extension-space planning\n // (M2 R2) never reaches this helper.\n const fieldEventOps = planFieldEventOperations({\n priorContract: options.fromContract,\n newContract: options.contract,\n codecHooks,\n });\n // Codec-emitted calls already conform to `OpFactoryCall` — render +\n // toOp + importRequirements ride directly through the same emit path\n // as structural ops, no `RawSqlCall` wrap.\n const calls = [...result.value.calls, ...fieldEventOps];\n\n const destination: SqliteMigrationDestinationInfo = {\n storageHash: options.contract.storage.storageHash,\n ...(options.contract.profileHash !== undefined\n ? { profileHash: options.contract.profileHash }\n : {}),\n };\n\n return {\n kind: 'success' as const,\n plan: new TypeScriptRenderableSqliteMigration(\n calls,\n {\n from: options.fromContract?.storage.storageHash ?? null,\n to: options.contract.storage.storageHash,\n },\n options.spaceId,\n destination,\n ),\n };\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy): SqlPlannerFailureResult | null {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n\n private collectSchemaIssues(options: SqlMigrationPlannerPlanOptions): readonly SchemaIssue[] {\n const allowed = options.policy.allowedOperationClasses;\n const strict = allowed.includes('widening') || allowed.includes('destructive');\n const verifyResult = verifySqlSchema({\n contract: options.contract,\n schema: options.schema,\n strict,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parseSqliteDefault,\n normalizeNativeType: normalizeSqliteNativeType,\n });\n return verifyResult.schema.issues;\n }\n}\n"],"mappings":";;;;;;;;;;;AAyDA,MAAM,uBAAuB,IAAI,IAAyB,CAAC,oBAAoB,kBAAkB,CAAC;AAElG,MAAM,0BAA0B,IAAI,IAAyB;CAC3D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAS,cAAc,OAAuD;CAC5E,IAAI,MAAM,SAAS,uBAAuB,OAAO;CACjD,IAAI,CAAC,MAAM,OAAO,OAAO;CACzB,IAAI,MAAM,SAAS,wBAEj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AkB;GAClB,qBAAqB;GACtB,CACkB,CAAC,OAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"tables-D84zfPZI.mjs","names":[],"sources":["../src/core/migrations/operations/shared.ts","../src/core/migrations/operations/columns.ts","../src/core/migrations/planner-ddl-builders.ts","../src/core/migrations/operations/indexes.ts","../src/core/migrations/operations/tables.ts"],"sourcesContent":["import type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { ReferentialAction } from '@prisma-next/sql-contract/types';\nimport { quoteIdentifier } from '../../sql-utils';\nimport type { SqlitePlanTargetDetails } from '../planner-target-details';\n\nexport type Op = SqlMigrationPlanOperation<SqlitePlanTargetDetails>;\n\nexport function step(description: string, sql: string): { description: string; sql: string } {\n return { description, sql };\n}\n\n/**\n * Flat, fully-resolved column shape consumed by `createTable`, `addColumn`,\n * and `recreateTable`. Codec / `typeRef` / default expansion happens at the\n * call-construction site (in the issue-planner / strategies) so the\n * operation factories deal only in pre-rendered SQL fragments — mirrors the\n * Postgres `ColumnSpec` pattern.\n *\n * - `typeSql` is the column's DDL type token (e.g. `\"INTEGER\"`, `\"TEXT\"`).\n * - `defaultSql` is the full `DEFAULT …` clause (or empty when there is no\n * default and when the column is rendered as `INTEGER PRIMARY KEY\n * AUTOINCREMENT`, since SQLite forbids a default on an autoincrement PK).\n * - `inlineAutoincrementPrimaryKey` directs the renderer to emit\n * `INTEGER PRIMARY KEY AUTOINCREMENT` inline and to skip the table-level\n * primary-key constraint for this column. SQLite-specific: the column\n * becomes an alias for `rowid` only when this exact form is used.\n */\nexport interface SqliteColumnSpec {\n readonly name: string;\n readonly typeSql: string;\n readonly defaultSql: string;\n readonly nullable: boolean;\n readonly inlineAutoincrementPrimaryKey?: boolean;\n}\n\nexport interface SqlitePrimaryKeySpec {\n readonly columns: readonly string[];\n}\n\nexport interface SqliteUniqueSpec {\n readonly columns: readonly string[];\n readonly name?: string;\n}\n\nexport interface SqliteForeignKeySpec {\n readonly columns: readonly string[];\n readonly references: {\n readonly table: string;\n readonly columns: readonly string[];\n };\n readonly name?: string;\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n readonly constraint: boolean;\n}\n\n/**\n * Flat shape of a contract table for DDL emission. Used by both\n * `createTable` (additive) and `recreateTable` (widening/destructive).\n */\nexport interface SqliteTableSpec {\n readonly columns: readonly SqliteColumnSpec[];\n readonly primaryKey?: SqlitePrimaryKeySpec;\n readonly uniques?: readonly SqliteUniqueSpec[];\n readonly foreignKeys?: readonly SqliteForeignKeySpec[];\n}\n\n/**\n * Index recreation spec for `recreateTable`. Both declared indexes and\n * FK-backing indexes flatten to the same shape; the planner dedupes by\n * column-set before constructing the call.\n */\nexport interface SqliteIndexSpec {\n readonly name: string;\n readonly columns: readonly string[];\n}\n\nconst REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string> = {\n noAction: 'NO ACTION',\n restrict: 'RESTRICT',\n cascade: 'CASCADE',\n setNull: 'SET NULL',\n setDefault: 'SET DEFAULT',\n};\n\n/**\n * Renders a single column's inline DDL fragment within a `CREATE TABLE`\n * statement. Honours the `inlineAutoincrementPrimaryKey` flag — SQLite\n * treats `INTEGER PRIMARY KEY AUTOINCREMENT` as a special form that aliases\n * `rowid`, and the column must not carry a `DEFAULT` or repeat `NOT NULL`.\n */\nexport function renderColumnDefinition(column: SqliteColumnSpec): string {\n const parts: string[] = [quoteIdentifier(column.name), column.typeSql];\n if (column.inlineAutoincrementPrimaryKey) {\n parts.push('PRIMARY KEY AUTOINCREMENT');\n } else {\n if (column.defaultSql) parts.push(column.defaultSql);\n if (!column.nullable) parts.push('NOT NULL');\n }\n return parts.join(' ');\n}\n\n/**\n * Renders an inline FOREIGN KEY constraint clause for a `CREATE TABLE`\n * body. Returns the empty string when `constraint` is false (the FK is\n * tracked at the contract level for index-creation purposes only and must\n * not produce DDL).\n */\nexport function renderForeignKeyClause(fk: SqliteForeignKeySpec): string {\n if (!fk.constraint) return '';\n const name = fk.name ? `CONSTRAINT ${quoteIdentifier(fk.name)} ` : '';\n let sql = `${name}FOREIGN KEY (${fk.columns.map(quoteIdentifier).join(', ')}) REFERENCES ${quoteIdentifier(fk.references.table)} (${fk.references.columns.map(quoteIdentifier).join(', ')})`;\n if (fk.onDelete !== undefined) {\n sql += ` ON DELETE ${REFERENTIAL_ACTION_SQL[fk.onDelete]}`;\n }\n if (fk.onUpdate !== undefined) {\n sql += ` ON UPDATE ${REFERENTIAL_ACTION_SQL[fk.onUpdate]}`;\n }\n return sql;\n}\n","import { escapeLiteral, quoteIdentifier } from '../../sql-utils';\nimport { buildTargetDetails } from '../planner-target-details';\nimport { type Op, type SqliteColumnSpec, step } from './shared';\n\nexport function addColumn(tableName: string, column: SqliteColumnSpec): Op {\n const parts = [\n `ALTER TABLE ${quoteIdentifier(tableName)}`,\n `ADD COLUMN ${quoteIdentifier(column.name)} ${column.typeSql}`,\n column.defaultSql,\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n const addSql = parts.join(' ');\n\n return {\n id: `column.${tableName}.${column.name}`,\n label: `Add column ${column.name} on ${tableName}`,\n summary: `Adds column ${column.name} on ${tableName}`,\n operationClass: 'additive',\n target: { id: 'sqlite', details: buildTargetDetails('column', column.name, tableName) },\n precheck: [\n step(\n `ensure column \"${column.name}\" is missing`,\n `SELECT COUNT(*) = 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(column.name)}'`,\n ),\n ],\n execute: [step(`add column \"${column.name}\"`, addSql)],\n postcheck: [\n step(\n `verify column \"${column.name}\" exists`,\n `SELECT COUNT(*) > 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(column.name)}'`,\n ),\n ],\n };\n}\n\nexport function dropColumn(tableName: string, columnName: string): Op {\n return {\n id: `dropColumn.${tableName}.${columnName}`,\n label: `Drop column ${columnName} on ${tableName}`,\n summary: `Drops column ${columnName} on ${tableName} which is not in the contract`,\n operationClass: 'destructive',\n target: { id: 'sqlite', details: buildTargetDetails('column', columnName, tableName) },\n precheck: [\n step(\n `ensure column \"${columnName}\" exists on \"${tableName}\"`,\n `SELECT COUNT(*) > 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(columnName)}'`,\n ),\n ],\n execute: [\n step(\n `drop column \"${columnName}\" from \"${tableName}\"`,\n `ALTER TABLE ${quoteIdentifier(tableName)} DROP COLUMN ${quoteIdentifier(columnName)}`,\n ),\n ],\n postcheck: [\n step(\n `verify column \"${columnName}\" is gone from \"${tableName}\"`,\n `SELECT COUNT(*) = 0 FROM pragma_table_info('${escapeLiteral(tableName)}') WHERE name = '${escapeLiteral(columnName)}'`,\n ),\n ],\n };\n}\n","/**\n * Low-level DDL fragment builders for SQLite migrations.\n *\n * These helpers consume `StorageColumn` (the contract shape, possibly with\n * `typeRef`) and produce string fragments. They are called once per column\n * at the call-construction boundary in `issue-planner.ts` / strategies to\n * build flat `SqliteColumnSpec`s; the operation factories themselves never\n * see `StorageColumn` or `storageTypes`.\n */\n\nimport type {\n StorageColumn,\n StorageTable,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { escapeLiteral, quoteIdentifier } from '../sql-utils';\n\ntype SqliteColumnDefault = StorageColumn['default'];\n\nconst SAFE_NATIVE_TYPE_PATTERN = /^[a-zA-Z][a-zA-Z0-9_ ]*$/;\n\nfunction assertSafeNativeType(nativeType: string): void {\n if (!SAFE_NATIVE_TYPE_PATTERN.test(nativeType)) {\n throw new Error(\n `Unsafe native type name in contract: \"${nativeType}\". ` +\n 'Native type names must match /^[a-zA-Z][a-zA-Z0-9_ ]*$/',\n );\n }\n}\n\nfunction assertSafeDefaultExpression(expression: string): void {\n if (expression.includes(';') || /--|\\/\\*|\\bSELECT\\b/i.test(expression)) {\n throw new Error(\n `Unsafe default expression in contract: \"${expression}\". ` +\n 'Default expressions must not contain semicolons, SQL comment tokens, or subqueries.',\n );\n }\n}\n\n/**\n * Renders the column's DDL type token (e.g. `\"INTEGER\"`, `\"TEXT\"`).\n * Resolves `typeRef` against `storageTypes` and validates the resulting\n * native type against a safe-identifier pattern.\n */\nexport function buildColumnTypeSql(\n column: StorageColumn,\n storageTypes: Record<string, StorageTypeInstance> = {},\n): string {\n const resolved = resolveColumnTypeMetadata(column, storageTypes);\n assertSafeNativeType(resolved.nativeType);\n return resolved.nativeType.toUpperCase();\n}\n\n/**\n * Renders the column's `DEFAULT …` clause. Returns the empty string when\n * there is no default, and also when the default is `autoincrement()` —\n * SQLite encodes that as `INTEGER PRIMARY KEY AUTOINCREMENT` inline on the\n * column definition, not as a separate DEFAULT.\n */\nexport function buildColumnDefaultSql(columnDefault: SqliteColumnDefault | undefined): string {\n if (!columnDefault) return '';\n\n switch (columnDefault.kind) {\n case 'literal':\n return `DEFAULT ${renderDefaultLiteral(columnDefault.value)}`;\n case 'function': {\n if (columnDefault.expression === 'autoincrement()') return '';\n if (columnDefault.expression === 'now()') return \"DEFAULT (datetime('now'))\";\n assertSafeDefaultExpression(columnDefault.expression);\n return `DEFAULT (${columnDefault.expression})`;\n }\n }\n}\n\nexport function renderDefaultLiteral(value: unknown): string {\n if (value instanceof Date) {\n return `'${escapeLiteral(value.toISOString())}'`;\n }\n if (typeof value === 'string') {\n return `'${escapeLiteral(value)}'`;\n }\n if (typeof value === 'number' || typeof value === 'bigint') {\n return String(value);\n }\n if (typeof value === 'boolean') {\n return value ? '1' : '0';\n }\n if (value === null) {\n return 'NULL';\n }\n return `'${escapeLiteral(JSON.stringify(value))}'`;\n}\n\nexport function buildCreateIndexSql(\n tableName: string,\n indexName: string,\n columns: readonly string[],\n unique = false,\n): string {\n const uniqueKeyword = unique ? 'UNIQUE ' : '';\n return `CREATE ${uniqueKeyword}INDEX ${quoteIdentifier(indexName)} ON ${quoteIdentifier(tableName)} (${columns.map(quoteIdentifier).join(', ')})`;\n}\n\nexport function buildDropIndexSql(indexName: string): string {\n return `DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`;\n}\n\n/**\n * True when the column is rendered inline as `INTEGER PRIMARY KEY\n * AUTOINCREMENT`. Requires the column's default to be `autoincrement()` and\n * the column to be the sole member of the table's primary key — anything\n * else falls back to a separate PRIMARY KEY constraint with a default\n * AUTOINCREMENT semantics expressed elsewhere.\n */\nexport function isInlineAutoincrementPrimaryKey(table: StorageTable, columnName: string): boolean {\n if (table.primaryKey?.columns.length !== 1) return false;\n if (table.primaryKey.columns[0] !== columnName) return false;\n const column = table.columns[columnName];\n return column?.default?.kind === 'function' && column.default.expression === 'autoincrement()';\n}\n\ntype ResolvedColumnTypeMetadata = Pick<StorageColumn, 'nativeType' | 'codecId' | 'typeParams'>;\n\nfunction resolveColumnTypeMetadata(\n column: StorageColumn,\n storageTypes: Record<string, StorageTypeInstance>,\n): ResolvedColumnTypeMetadata {\n if (!column.typeRef) {\n return column;\n }\n const referencedType = storageTypes[column.typeRef];\n if (!referencedType) {\n throw new Error(\n `Storage type \"${column.typeRef}\" referenced by column is not defined in storage.types.`,\n );\n }\n return {\n codecId: referencedType.codecId,\n nativeType: referencedType.nativeType,\n typeParams: referencedType.typeParams,\n };\n}\n","import { escapeLiteral } from '../../sql-utils';\nimport { buildCreateIndexSql, buildDropIndexSql } from '../planner-ddl-builders';\nimport { buildTargetDetails } from '../planner-target-details';\nimport { type Op, step } from './shared';\n\nexport function createIndex(tableName: string, indexName: string, columns: readonly string[]): Op {\n return {\n id: `index.${tableName}.${indexName}`,\n label: `Create index ${indexName} on ${tableName}`,\n summary: `Creates index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: { id: 'sqlite', details: buildTargetDetails('index', indexName, tableName) },\n precheck: [\n step(\n `ensure index \"${indexName}\" is missing`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n execute: [\n step(`create index \"${indexName}\"`, buildCreateIndexSql(tableName, indexName, columns)),\n ],\n postcheck: [\n step(\n `verify index \"${indexName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n };\n}\n\nexport function dropIndex(tableName: string, indexName: string): Op {\n return {\n id: `dropIndex.${tableName}.${indexName}`,\n label: `Drop index ${indexName} on ${tableName}`,\n summary: `Drops index ${indexName} on ${tableName} which is not in the contract`,\n operationClass: 'destructive',\n target: { id: 'sqlite', details: buildTargetDetails('index', indexName, tableName) },\n precheck: [\n step(\n `ensure index \"${indexName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n execute: [step(`drop index \"${indexName}\"`, buildDropIndexSql(indexName))],\n postcheck: [\n step(\n `verify index \"${indexName}\" is gone`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'index' AND name = '${escapeLiteral(indexName)}'`,\n ),\n ],\n };\n}\n","import type { MigrationOperationClass } from '@prisma-next/family-sql/control';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport { stripOuterParens } from '../../default-normalizer';\nimport { escapeLiteral, quoteIdentifier } from '../../sql-utils';\nimport { buildCreateIndexSql } from '../planner-ddl-builders';\nimport { buildTargetDetails } from '../planner-target-details';\nimport {\n type Op,\n renderColumnDefinition,\n renderForeignKeyClause,\n type SqliteIndexSpec,\n type SqliteTableSpec,\n step,\n} from './shared';\n\n/**\n * Renders the body of a `CREATE TABLE <name> ( … )` statement from a flat\n * `SqliteTableSpec`. SQLite's `INTEGER PRIMARY KEY AUTOINCREMENT` form is\n * inline on the column; the table-level PRIMARY KEY clause is emitted only\n * when no column carries `inlineAutoincrementPrimaryKey`.\n */\nfunction renderCreateTableSql(tableName: string, spec: SqliteTableSpec): string {\n const columnDefs = spec.columns.map(renderColumnDefinition);\n\n const constraintDefs: string[] = [];\n const hasInlinePk = spec.columns.some((c) => c.inlineAutoincrementPrimaryKey);\n if (spec.primaryKey && !hasInlinePk) {\n constraintDefs.push(`PRIMARY KEY (${spec.primaryKey.columns.map(quoteIdentifier).join(', ')})`);\n }\n\n for (const u of spec.uniques ?? []) {\n const name = u.name ? `CONSTRAINT ${quoteIdentifier(u.name)} ` : '';\n constraintDefs.push(`${name}UNIQUE (${u.columns.map(quoteIdentifier).join(', ')})`);\n }\n\n for (const fk of spec.foreignKeys ?? []) {\n const clause = renderForeignKeyClause(fk);\n if (clause) constraintDefs.push(clause);\n }\n\n const allDefs = [...columnDefs, ...constraintDefs];\n return `CREATE TABLE ${quoteIdentifier(tableName)} (\\n ${allDefs.join(',\\n ')}\\n)`;\n}\n\nexport function createTable(tableName: string, spec: SqliteTableSpec): Op {\n return {\n id: `table.${tableName}`,\n label: `Create table ${tableName}`,\n summary: `Creates table ${tableName} with required columns`,\n operationClass: 'additive',\n target: { id: 'sqlite', details: buildTargetDetails('table', tableName) },\n precheck: [\n step(\n `ensure table \"${tableName}\" does not exist`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n execute: [step(`create table \"${tableName}\"`, renderCreateTableSql(tableName, spec))],\n postcheck: [\n step(\n `verify table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n };\n}\n\nexport function dropTable(tableName: string): Op {\n return {\n id: `dropTable.${tableName}`,\n label: `Drop table ${tableName}`,\n summary: `Drops table ${tableName} which is not in the contract`,\n operationClass: 'destructive',\n target: { id: 'sqlite', details: buildTargetDetails('table', tableName) },\n precheck: [\n step(\n `ensure table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n execute: [step(`drop table \"${tableName}\"`, `DROP TABLE ${quoteIdentifier(tableName)}`)],\n postcheck: [\n step(\n `verify table \"${tableName}\" is gone`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n ],\n };\n}\n\nexport interface RecreateTableArgs {\n readonly tableName: string;\n /** New (post-recreate) shape of the table. Same flat spec as `createTable`. */\n readonly contractTable: SqliteTableSpec;\n /**\n * Names of columns that exist in the live (pre-recreate) schema. Used to\n * compute the `INSERT INTO temp ... SELECT ... FROM old` column list — only\n * shared columns are copied, so dropped columns are left behind and added\n * columns come from defaults.\n */\n readonly schemaColumnNames: readonly string[];\n /**\n * Indexes (declared + FK-backing, deduped by column-set) to recreate after\n * the table has been replaced. The planner pre-merges these.\n */\n readonly indexes: readonly SqliteIndexSpec[];\n /** Human-readable summary of the change, built by the planner from issues. */\n readonly summary: string;\n /**\n * Per-issue postcheck steps appended after the structural postchecks. The\n * planner pre-builds these via `buildRecreatePostchecks` so the call IR\n * carries flat, serializable data only — no `SchemaIssue` references.\n */\n readonly postchecks: readonly { readonly description: string; readonly sql: string }[];\n readonly operationClass: MigrationOperationClass;\n}\n\nexport function recreateTable(args: RecreateTableArgs): Op {\n const {\n tableName,\n contractTable,\n schemaColumnNames,\n indexes,\n summary,\n postchecks,\n operationClass,\n } = args;\n const tempName = `_prisma_new_${tableName}`;\n const liveSet = new Set(schemaColumnNames);\n const sharedColumns = contractTable.columns.filter((c) => liveSet.has(c.name)).map((c) => c.name);\n const columnList = sharedColumns.map(quoteIdentifier).join(', ');\n\n const indexStatements = indexes.map((idx) => ({\n description: `recreate index \"${idx.name}\" on \"${tableName}\"`,\n sql: buildCreateIndexSql(tableName, idx.name, idx.columns),\n }));\n\n // If the contract retains no columns from the live table, an `INSERT INTO\n // tmp () SELECT FROM old` is invalid SQL — and would also be a no-op since\n // there's nothing to copy. Skip the copy step in that case; the new\n // (empty) table replaces the old one directly.\n const copyStep =\n sharedColumns.length > 0\n ? [\n step(\n `copy data from \"${tableName}\" to \"${tempName}\"`,\n `INSERT INTO ${quoteIdentifier(tempName)} (${columnList}) SELECT ${columnList} FROM ${quoteIdentifier(tableName)}`,\n ),\n ]\n : [];\n\n return {\n id: `recreateTable.${tableName}`,\n label: `Recreate table ${tableName}`,\n summary,\n operationClass,\n target: { id: 'sqlite', details: buildTargetDetails('table', tableName) },\n precheck: [\n step(\n `ensure table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n step(\n `ensure temp table \"${tempName}\" does not exist`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tempName)}'`,\n ),\n ],\n execute: [\n step(\n `create new table \"${tempName}\" with desired schema`,\n renderCreateTableSql(tempName, contractTable),\n ),\n ...copyStep,\n step(`drop old table \"${tableName}\"`, `DROP TABLE ${quoteIdentifier(tableName)}`),\n step(\n `rename \"${tempName}\" to \"${tableName}\"`,\n `ALTER TABLE ${quoteIdentifier(tempName)} RENAME TO ${quoteIdentifier(tableName)}`,\n ),\n ...indexStatements,\n ],\n postcheck: [\n step(\n `verify table \"${tableName}\" exists`,\n `SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tableName)}'`,\n ),\n step(\n `verify temp table \"${tempName}\" is gone`,\n `SELECT COUNT(*) = 0 FROM sqlite_master WHERE type = 'table' AND name = '${escapeLiteral(tempName)}'`,\n ),\n ...postchecks,\n ],\n };\n}\n\n/**\n * Build a one-line summary of a recreate-table operation from the schema\n * issues that triggered it. Lives next to `recreateTable` so the planner\n * (which has the issues) can produce the same description the factory\n * used to build inline. Keeping the formatting target-side keeps\n * `RecreateTableCall` issue-free at the IR layer.\n */\nexport function buildRecreateSummary(tableName: string, issues: readonly SchemaIssue[]): string {\n const messages = issues.map((i) => i.message).join('; ');\n return `Recreates table ${tableName} to apply schema changes: ${messages}`;\n}\n\nconst COLUMN_LEVEL_ISSUE_KINDS = new Set<SchemaIssue['kind']>([\n 'nullability_mismatch',\n 'default_mismatch',\n 'default_missing',\n 'extra_default',\n 'type_mismatch',\n]);\n\nconst PK_ISSUE_KINDS = new Set<SchemaIssue['kind']>(['primary_key_mismatch', 'extra_primary_key']);\n\nconst UNIQUE_ISSUE_KINDS = new Set<SchemaIssue['kind']>([\n 'unique_constraint_mismatch',\n 'extra_unique_constraint',\n]);\n\nconst FK_ISSUE_KINDS = new Set<SchemaIssue['kind']>(['foreign_key_mismatch', 'extra_foreign_key']);\n\n/**\n * Returns the columns the contract expects as the table's primary key. Picks\n * up SQLite's inline `INTEGER PRIMARY KEY AUTOINCREMENT` form when no\n * explicit `primaryKey` clause is set on the spec.\n */\nfunction expectedPrimaryKeyColumns(spec: SqliteTableSpec): readonly string[] {\n if (spec.primaryKey) return spec.primaryKey.columns;\n const inlinePk = spec.columns.find((c) => c.inlineAutoincrementPrimaryKey);\n return inlinePk ? [inlinePk.name] : [];\n}\n\nfunction quoteSqlList(values: readonly string[]): string {\n return values.map((v) => `'${escapeLiteral(v)}'`).join(', ');\n}\n\n/**\n * Per-issue postchecks verifying the recreated table's shape against the\n * contract spec. Column-level issues (`nullability_mismatch`,\n * `default_mismatch`, …) emit one targeted check each; constraint-level\n * issues (`primary_key_mismatch`, `unique_constraint_mismatch`,\n * `foreign_key_mismatch`, plus their `extra_*` siblings) emit one\n * `pragma_*`-driven check per declared constraint in the contract spec, so\n * a recreated table with the right columns but the wrong PK / unique / FK\n * shape fails the postcheck instead of passing silently. Exported so the\n * planner can pre-build the list at construction time and\n * `RecreateTableCall` doesn't have to carry `SchemaIssue` objects through\n * to render time.\n */\nexport function buildRecreatePostchecks(\n tableName: string,\n issues: readonly SchemaIssue[],\n spec: SqliteTableSpec,\n): Array<{ description: string; sql: string }> {\n const checks: Array<{ description: string; sql: string }> = [];\n const t = escapeLiteral(tableName);\n const byName = new Map(spec.columns.map((c) => [c.name, c]));\n\n for (const issue of issues) {\n if (issue.kind === 'enum_values_changed') continue;\n if (!COLUMN_LEVEL_ISSUE_KINDS.has(issue.kind)) continue;\n if (!issue.column) continue;\n const c = escapeLiteral(issue.column);\n if (issue.kind === 'nullability_mismatch') {\n // `expected` carries the contract's nullable flag as a string. We only\n // emit a postcheck when the value is recognized — anything else\n // (case-folded, numeric coding, etc.) is left to the structural\n // verifier so a typo here can't silently invert the meaning.\n let wantNotNull: boolean | undefined;\n if (issue.expected === 'false') wantNotNull = true;\n else if (issue.expected === 'true') wantNotNull = false;\n if (wantNotNull !== undefined) {\n checks.push({\n description: `verify \"${issue.column}\" nullability on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND \"notnull\" = ${wantNotNull ? 1 : 0}`,\n });\n }\n }\n if (issue.kind === 'default_mismatch' || issue.kind === 'default_missing') {\n const colSpec = byName.get(issue.column);\n const expectedRaw = colSpec?.defaultSql.startsWith('DEFAULT ')\n ? // SQLite's pragma_table_info.dflt_value strips outer parens for\n // expression defaults (per the SQLite docs), so `(datetime('now'))`\n // is stored as `datetime('now')`. Strip them here so the postcheck\n // matches.\n stripOuterParens(colSpec.defaultSql.slice('DEFAULT '.length))\n : null;\n if (expectedRaw) {\n checks.push({\n description: `verify \"${issue.column}\" default on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND dflt_value = '${escapeLiteral(expectedRaw)}'`,\n });\n }\n }\n if (issue.kind === 'type_mismatch') {\n const colSpec = byName.get(issue.column);\n if (colSpec) {\n checks.push({\n description: `verify \"${issue.column}\" type on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND LOWER(type) = '${escapeLiteral(colSpec.typeSql.toLowerCase())}'`,\n });\n }\n }\n if (issue.kind === 'extra_default') {\n checks.push({\n description: `verify \"${issue.column}\" has no default on \"${tableName}\"`,\n sql: `SELECT COUNT(*) > 0 FROM pragma_table_info('${t}') WHERE name = '${c}' AND dflt_value IS NULL`,\n });\n }\n }\n\n // Constraint-level issues — emit one postcheck per declared constraint in\n // the contract spec when *any* issue of that kind fires, since recreate\n // rebuilds the entire table at once.\n const hasPkIssue = issues.some((i) => PK_ISSUE_KINDS.has(i.kind));\n const hasUniqueIssue = issues.some((i) => UNIQUE_ISSUE_KINDS.has(i.kind));\n const hasFkIssue = issues.some((i) => FK_ISSUE_KINDS.has(i.kind));\n\n if (hasPkIssue) {\n const pkColumns = expectedPrimaryKeyColumns(spec);\n // Verify pragma_table_info reports exactly these columns as PK members\n // (count + named membership); zero columns expected ⇒ no PK at all.\n const colCount = pkColumns.length;\n if (colCount === 0) {\n checks.push({\n description: `verify \"${tableName}\" has no primary key`,\n sql: `SELECT (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0) = 0`,\n });\n } else {\n checks.push({\n description: `verify primary key on \"${tableName}\"`,\n sql:\n `SELECT (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0) = ${colCount}` +\n ` AND (SELECT COUNT(*) FROM pragma_table_info('${t}') WHERE pk > 0 AND name IN (${quoteSqlList(pkColumns)})) = ${colCount}`,\n });\n }\n }\n\n if (hasUniqueIssue) {\n for (const u of spec.uniques ?? []) {\n const colCount = u.columns.length;\n const description = u.name\n ? `verify unique constraint \"${u.name}\" on \"${tableName}\"`\n : `verify unique constraint (${u.columns.join(', ')}) on \"${tableName}\"`;\n // Match any unique index whose covered columns are exactly the expected\n // set. Order is intentionally not checked — SQLite's unique-index\n // identity is column-set, not column-sequence.\n checks.push({\n description,\n sql:\n `SELECT EXISTS (SELECT 1 FROM pragma_index_list('${t}') l` +\n ` WHERE l.\"unique\" = 1` +\n ` AND (SELECT COUNT(*) FROM pragma_index_info(l.name)) = ${colCount}` +\n ` AND (SELECT COUNT(*) FROM pragma_index_info(l.name) WHERE name IN (${quoteSqlList(u.columns)})) = ${colCount})`,\n });\n }\n }\n\n if (hasFkIssue) {\n for (const fk of spec.foreignKeys ?? []) {\n const refTable = escapeLiteral(fk.references.table);\n const colCount = fk.columns.length;\n // Build a `SUM(CASE WHEN (\"from\",\"to\") IN ((…)) …)` so the check works\n // for both single- and multi-column FKs without depending on FK row\n // ordering inside `pragma_foreign_key_list`.\n const tuples = fk.columns\n .map((from, i) => {\n const to = fk.references.columns[i] ?? from;\n return `('${escapeLiteral(from)}', '${escapeLiteral(to)}')`;\n })\n .join(', ');\n const description = `verify foreign key (${fk.columns.join(', ')}) → ${fk.references.table}(${fk.references.columns.join(', ')}) on \"${tableName}\"`;\n checks.push({\n description,\n sql:\n `SELECT EXISTS (SELECT 1 FROM pragma_foreign_key_list('${t}') f` +\n ` WHERE f.\"table\" = '${refTable}'` +\n ' GROUP BY f.id' +\n ` HAVING COUNT(*) = ${colCount}` +\n ` AND SUM(CASE WHEN (f.\"from\", f.\"to\") IN (${tuples}) THEN 1 ELSE 0 END) = ${colCount})`,\n });\n }\n }\n\n return checks;\n}\n"],"mappings":";;;;AAOA,SAAgB,KAAK,aAAqB,KAAmD;CAC3F,OAAO;EAAE;EAAa;EAAK;;AAqE7B,MAAM,yBAA4D;CAChE,UAAU;CACV,UAAU;CACV,SAAS;CACT,SAAS;CACT,YAAY;CACb;;;;;;;AAQD,SAAgB,uBAAuB,QAAkC;CACvE,MAAM,QAAkB,CAAC,gBAAgB,OAAO,KAAK,EAAE,OAAO,QAAQ;CACtE,IAAI,OAAO,+BACT,MAAM,KAAK,4BAA4B;MAClC;EACL,IAAI,OAAO,YAAY,MAAM,KAAK,OAAO,WAAW;EACpD,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,WAAW;;CAE9C,OAAO,MAAM,KAAK,IAAI;;;;;;;;AASxB,SAAgB,uBAAuB,IAAkC;CACvE,IAAI,CAAC,GAAG,YAAY,OAAO;CAE3B,IAAI,MAAM,GADG,GAAG,OAAO,cAAc,gBAAgB,GAAG,KAAK,CAAC,KAAK,GACjD,eAAe,GAAG,QAAQ,IAAI,gBAAgB,CAAC,KAAK,KAAK,CAAC,eAAe,gBAAgB,GAAG,WAAW,MAAM,CAAC,IAAI,GAAG,WAAW,QAAQ,IAAI,gBAAgB,CAAC,KAAK,KAAK,CAAC;C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