@prisma-next/target-sqlite 0.13.0-dev.35 → 0.13.0-dev.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/contract-free.d.mts +35 -2
  2. package/dist/contract-free.d.mts.map +1 -1
  3. package/dist/contract-free.mjs +3 -3
  4. package/dist/control.mjs +2 -2
  5. package/dist/ddl-DrtjQMFK.mjs +68 -0
  6. package/dist/ddl-DrtjQMFK.mjs.map +1 -0
  7. package/dist/migration.d.mts +3 -45
  8. package/dist/migration.d.mts.map +1 -1
  9. package/dist/migration.mjs +3 -3
  10. package/dist/{op-factory-call-z4TT72k3.mjs → op-factory-call-DmdfD1yd.mjs} +143 -104
  11. package/dist/op-factory-call-DmdfD1yd.mjs.map +1 -0
  12. package/dist/op-factory-call.d.mts +12 -6
  13. package/dist/op-factory-call.d.mts.map +1 -1
  14. package/dist/op-factory-call.mjs +1 -1
  15. package/dist/{planner-jMHqfl1A.mjs → planner-Ciq8p_dL.mjs} +3 -3
  16. package/dist/{planner-jMHqfl1A.mjs.map → planner-Ciq8p_dL.mjs.map} +1 -1
  17. package/dist/{planner-produced-sqlite-migration-CyyvoPmm.mjs → planner-produced-sqlite-migration-0xPEm3R1.mjs} +2 -2
  18. package/dist/{planner-produced-sqlite-migration-CyyvoPmm.mjs.map → planner-produced-sqlite-migration-0xPEm3R1.mjs.map} +1 -1
  19. package/dist/{planner-produced-sqlite-migration-BWpnDmhM.d.mts → planner-produced-sqlite-migration-CpgsY-M9.d.mts} +2 -2
  20. package/dist/{planner-produced-sqlite-migration-BWpnDmhM.d.mts.map → planner-produced-sqlite-migration-CpgsY-M9.d.mts.map} +1 -1
  21. package/dist/planner-produced-sqlite-migration.d.mts +1 -1
  22. package/dist/planner-produced-sqlite-migration.mjs +1 -1
  23. package/dist/planner.d.mts +1 -1
  24. package/dist/planner.mjs +1 -1
  25. package/dist/shared-Dhc8mLK1.d.mts.map +1 -1
  26. package/dist/{sqlite-migration-DhW4ycZV.mjs → sqlite-migration-A0rwqPOG.mjs} +32 -13
  27. package/dist/sqlite-migration-A0rwqPOG.mjs.map +1 -0
  28. package/dist/sqlite-migration-DVfhQwN_.d.mts +75 -0
  29. package/dist/sqlite-migration-DVfhQwN_.d.mts.map +1 -0
  30. package/package.json +18 -18
  31. package/src/contract-free/checks.ts +75 -0
  32. package/src/core/migrations/op-factory-call.ts +191 -43
  33. package/src/core/migrations/operations/columns.ts +32 -26
  34. package/src/core/migrations/operations/indexes.ts +31 -27
  35. package/src/core/migrations/operations/shared.ts +11 -3
  36. package/src/core/migrations/operations/tables.ts +39 -37
  37. package/src/core/migrations/sqlite-migration.ts +82 -14
  38. package/src/exports/contract-free.ts +8 -0
  39. package/src/exports/migration.ts +0 -3
  40. package/dist/ddl-CH8V_qcd.mjs +0 -23
  41. package/dist/ddl-CH8V_qcd.mjs.map +0 -1
  42. package/dist/op-factory-call-z4TT72k3.mjs.map +0 -1
  43. package/dist/sqlite-migration-CJrASAxf.d.mts +0 -46
  44. package/dist/sqlite-migration-CJrASAxf.d.mts.map +0 -1
  45. package/dist/sqlite-migration-DhW4ycZV.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"op-factory-call.d.mts","names":[],"sources":["../src/core/migrations/op-factory-call.ts"],"mappings":";;;;;;;;;KAmCK,EAAA,GAAK,yBAAyB,CAAC,uBAAA;AAAA,uBAIrB,uBAAA,SAAgC,YAAA,YAAwB,aAAA;EAAA,kBACnD,WAAA;EAAA,kBACA,cAAA,EAAgB,uBAAA;EAAA,kBAChB,KAAA;EAAA,SACT,IAAA,CAAK,OAAA,GAAU,OAAA,GAAU,EAAA,GAAK,OAAA,CAAQ,EAAA;EAE/C,kBAAA,aAA+B,iBAAA;EAAA,UAIrB,MAAA;AAAA;AAAA,cAuEC,eAAA,SAAwB,uBAAA;EAAA,SAC1B,WAAA;EAAA,SACA,cAAA;EAAA,SACA,SAAA;EAAA,SACA,OAAA,WA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A;EAAA,SACxB,WAAA;EAAA,SACA,cAAA;EAAA,SACA,SAAA;EAAA,SACA,SAAA;EAAA,SACA,KAAA;cAEG,SAAA,UAAmB,SAAA;EAQzB,IAAA,CAAK,OAAA,GAAU,qBAAA,GAAwB,OAAA,CAAQ,EAAA;EAwBrD,gBAAA;EAIS,kBAAA,aAA+B,iBAAA;AAAA;;;;;;;;;;;;;cAqB7B,iBAAA,SAA0B,uBAAA;EAAA,SAC5B,WAAA;EAAA,SACA,cAAA;EAAA,SACA,EAAA;EAAA,SACA,KAAA;EAAA,SACA,SAAA;EAAA,SACA,UAAA;cAEG,EAAA,UAAY,KAAA,UAAe,SAAA,UAAmB,UAAA;EAS1D,IAAA,CAAK,QAAA,GAAW,OAAA,GAAU,EAAA;EAI1B,gBAAA;EAaS,kBAAA,aAA+B,iBAAA;AAAA;;;;;;;;;;cAqB7B,UAAA,SAAmB,uBAAA;EAAA,SACrB,WAAA;EAAA,SACA,cAAA,EAAgB,uBAAA;EAAA,SAChB,KAAA;EAAA,SACA,EAAA,EAAI,EAAA;cAED,EAAA,EAAI,EAAA;EAQhB,IAAA,CAAK,QAAA,GAAW,OAAA,GAAU,EAAA;EAI1B,gBAAA;AAAA;AAAA,KASU,mBAAA,GACR,eAAA,GACA,aAAA,GACA,iBAAA,GACA,aAAA,GACA,cAAA,GACA,eAAA,GACA,aAAA,GACA,iBAAA,GACA,UAAA"}
@@ -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-z4TT72k3.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-DmdfD1yd.mjs";
2
2
  export { AddColumnCall, CreateIndexCall, CreateTableCall, DataTransformCall, DropColumnCall, DropIndexCall, DropTableCall, RawSqlCall, RecreateTableCall };
@@ -1,8 +1,8 @@
1
1
  import { t as parseSqliteDefault } from "./default-normalizer-DuoHj9-O.mjs";
2
2
  import { t as normalizeSqliteNativeType } from "./native-type-normalizer-CiSyVmMP.mjs";
3
3
  import { t as CONTROL_TABLE_NAMES } from "./control-tables-7KwMyJ6i.mjs";
4
- import { _ as buildColumnTypeSql, a as DropColumnCall, b as resolveColumnTypeMetadata, d as buildRecreateSummary, g as buildColumnDefaultSql, i as DataTransformCall, l as RecreateTableCall, n as CreateIndexCall, o as DropIndexCall, r as CreateTableCall, s as DropTableCall, t as AddColumnCall, u as buildRecreatePostchecks, v as isInlineAutoincrementPrimaryKey } from "./op-factory-call-z4TT72k3.mjs";
5
- import { t as TypeScriptRenderableSqliteMigration } from "./planner-produced-sqlite-migration-CyyvoPmm.mjs";
4
+ import { a as DropColumnCall, d as buildRecreateSummary, f as buildColumnDefaultSql, g as resolveColumnTypeMetadata, i as DataTransformCall, l as RecreateTableCall, m as isInlineAutoincrementPrimaryKey, n as CreateIndexCall, o as DropIndexCall, p as buildColumnTypeSql, r as CreateTableCall, s as DropTableCall, t as AddColumnCall, u as buildRecreatePostchecks } from "./op-factory-call-DmdfD1yd.mjs";
5
+ import { t as TypeScriptRenderableSqliteMigration } from "./planner-produced-sqlite-migration-0xPEm3R1.mjs";
6
6
  import { DdlColumn, ForeignKeyConstraint, FunctionColumnDefault, LiteralColumnDefault, PrimaryKeyConstraint, UniqueConstraint } from "@prisma-next/sql-relational-core/ast";
7
7
  import { extractCodecControlHooks, planFieldEventOperations, plannerFailure } from "@prisma-next/family-sql/control";
8
8
  import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
@@ -619,4 +619,4 @@ var SqliteMigrationPlanner = class {
619
619
  //#endregion
620
620
  export { createSqliteMigrationPlanner as n, SqliteMigrationPlanner as t };
621
621
 
622
- //# sourceMappingURL=planner-jMHqfl1A.mjs.map
622
+ //# sourceMappingURL=planner-Ciq8p_dL.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"planner-jMHqfl1A.mjs","names":["exhaustive","#lowerer"],"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 { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type {\n SqlStorage,\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 { 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\n/**\n * Look up a storage table by its explicit namespace coordinate. Returns\n * `undefined` when the namespace has no table by that name (or no such\n * namespace exists). Callers that get `undefined` MUST treat it as an\n * explicit conflict rather than silently falling back to a name-only\n * walk across namespaces — the SQLite target currently has a single\n * namespace, but this helper enforces the explicit-coordinate\n * discipline so a future multi-namespace SQLite shape inherits the\n * conflict-on-stale-coordinate behaviour the Postgres planner already\n * has.\n */\nexport function tableAt(\n storage: SqlStorage,\n namespaceId: string,\n tableName: string,\n): StorageTable | undefined {\n const ns = storage.namespaces[namespaceId];\n return ns !== undefined ? ns.entries.table?.[tableName] : undefined;\n}\n\n/**\n * Default namespace coordinate for an issue that does not carry one\n * explicitly. Hand-crafted unit-test issues fall back to `__unbound__`,\n * the only namespace any single-namespace contract carries —\n * verifier-emitted issues for legacy single-namespace contracts already\n * stamp this id explicitly. Typed structurally so issue variants\n * without a `namespaceId` slot flow through to the same fallback.\n */\nexport function resolveNamespaceIdForIssue(issue: { readonly namespaceId?: string }): string {\n return issue.namespaceId ?? UNBOUND_NAMESPACE_ID;\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<\n string,\n { issues: SchemaIssue[]; hasDestructive: boolean; namespaceId: string }\n >();\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, {\n issues: [issue],\n hasDestructive: cls === 'destructive',\n namespaceId: resolveNamespaceIdForIssue(issue),\n });\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 = tableAt(ctx.toContract.storage, entry.namespaceId, 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.source.columns.join(',');\n if (seenIndexColumnKeys.has(key)) continue;\n seenIndexColumnKeys.add(key);\n indexes.push({\n name: defaultIndexName(tableName, fk.source.columns),\n columns: fk.source.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 namespaceId = resolveNamespaceIdForIssue(issue);\n const column = tableAt(ctx.toContract.storage, namespaceId, 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, JsonValue } 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 type { CodecRef, DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';\nimport {\n DdlColumn,\n ForeignKeyConstraint,\n FunctionColumnDefault,\n LiteralColumnDefault,\n PrimaryKeyConstraint,\n UniqueConstraint,\n} from '@prisma-next/sql-relational-core/ast';\nimport { defaultIndexName } from '@prisma-next/sql-schema-ir/naming';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport { CONTROL_TABLE_NAMES } from '../control-tables';\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 resolveColumnTypeMetadata,\n} from './planner-ddl-builders';\nimport {\n type CallMigrationStrategy,\n resolveNamespaceIdForIssue,\n type StrategyContext,\n sqlitePlannerStrategies,\n tableAt,\n} from './planner-strategies';\n\nexport type { CallMigrationStrategy, StrategyContext };\n\n// ============================================================================\n// Issue kind ordering (dependency order)\n// ============================================================================\n\nconst ISSUE_KIND_ORDER: Record<string, number> = {\n // 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(\n column,\n blindCast<\n Record<string, StorageTypeInstance>,\n 'buildColumnTypeSql declares its storageTypes parameter as mutable Record while the planner stores it readonly; the helper does not mutate, so the readonly→mutable narrowing is sound'\n >(storageTypes),\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>>,\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.source.columns,\n references: { table: fk.target.tableName, columns: fk.target.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// StorageTable / StorageColumn → DdlColumn[] + DdlTableConstraint[] (for CreateTableCall)\n// ============================================================================\n\nfunction sqliteDefaultToDdlColumnDefault(\n columnDefault: StorageColumn['default'],\n): DdlColumn['default'] {\n if (!columnDefault) return undefined;\n switch (columnDefault.kind) {\n case 'literal':\n return new LiteralColumnDefault(columnDefault.value);\n case 'function':\n // `autoincrement()` is not a DEFAULT clause — SQLite encodes it as\n // `INTEGER PRIMARY KEY AUTOINCREMENT` inline on the column. Skip it\n // here; the renderer also has a defensive guard for the same case.\n if (columnDefault.expression === 'autoincrement()') return undefined;\n return new FunctionColumnDefault(columnDefault.expression);\n default: {\n const exhaustive: never = columnDefault;\n throw new Error(\n `sqliteDefaultToDdlColumnDefault: unhandled kind \"${blindCast<{ kind: string }, 'exhaustiveness: surface the unhandled default kind'>(exhaustive).kind}\"`,\n );\n }\n }\n}\n\n/**\n * Converts a `StorageTable` to the `DdlColumn[]` + `DdlTableConstraint[]`\n * pair used by `CreateTableCall`. This is the structured form consumed by\n * the DDL lowering path; `toTableSpec` / `toColumnSpec` remain in use for\n * `RecreateTableCall` and `AddColumnCall` (Phase 2).\n */\nexport function tableToDdlParts(\n table: StorageTable,\n storageTypes: Record<string, StorageTypeInstance>,\n): { columns: DdlColumn[]; constraints: DdlTableConstraint[] } {\n const columns: DdlColumn[] = Object.entries(table.columns).map(([name, column]) => {\n const inlineAutoincrement = isInlineAutoincrementPrimaryKey(table, name);\n const typeSql = buildColumnTypeSql(\n column,\n blindCast<\n Record<string, StorageTypeInstance>,\n 'buildColumnTypeSql declares its storageTypes parameter as mutable Record while the planner stores it readonly; the helper does not mutate, so the readonly→mutable narrowing is sound'\n >(storageTypes),\n );\n\n if (inlineAutoincrement) {\n // `DdlColumn` has no SQLite-specific autoincrement flag, so the full\n // `PRIMARY KEY AUTOINCREMENT` clause is embedded in the `type` string.\n // The DDL renderer (`ddl-renderer.ts`) substring-detects `AUTOINCREMENT`\n // to suppress the normal NOT NULL / PRIMARY KEY / DEFAULT clause rendering\n // and emit the entire type string verbatim. Both sites must stay in sync.\n // The structural fix (a SQLite-specific column option) is tracked in TML-2866.\n return new DdlColumn({ name, type: `${typeSql} PRIMARY KEY AUTOINCREMENT` });\n }\n const colDefault = sqliteDefaultToDdlColumnDefault(column.default);\n const resolved = resolveColumnTypeMetadata(\n column,\n blindCast<\n Record<string, StorageTypeInstance>,\n 'resolveColumnTypeMetadata declares its storageTypes parameter as mutable Record while the planner stores it readonly; the helper does not mutate, so the readonly→mutable narrowing is sound'\n >(storageTypes),\n );\n const codecRef: CodecRef | undefined = resolved.codecId\n ? {\n codecId: resolved.codecId,\n ...(resolved.typeParams !== undefined\n ? {\n typeParams: blindCast<\n JsonValue,\n 'resolved.typeParams is JsonValue-shaped storage metadata; the narrowed (non-undefined) value lands in CodecRef.typeParams which is JsonValue'\n >(resolved.typeParams),\n }\n : {}),\n }\n : undefined;\n return new DdlColumn({\n name,\n type: typeSql,\n ...(!column.nullable ? { notNull: true } : {}),\n ...(colDefault !== undefined ? { default: colDefault } : {}),\n ...(codecRef !== undefined ? { codecRef } : {}),\n });\n });\n\n const constraints: DdlTableConstraint[] = [];\n\n const hasInlinePk = Object.entries(table.columns).some(([name]) =>\n isInlineAutoincrementPrimaryKey(table, name),\n );\n if (table.primaryKey && !hasInlinePk) {\n constraints.push(new PrimaryKeyConstraint({ columns: table.primaryKey.columns }));\n }\n\n for (const u of table.uniques) {\n constraints.push(\n new UniqueConstraint({\n columns: u.columns,\n ...(u.name !== undefined ? { name: u.name } : {}),\n }),\n );\n }\n\n for (const fk of table.foreignKeys) {\n if (fk.constraint === false) continue;\n constraints.push(\n new ForeignKeyConstraint({\n columns: fk.source.columns,\n refTable: fk.target.tableName,\n refColumns: fk.target.columns,\n ...ifDefined('name', fk.name),\n ...ifDefined('onDelete', fk.onDelete),\n ...ifDefined('onUpdate', fk.onUpdate),\n }),\n );\n }\n\n return { columns, constraints };\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 namespaceId = resolveNamespaceIdForIssue(issue);\n const contractTable = tableAt(ctx.toContract.storage, namespaceId, issue.table);\n if (!contractTable) {\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Table \"${issue.table}\" in namespace \"${namespaceId}\" reported missing but not found in destination contract`,\n ),\n );\n }\n const { columns: ddlColumns, constraints: ddlConstraints } = tableToDdlParts(\n contractTable,\n ctx.storageTypes,\n );\n const calls: SqliteOpFactoryCall[] = [\n new CreateTableCall(\n issue.table,\n ddlColumns,\n ddlConstraints.length > 0 ? ddlConstraints : undefined,\n ),\n ];\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.source.columns.join(','))) continue;\n const indexName = defaultIndexName(issue.table, fk.source.columns);\n calls.push(new CreateIndexCall(issue.table, indexName, fk.source.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 namespaceId = resolveNamespaceIdForIssue(issue);\n const contractTable2 = tableAt(ctx.toContract.storage, namespaceId, issue.table);\n const column = contractTable2?.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 = contractTable2;\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 namespaceId = resolveNamespaceIdForIssue(issue);\n const columns = issue.expected.split(', ');\n const contractTable = tableAt(ctx.toContract.storage, namespaceId, 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 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 type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\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(\n lowerer: ExecuteRequestLowerer,\n): SqliteMigrationPlanner {\n return new SqliteMigrationPlanner(lowerer);\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 readonly #lowerer: ExecuteRequestLowerer;\n\n constructor(lowerer: ExecuteRequestLowerer) {\n this.#lowerer = lowerer;\n }\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 undefined,\n this.#lowerer,\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 this.#lowerer,\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,SAAgB,QACd,SACA,aACA,WAC0B;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aACA,KAAKA,QACP;EACF;CACF;CAEA,qBAA6B,QAAkE;EAC7F,IAAI,CAAC,OAAO,wBAAwB,SAAS,UAAU,GACrD,OAAO,eAAe,CACpB;GACE,MAAM;GACN,SAAS;GACT,KAAK;EACP,CACF,CAAC;EAEH,OAAO;CACT;CAEA,oBAA4B,SAAiE;EAC3F,MAAM,UAAU,QAAQ,OAAO;EAC/B,MAAM,SAAS,QAAQ,SAAS,UAAU,KAAK,QAAQ,SAAS,aAAa;EAU7E,OATqB,gBAAgB;GACnC,UAAU,QAAQ;GAClB,QAAQ,QAAQ;GAChB;GACA,sCAAsB,IAAI,IAAI;GAC9B,qBAAqB,QAAQ;GAC7B,kBAAkB;GAClB,qBAAqB;EACvB,CACkB,CAAC,CAAC,OAAO;CAC7B;AACF"}
1
+ {"version":3,"file":"planner-Ciq8p_dL.mjs","names":["exhaustive","#lowerer"],"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 { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type {\n SqlStorage,\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 { 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\n/**\n * Look up a storage table by its explicit namespace coordinate. Returns\n * `undefined` when the namespace has no table by that name (or no such\n * namespace exists). Callers that get `undefined` MUST treat it as an\n * explicit conflict rather than silently falling back to a name-only\n * walk across namespaces — the SQLite target currently has a single\n * namespace, but this helper enforces the explicit-coordinate\n * discipline so a future multi-namespace SQLite shape inherits the\n * conflict-on-stale-coordinate behaviour the Postgres planner already\n * has.\n */\nexport function tableAt(\n storage: SqlStorage,\n namespaceId: string,\n tableName: string,\n): StorageTable | undefined {\n const ns = storage.namespaces[namespaceId];\n return ns !== undefined ? ns.entries.table?.[tableName] : undefined;\n}\n\n/**\n * Default namespace coordinate for an issue that does not carry one\n * explicitly. Hand-crafted unit-test issues fall back to `__unbound__`,\n * the only namespace any single-namespace contract carries —\n * verifier-emitted issues for legacy single-namespace contracts already\n * stamp this id explicitly. Typed structurally so issue variants\n * without a `namespaceId` slot flow through to the same fallback.\n */\nexport function resolveNamespaceIdForIssue(issue: { readonly namespaceId?: string }): string {\n return issue.namespaceId ?? UNBOUND_NAMESPACE_ID;\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<\n string,\n { issues: SchemaIssue[]; hasDestructive: boolean; namespaceId: string }\n >();\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, {\n issues: [issue],\n hasDestructive: cls === 'destructive',\n namespaceId: resolveNamespaceIdForIssue(issue),\n });\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 = tableAt(ctx.toContract.storage, entry.namespaceId, 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.source.columns.join(',');\n if (seenIndexColumnKeys.has(key)) continue;\n seenIndexColumnKeys.add(key);\n indexes.push({\n name: defaultIndexName(tableName, fk.source.columns),\n columns: fk.source.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 namespaceId = resolveNamespaceIdForIssue(issue);\n const column = tableAt(ctx.toContract.storage, namespaceId, 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, JsonValue } 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 type { CodecRef, DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';\nimport {\n DdlColumn,\n ForeignKeyConstraint,\n FunctionColumnDefault,\n LiteralColumnDefault,\n PrimaryKeyConstraint,\n UniqueConstraint,\n} from '@prisma-next/sql-relational-core/ast';\nimport { defaultIndexName } from '@prisma-next/sql-schema-ir/naming';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport { CONTROL_TABLE_NAMES } from '../control-tables';\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 resolveColumnTypeMetadata,\n} from './planner-ddl-builders';\nimport {\n type CallMigrationStrategy,\n resolveNamespaceIdForIssue,\n type StrategyContext,\n sqlitePlannerStrategies,\n tableAt,\n} from './planner-strategies';\n\nexport type { CallMigrationStrategy, StrategyContext };\n\n// ============================================================================\n// Issue kind ordering (dependency order)\n// ============================================================================\n\nconst ISSUE_KIND_ORDER: Record<string, number> = {\n // 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(\n column,\n blindCast<\n Record<string, StorageTypeInstance>,\n 'buildColumnTypeSql declares its storageTypes parameter as mutable Record while the planner stores it readonly; the helper does not mutate, so the readonly→mutable narrowing is sound'\n >(storageTypes),\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>>,\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.source.columns,\n references: { table: fk.target.tableName, columns: fk.target.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// StorageTable / StorageColumn → DdlColumn[] + DdlTableConstraint[] (for CreateTableCall)\n// ============================================================================\n\nfunction sqliteDefaultToDdlColumnDefault(\n columnDefault: StorageColumn['default'],\n): DdlColumn['default'] {\n if (!columnDefault) return undefined;\n switch (columnDefault.kind) {\n case 'literal':\n return new LiteralColumnDefault(columnDefault.value);\n case 'function':\n // `autoincrement()` is not a DEFAULT clause — SQLite encodes it as\n // `INTEGER PRIMARY KEY AUTOINCREMENT` inline on the column. Skip it\n // here; the renderer also has a defensive guard for the same case.\n if (columnDefault.expression === 'autoincrement()') return undefined;\n return new FunctionColumnDefault(columnDefault.expression);\n default: {\n const exhaustive: never = columnDefault;\n throw new Error(\n `sqliteDefaultToDdlColumnDefault: unhandled kind \"${blindCast<{ kind: string }, 'exhaustiveness: surface the unhandled default kind'>(exhaustive).kind}\"`,\n );\n }\n }\n}\n\n/**\n * Converts a `StorageTable` to the `DdlColumn[]` + `DdlTableConstraint[]`\n * pair used by `CreateTableCall`. This is the structured form consumed by\n * the DDL lowering path; `toTableSpec` / `toColumnSpec` remain in use for\n * `RecreateTableCall` and `AddColumnCall` (Phase 2).\n */\nexport function tableToDdlParts(\n table: StorageTable,\n storageTypes: Record<string, StorageTypeInstance>,\n): { columns: DdlColumn[]; constraints: DdlTableConstraint[] } {\n const columns: DdlColumn[] = Object.entries(table.columns).map(([name, column]) => {\n const inlineAutoincrement = isInlineAutoincrementPrimaryKey(table, name);\n const typeSql = buildColumnTypeSql(\n column,\n blindCast<\n Record<string, StorageTypeInstance>,\n 'buildColumnTypeSql declares its storageTypes parameter as mutable Record while the planner stores it readonly; the helper does not mutate, so the readonly→mutable narrowing is sound'\n >(storageTypes),\n );\n\n if (inlineAutoincrement) {\n // `DdlColumn` has no SQLite-specific autoincrement flag, so the full\n // `PRIMARY KEY AUTOINCREMENT` clause is embedded in the `type` string.\n // The DDL renderer (`ddl-renderer.ts`) substring-detects `AUTOINCREMENT`\n // to suppress the normal NOT NULL / PRIMARY KEY / DEFAULT clause rendering\n // and emit the entire type string verbatim. Both sites must stay in sync.\n // The structural fix (a SQLite-specific column option) is tracked in TML-2866.\n return new DdlColumn({ name, type: `${typeSql} PRIMARY KEY AUTOINCREMENT` });\n }\n const colDefault = sqliteDefaultToDdlColumnDefault(column.default);\n const resolved = resolveColumnTypeMetadata(\n column,\n blindCast<\n Record<string, StorageTypeInstance>,\n 'resolveColumnTypeMetadata declares its storageTypes parameter as mutable Record while the planner stores it readonly; the helper does not mutate, so the readonly→mutable narrowing is sound'\n >(storageTypes),\n );\n const codecRef: CodecRef | undefined = resolved.codecId\n ? {\n codecId: resolved.codecId,\n ...(resolved.typeParams !== undefined\n ? {\n typeParams: blindCast<\n JsonValue,\n 'resolved.typeParams is JsonValue-shaped storage metadata; the narrowed (non-undefined) value lands in CodecRef.typeParams which is JsonValue'\n >(resolved.typeParams),\n }\n : {}),\n }\n : undefined;\n return new DdlColumn({\n name,\n type: typeSql,\n ...(!column.nullable ? { notNull: true } : {}),\n ...(colDefault !== undefined ? { default: colDefault } : {}),\n ...(codecRef !== undefined ? { codecRef } : {}),\n });\n });\n\n const constraints: DdlTableConstraint[] = [];\n\n const hasInlinePk = Object.entries(table.columns).some(([name]) =>\n isInlineAutoincrementPrimaryKey(table, name),\n );\n if (table.primaryKey && !hasInlinePk) {\n constraints.push(new PrimaryKeyConstraint({ columns: table.primaryKey.columns }));\n }\n\n for (const u of table.uniques) {\n constraints.push(\n new UniqueConstraint({\n columns: u.columns,\n ...(u.name !== undefined ? { name: u.name } : {}),\n }),\n );\n }\n\n for (const fk of table.foreignKeys) {\n if (fk.constraint === false) continue;\n constraints.push(\n new ForeignKeyConstraint({\n columns: fk.source.columns,\n refTable: fk.target.tableName,\n refColumns: fk.target.columns,\n ...ifDefined('name', fk.name),\n ...ifDefined('onDelete', fk.onDelete),\n ...ifDefined('onUpdate', fk.onUpdate),\n }),\n );\n }\n\n return { columns, constraints };\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 namespaceId = resolveNamespaceIdForIssue(issue);\n const contractTable = tableAt(ctx.toContract.storage, namespaceId, issue.table);\n if (!contractTable) {\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Table \"${issue.table}\" in namespace \"${namespaceId}\" reported missing but not found in destination contract`,\n ),\n );\n }\n const { columns: ddlColumns, constraints: ddlConstraints } = tableToDdlParts(\n contractTable,\n ctx.storageTypes,\n );\n const calls: SqliteOpFactoryCall[] = [\n new CreateTableCall(\n issue.table,\n ddlColumns,\n ddlConstraints.length > 0 ? ddlConstraints : undefined,\n ),\n ];\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.source.columns.join(','))) continue;\n const indexName = defaultIndexName(issue.table, fk.source.columns);\n calls.push(new CreateIndexCall(issue.table, indexName, fk.source.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 namespaceId = resolveNamespaceIdForIssue(issue);\n const contractTable2 = tableAt(ctx.toContract.storage, namespaceId, issue.table);\n const column = contractTable2?.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 = contractTable2;\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 namespaceId = resolveNamespaceIdForIssue(issue);\n const columns = issue.expected.split(', ');\n const contractTable = tableAt(ctx.toContract.storage, namespaceId, 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 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 type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\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(\n lowerer: ExecuteRequestLowerer,\n): SqliteMigrationPlanner {\n return new SqliteMigrationPlanner(lowerer);\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 readonly #lowerer: ExecuteRequestLowerer;\n\n constructor(lowerer: ExecuteRequestLowerer) {\n this.#lowerer = lowerer;\n }\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 undefined,\n this.#lowerer,\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 this.#lowerer,\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,SAAgB,QACd,SACA,aACA,WAC0B;CAC1B,MAAM,KAAK,QAAQ,WAAW;CAC9B,OAAO,OAAO,KAAA,IAAY,GAAG,QAAQ,QAAQ,aAAa,KAAA;AAC5D;;;;;;;;;AAUA,SAAgB,2BAA2B,OAAkD;CAC3F,OAAO,MAAM,eAAe;AAC9B;AAkBA,MAAM,uBAAuB,IAAI,IAAyB,CAAC,oBAAoB,iBAAiB,CAAC;AAEjG,MAAM,0BAA0B,IAAI,IAAyB;CAC3D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,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,IAAI,GAAG,OAAO;CACjD,IAAI,wBAAwB,IAAI,MAAM,IAAI,GAAG,OAAO;CACpD,OAAO;AACT;;;;;;;AAQA,MAAa,yBAAgD,QAAQ,QAAQ;CAC3E,MAAM,0BAAU,IAAI,IAGlB;CACF,MAAM,2BAAW,IAAI,IAAiB;CAEtC,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,MAAM,cAAc,KAAK;EA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Ae,OAAO,OAAO;EAStC,MAAM,gBAAgB,yBAAyB;GAC7C,eAAe,QAAQ;GACvB,aAAa,QAAQ;GACrB;EACF,CAAC;EAID,MAAM,QAAQ,CAAC,GAAG,OAAO,MAAM,OAAO,GAAG,aAAa;EAEtD,MAAM,cAA8C;GAClD,aAAa,QAAQ,SAAS,QAAQ;GACtC,GAAI,QAAQ,SAAS,gBAAgB,KAAA,IACjC,EAAE,aAAa,QAAQ,SAAS,YAAY,IAC5C,CAAC;EACP;EAEA,OAAO;GACL,MAAM;GACN,MAAM,IAAI,oCACR,OACA;IACE,MAAM,QAAQ,cAAc,QAAQ,eAAe;IACnD,IAAI,QAAQ,SAAS,QAAQ;GAC/B,GACA,QAAQ,SACR,aACA,KAAKA,QACP;EACF;CACF;CAEA,qBAA6B,QAAkE;EAC7F,IAAI,CAAC,OAAO,wBAAwB,SAAS,UAAU,GACrD,OAAO,eAAe,CACpB;GACE,MAAM;GACN,SAAS;GACT,KAAK;EACP,CACF,CAAC;EAEH,OAAO;CACT;CAEA,oBAA4B,SAAiE;EAC3F,MAAM,UAAU,QAAQ,OAAO;EAC/B,MAAM,SAAS,QAAQ,SAAS,UAAU,KAAK,QAAQ,SAAS,aAAa;EAU7E,OATqB,gBAAgB;GACnC,UAAU,QAAQ;GAClB,QAAQ,QAAQ;GAChB;GACA,sCAAsB,IAAI,IAAI;GAC9B,qBAAqB,QAAQ;GAC7B,kBAAkB;GAClB,qBAAqB;EACvB,CACkB,CAAC,CAAC,OAAO;CAC7B;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { t as renderOps } from "./render-ops-BDW2tUeR.mjs";
2
- import { t as SqliteMigration } from "./sqlite-migration-DhW4ycZV.mjs";
2
+ import { t as SqliteMigration } from "./sqlite-migration-A0rwqPOG.mjs";
3
3
  import { renderImports } from "@prisma-next/ts-render";
4
4
  import { detectScaffoldRuntime, shebangLineFor } from "@prisma-next/migration-tools/migration-ts";
5
5
  //#region src/core/migrations/render-typescript.ts
@@ -108,4 +108,4 @@ var TypeScriptRenderableSqliteMigration = class extends SqliteMigration {
108
108
  //#endregion
109
109
  export { TypeScriptRenderableSqliteMigration as t };
110
110
 
111
- //# sourceMappingURL=planner-produced-sqlite-migration-CyyvoPmm.mjs.map
111
+ //# sourceMappingURL=planner-produced-sqlite-migration-0xPEm3R1.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"planner-produced-sqlite-migration-CyyvoPmm.mjs","names":["#calls","#meta","#destination","#spaceId","#lowerer","#operationsCache"],"sources":["../src/core/migrations/render-typescript.ts","../src/core/migrations/planner-produced-sqlite-migration.ts"],"sourcesContent":["/**\n * Polymorphic TypeScript emitter for the SQLite migration IR. Mirrors the\n * Postgres `render-typescript.ts` — different base-class + factory module\n * specifier, same overall shape.\n */\n\nimport type { OpFactoryCall } from '@prisma-next/framework-components/control';\nimport { detectScaffoldRuntime, shebangLineFor } from '@prisma-next/migration-tools/migration-ts';\nimport { type ImportRequirement, renderImports } from '@prisma-next/ts-render';\n\nexport interface RenderMigrationMeta {\n readonly from: string | null;\n readonly to: string;\n}\n\n/**\n * Always-present base imports for the rendered scaffold. Both come from\n * `@prisma-next/sqlite/migration` so an authored SQLite\n * `migration.ts` only needs a single dependency for its base class and\n * its CLI entrypoint. Mirrors Postgres's `BASE_IMPORTS`.\n *\n * - `Migration` — the facade re-export fixes the `SqlMigration`\n * generic to `SqlitePlanTargetDetails` and the abstract `targetId` to\n * `'sqlite'`.\n * - `MigrationCLI` — the migration-file CLI entrypoint, re-exported from\n * `@prisma-next/cli/migration-cli`. Loads `prisma-next.config.ts`,\n * assembles a `ControlStack`, and instantiates the migration class.\n */\nconst BASE_IMPORTS: readonly ImportRequirement[] = [\n { moduleSpecifier: '@prisma-next/sqlite/migration', symbol: 'Migration' },\n { moduleSpecifier: '@prisma-next/sqlite/migration', symbol: 'MigrationCLI' },\n];\n\nexport function renderCallsToTypeScript(\n calls: ReadonlyArray<OpFactoryCall>,\n meta: RenderMigrationMeta,\n): string {\n const imports = buildImports(calls);\n const operationsBody = calls.map((c) => c.renderTypeScript()).join(',\\n');\n\n return [\n shebangLineFor(detectScaffoldRuntime()),\n imports,\n '',\n 'export default class M extends Migration {',\n buildDescribeMethod(meta),\n ' override get operations() {',\n ' return [',\n indent(operationsBody, 6),\n ' ];',\n ' }',\n '}',\n '',\n 'MigrationCLI.run(import.meta.url, M);',\n '',\n ].join('\\n');\n}\n\nfunction buildImports(calls: ReadonlyArray<OpFactoryCall>): string {\n const requirements: ImportRequirement[] = [...BASE_IMPORTS];\n for (const call of calls) {\n for (const req of call.importRequirements()) {\n requirements.push(req);\n }\n }\n return renderImports(requirements);\n}\n\nfunction buildDescribeMethod(meta: RenderMigrationMeta): string {\n const lines: string[] = [];\n lines.push(' override describe() {');\n lines.push(' return {');\n lines.push(` from: ${JSON.stringify(meta.from)},`);\n lines.push(` to: ${JSON.stringify(meta.to)},`);\n lines.push(' };');\n lines.push(' }');\n lines.push('');\n return lines.join('\\n');\n}\n\nfunction indent(text: string, spaces: number): string {\n const pad = ' '.repeat(spaces);\n return text\n .split('\\n')\n .map((line) => (line.trim() ? `${pad}${line}` : line))\n .join('\\n');\n}\n","import type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport type {\n MigrationPlanWithAuthoringSurface,\n OpFactoryCall,\n} from '@prisma-next/framework-components/control';\nimport type { MigrationMeta } from '@prisma-next/migration-tools/migration';\nimport type { SqlitePlanTargetDetails } from './planner-target-details';\nimport { renderOps } from './render-ops';\nimport { renderCallsToTypeScript } from './render-typescript';\nimport { SqliteMigration } from './sqlite-migration';\n\ntype Op = SqlMigrationPlanOperation<SqlitePlanTargetDetails>;\n\nexport interface SqliteMigrationDestinationInfo {\n readonly storageHash: string;\n readonly profileHash?: string;\n}\n\nexport class TypeScriptRenderableSqliteMigration\n extends SqliteMigration\n implements MigrationPlanWithAuthoringSurface\n{\n readonly #calls: readonly OpFactoryCall[];\n readonly #meta: MigrationMeta;\n readonly #destination: SqliteMigrationDestinationInfo;\n readonly #spaceId: string;\n readonly #lowerer: ExecuteRequestLowerer | undefined;\n #operationsCache: readonly (Op | Promise<Op>)[] | undefined;\n\n constructor(\n calls: readonly OpFactoryCall[],\n meta: MigrationMeta,\n spaceId: string,\n destination?: SqliteMigrationDestinationInfo,\n lowerer?: ExecuteRequestLowerer,\n ) {\n super();\n this.#calls = calls;\n this.#meta = meta;\n this.#spaceId = spaceId;\n this.#destination = destination ?? { storageHash: meta.to };\n this.#lowerer = lowerer;\n }\n\n override get operations(): readonly (Op | Promise<Op>)[] {\n this.#operationsCache ??= renderOps(this.#calls, this.#lowerer);\n return this.#operationsCache;\n }\n\n override describe(): MigrationMeta {\n return this.#meta;\n }\n\n override get destination(): SqliteMigrationDestinationInfo {\n return this.#destination;\n }\n\n /**\n * Contract space this planner-produced plan applies to. Threaded\n * from {@link SqlMigrationPlannerPlanOptions.spaceId} so the runner\n * keys the marker row by the right space when executing the plan.\n */\n get spaceId(): string {\n return this.#spaceId;\n }\n\n renderTypeScript(): string {\n return renderCallsToTypeScript(this.#calls, {\n from: this.#meta.from,\n to: this.#meta.to,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4BA,MAAM,eAA6C,CACjD;CAAE,iBAAiB;CAAiC,QAAQ;AAAY,GACxE;CAAE,iBAAiB;CAAiC,QAAQ;AAAe,CAC7E;AAEA,SAAgB,wBACd,OACA,MACQ;CACR,MAAM,UAAU,aAAa,KAAK;CAClC,MAAM,iBAAiB,MAAM,KAAK,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC,KAAK,KAAK;CAExE,OAAO;EACL,eAAe,sBAAsB,CAAC;EACtC;EACA;EACA;EACA,oBAAoB,IAAI;EACxB;EACA;EACA,OAAO,gBAAgB,CAAC;EACxB;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;AAEA,SAAS,aAAa,OAA6C;CACjE,MAAM,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KAAKA,MAAM;EACjB,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"planner-produced-sqlite-migration-0xPEm3R1.mjs","names":["#calls","#meta","#destination","#spaceId","#lowerer","#operationsCache"],"sources":["../src/core/migrations/render-typescript.ts","../src/core/migrations/planner-produced-sqlite-migration.ts"],"sourcesContent":["/**\n * Polymorphic TypeScript emitter for the SQLite migration IR. Mirrors the\n * Postgres `render-typescript.ts` — different base-class + factory module\n * specifier, same overall shape.\n */\n\nimport type { OpFactoryCall } from '@prisma-next/framework-components/control';\nimport { detectScaffoldRuntime, shebangLineFor } from '@prisma-next/migration-tools/migration-ts';\nimport { type ImportRequirement, renderImports } from '@prisma-next/ts-render';\n\nexport interface RenderMigrationMeta {\n readonly from: string | null;\n readonly to: string;\n}\n\n/**\n * Always-present base imports for the rendered scaffold. Both come from\n * `@prisma-next/sqlite/migration` so an authored SQLite\n * `migration.ts` only needs a single dependency for its base class and\n * its CLI entrypoint. Mirrors Postgres's `BASE_IMPORTS`.\n *\n * - `Migration` — the facade re-export fixes the `SqlMigration`\n * generic to `SqlitePlanTargetDetails` and the abstract `targetId` to\n * `'sqlite'`.\n * - `MigrationCLI` — the migration-file CLI entrypoint, re-exported from\n * `@prisma-next/cli/migration-cli`. Loads `prisma-next.config.ts`,\n * assembles a `ControlStack`, and instantiates the migration class.\n */\nconst BASE_IMPORTS: readonly ImportRequirement[] = [\n { moduleSpecifier: '@prisma-next/sqlite/migration', symbol: 'Migration' },\n { moduleSpecifier: '@prisma-next/sqlite/migration', symbol: 'MigrationCLI' },\n];\n\nexport function renderCallsToTypeScript(\n calls: ReadonlyArray<OpFactoryCall>,\n meta: RenderMigrationMeta,\n): string {\n const imports = buildImports(calls);\n const operationsBody = calls.map((c) => c.renderTypeScript()).join(',\\n');\n\n return [\n shebangLineFor(detectScaffoldRuntime()),\n imports,\n '',\n 'export default class M extends Migration {',\n buildDescribeMethod(meta),\n ' override get operations() {',\n ' return [',\n indent(operationsBody, 6),\n ' ];',\n ' }',\n '}',\n '',\n 'MigrationCLI.run(import.meta.url, M);',\n '',\n ].join('\\n');\n}\n\nfunction buildImports(calls: ReadonlyArray<OpFactoryCall>): string {\n const requirements: ImportRequirement[] = [...BASE_IMPORTS];\n for (const call of calls) {\n for (const req of call.importRequirements()) {\n requirements.push(req);\n }\n }\n return renderImports(requirements);\n}\n\nfunction buildDescribeMethod(meta: RenderMigrationMeta): string {\n const lines: string[] = [];\n lines.push(' override describe() {');\n lines.push(' return {');\n lines.push(` from: ${JSON.stringify(meta.from)},`);\n lines.push(` to: ${JSON.stringify(meta.to)},`);\n lines.push(' };');\n lines.push(' }');\n lines.push('');\n return lines.join('\\n');\n}\n\nfunction indent(text: string, spaces: number): string {\n const pad = ' '.repeat(spaces);\n return text\n .split('\\n')\n .map((line) => (line.trim() ? `${pad}${line}` : line))\n .join('\\n');\n}\n","import type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport type {\n MigrationPlanWithAuthoringSurface,\n OpFactoryCall,\n} from '@prisma-next/framework-components/control';\nimport type { MigrationMeta } from '@prisma-next/migration-tools/migration';\nimport type { SqlitePlanTargetDetails } from './planner-target-details';\nimport { renderOps } from './render-ops';\nimport { renderCallsToTypeScript } from './render-typescript';\nimport { SqliteMigration } from './sqlite-migration';\n\ntype Op = SqlMigrationPlanOperation<SqlitePlanTargetDetails>;\n\nexport interface SqliteMigrationDestinationInfo {\n readonly storageHash: string;\n readonly profileHash?: string;\n}\n\nexport class TypeScriptRenderableSqliteMigration\n extends SqliteMigration\n implements MigrationPlanWithAuthoringSurface\n{\n readonly #calls: readonly OpFactoryCall[];\n readonly #meta: MigrationMeta;\n readonly #destination: SqliteMigrationDestinationInfo;\n readonly #spaceId: string;\n readonly #lowerer: ExecuteRequestLowerer | undefined;\n #operationsCache: readonly (Op | Promise<Op>)[] | undefined;\n\n constructor(\n calls: readonly OpFactoryCall[],\n meta: MigrationMeta,\n spaceId: string,\n destination?: SqliteMigrationDestinationInfo,\n lowerer?: ExecuteRequestLowerer,\n ) {\n super();\n this.#calls = calls;\n this.#meta = meta;\n this.#spaceId = spaceId;\n this.#destination = destination ?? { storageHash: meta.to };\n this.#lowerer = lowerer;\n }\n\n override get operations(): readonly (Op | Promise<Op>)[] {\n this.#operationsCache ??= renderOps(this.#calls, this.#lowerer);\n return this.#operationsCache;\n }\n\n override describe(): MigrationMeta {\n return this.#meta;\n }\n\n override get destination(): SqliteMigrationDestinationInfo {\n return this.#destination;\n }\n\n /**\n * Contract space this planner-produced plan applies to. Threaded\n * from {@link SqlMigrationPlannerPlanOptions.spaceId} so the runner\n * keys the marker row by the right space when executing the plan.\n */\n get spaceId(): string {\n return this.#spaceId;\n }\n\n renderTypeScript(): string {\n return renderCallsToTypeScript(this.#calls, {\n from: this.#meta.from,\n to: this.#meta.to,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4BA,MAAM,eAA6C,CACjD;CAAE,iBAAiB;CAAiC,QAAQ;AAAY,GACxE;CAAE,iBAAiB;CAAiC,QAAQ;AAAe,CAC7E;AAEA,SAAgB,wBACd,OACA,MACQ;CACR,MAAM,UAAU,aAAa,KAAK;CAClC,MAAM,iBAAiB,MAAM,KAAK,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC,KAAK,KAAK;CAExE,OAAO;EACL,eAAe,sBAAsB,CAAC;EACtC;EACA;EACA;EACA,oBAAoB,IAAI;EACxB;EACA;EACA,OAAO,gBAAgB,CAAC;EACxB;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;AAEA,SAAS,aAAa,OAA6C;CACjE,MAAM,eAAoC,CAAC,GAAG,YAAY;CAC1D,KAAK,MAAM,QAAQ,OACjB,KAAK,MAAM,OAAO,KAAK,mBAAmB,GACxC,aAAa,KAAK,GAAG;CAGzB,OAAO,cAAc,YAAY;AACnC;AAEA,SAAS,oBAAoB,MAAmC;CAC9D,MAAM,QAAkB,CAAC;CACzB,MAAM,KAAK,yBAAyB;CACpC,MAAM,KAAK,cAAc;CACzB,MAAM,KAAK,eAAe,KAAK,UAAU,KAAK,IAAI,EAAE,EAAE;CACtD,MAAM,KAAK,aAAa,KAAK,UAAU,KAAK,EAAE,EAAE,EAAE;CAClD,MAAM,KAAK,QAAQ;CACnB,MAAM,KAAK,KAAK;CAChB,MAAM,KAAK,EAAE;CACb,OAAO,MAAM,KAAK,IAAI;AACxB;AAEA,SAAS,OAAO,MAAc,QAAwB;CACpD,MAAM,MAAM,IAAI,OAAO,MAAM;CAC7B,OAAO,KACJ,MAAM,IAAI,CAAC,CACX,KAAK,SAAU,KAAK,KAAK,IAAI,GAAG,MAAM,SAAS,IAAK,CAAC,CACrD,KAAK,IAAI;AACd;;;ACnEA,IAAa,sCAAb,cACU,gBAEV;CACE;CACA;CACA;CACA;CACA;CACA;CAEA,YACE,OACA,MACA,SACA,aACA,SACA;EACA,MAAM;EACN,KAAKA,SAAS;EACd,KAAKC,QAAQ;EACb,KAAKE,WAAW;EAChB,KAAKD,eAAe,eAAe,EAAE,aAAa,KAAK,GAAG;EAC1D,KAAKE,WAAW;CAClB;CAEA,IAAa,aAA4C;EACvD,KAAKC,qBAAqB,UAAU,KAAKL,QAAQ,KAAKI,QAAQ;EAC9D,OAAO,KAAKC;CACd;CAEA,WAAmC;EACjC,OAAO,KAAKJ;CACd;CAEA,IAAa,cAA8C;EACzD,OAAO,KAAKC;CACd;;;;;;CAOA,IAAI,UAAkB;EACpB,OAAO,KAAKC;CACd;CAEA,mBAA2B;EACzB,OAAO,wBAAwB,KAAKH,QAAQ;GAC1C,MAAM,KAAKC,MAAM;GACjB,IAAI,KAAKA,MAAM;EACjB,CAAC;CACH;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { t as SqlitePlanTargetDetails } from "./planner-target-details-xR6UfIcz.mjs";
2
- import { t as SqliteMigration } from "./sqlite-migration-CJrASAxf.mjs";
2
+ import { t as SqliteMigration } from "./sqlite-migration-DVfhQwN_.mjs";
3
3
  import { SqlMigrationPlanOperation } from "@prisma-next/family-sql/control";
4
4
  import { MigrationPlanWithAuthoringSurface, OpFactoryCall } from "@prisma-next/framework-components/control";
5
5
  import { ExecuteRequestLowerer } from "@prisma-next/family-sql/control-adapter";
@@ -27,4 +27,4 @@ declare class TypeScriptRenderableSqliteMigration extends SqliteMigration implem
27
27
  }
28
28
  //#endregion
29
29
  export { TypeScriptRenderableSqliteMigration as n, SqliteMigrationDestinationInfo as t };
30
- //# sourceMappingURL=planner-produced-sqlite-migration-BWpnDmhM.d.mts.map
30
+ //# sourceMappingURL=planner-produced-sqlite-migration-CpgsY-M9.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"planner-produced-sqlite-migration-BWpnDmhM.d.mts","names":[],"sources":["../src/core/migrations/planner-produced-sqlite-migration.ts"],"mappings":";;;;;;;;KAYK,EAAA,GAAK,yBAAyB,CAAC,uBAAA;AAAA,UAEnB,8BAAA;EAAA,SACN,WAAA;EAAA,SACA,WAAW;AAAA;AAAA,cAGT,mCAAA,SACH,eAAA,YACG,iCAAA;EAAA;cAUT,KAAA,WAAgB,aAAA,IAChB,IAAA,EAAM,aAAA,EACN,OAAA,UACA,WAAA,GAAc,8BAAA,EACd,OAAA,GAAU,qBAAA;EAAA,IAUC,UAAA,cAAwB,EAAA,GAAK,OAAA,CAAQ,EAAA;EAKzC,QAAA,IAAY,aAAA;EAAA,IAIR,WAAA,IAAe,8BAAA;EAtCR;AAGtB;;;;EAHsB,IA+ChB,OAAA;EAIJ,gBAAA;AAAA"}
1
+ {"version":3,"file":"planner-produced-sqlite-migration-CpgsY-M9.d.mts","names":[],"sources":["../src/core/migrations/planner-produced-sqlite-migration.ts"],"mappings":";;;;;;;;KAYK,EAAA,GAAK,yBAAyB,CAAC,uBAAA;AAAA,UAEnB,8BAAA;EAAA,SACN,WAAA;EAAA,SACA,WAAW;AAAA;AAAA,cAGT,mCAAA,SACH,eAAA,YACG,iCAAA;EAAA;cAUT,KAAA,WAAgB,aAAA,IAChB,IAAA,EAAM,aAAA,EACN,OAAA,UACA,WAAA,GAAc,8BAAA,EACd,OAAA,GAAU,qBAAA;EAAA,IAUC,UAAA,cAAwB,EAAA,GAAK,OAAA,CAAQ,EAAA;EAKzC,QAAA,IAAY,aAAA;EAAA,IAIR,WAAA,IAAe,8BAAA;EAtCR;AAGtB;;;;EAHsB,IA+ChB,OAAA;EAIJ,gBAAA;AAAA"}
@@ -1,2 +1,2 @@
1
- import { n as TypeScriptRenderableSqliteMigration, t as SqliteMigrationDestinationInfo } from "./planner-produced-sqlite-migration-BWpnDmhM.mjs";
1
+ import { n as TypeScriptRenderableSqliteMigration, t as SqliteMigrationDestinationInfo } from "./planner-produced-sqlite-migration-CpgsY-M9.mjs";
2
2
  export { type SqliteMigrationDestinationInfo, TypeScriptRenderableSqliteMigration };
@@ -1,2 +1,2 @@
1
- import { t as TypeScriptRenderableSqliteMigration } from "./planner-produced-sqlite-migration-CyyvoPmm.mjs";
1
+ import { t as TypeScriptRenderableSqliteMigration } from "./planner-produced-sqlite-migration-0xPEm3R1.mjs";
2
2
  export { TypeScriptRenderableSqliteMigration };
@@ -1,5 +1,5 @@
1
1
  import { t as SqlitePlanTargetDetails } from "./planner-target-details-xR6UfIcz.mjs";
2
- import { n as TypeScriptRenderableSqliteMigration } from "./planner-produced-sqlite-migration-BWpnDmhM.mjs";
2
+ import { n as TypeScriptRenderableSqliteMigration } from "./planner-produced-sqlite-migration-CpgsY-M9.mjs";
3
3
  import { MigrationOperationPolicy, SqlMigrationPlanner, SqlPlannerFailureResult } from "@prisma-next/family-sql/control";
4
4
  import { MigrationPlanner, MigrationScaffoldContext } from "@prisma-next/framework-components/control";
5
5
  import { Contract } from "@prisma-next/contract/types";
package/dist/planner.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { n as createSqliteMigrationPlanner, t as SqliteMigrationPlanner } from "./planner-jMHqfl1A.mjs";
1
+ import { n as createSqliteMigrationPlanner, t as SqliteMigrationPlanner } from "./planner-Ciq8p_dL.mjs";
2
2
  export { SqliteMigrationPlanner, createSqliteMigrationPlanner };
@@ -1 +1 @@
1
- {"version":3,"file":"shared-Dhc8mLK1.d.mts","names":[],"sources":["../src/core/migrations/operations/shared.ts"],"mappings":";;;;;KAMY,EAAA,GAAK,yBAAyB,CAAC,uBAAA;;AAAuB;AAsBlE;;;;;;;;;;AAKwC;AAGxC;;;UARiB,gBAAA;EAAA,SACN,IAAA;EAAA,SACA,OAAA;EAAA,SACA,UAAA;EAAA,SACA,QAAA;EAAA,SACA,6BAAA;AAAA;AAAA,UAGM,oBAAA;EAAA,SACN,OAAO;AAAA;AAAA,UAGD,gBAAA;EAAA,SACN,OAAA;EAAA,SACA,IAAI;AAAA;AAAA,UAGE,oBAAA;EAAA,SACN,OAAA;EAAA,SACA,UAAA;IAAA,SACE,KAAA;IAAA,SACA,OAAA;EAAA;EAAA,SAEF,IAAA;EAAA,SACA,QAAA,GAAW,iBAAA;EAAA,SACX,QAAA,GAAW,iBAAiB;EAAA,SAC5B,UAAA;AAAA;;;;;UAOM,eAAA;EAAA,SACN,OAAA,WAAkB,gBAAA;EAAA,SAClB,UAAA,GAAa,oBAAA;EAAA,SACb,OAAA,YAAmB,gBAAA;EAAA,SACnB,WAAA,YAAuB,oBAAA;AAAA;;;;;;UAQjB,eAAA;EAAA,SACN,IAAA;EAAA,SACA,OAAO;AAAA"}
1
+ {"version":3,"file":"shared-Dhc8mLK1.d.mts","names":[],"sources":["../src/core/migrations/operations/shared.ts"],"mappings":";;;;;KAUY,EAAA,GAAK,yBAAyB,CAAC,uBAAA;AAA3C;;;;AAAkE;AA0BlE;;;;;;;;;;AAKwC;AA/BxC,UA0BiB,gBAAA;EAAA,SACN,IAAA;EAAA,SACA,OAAA;EAAA,SACA,UAAA;EAAA,SACA,QAAA;EAAA,SACA,6BAAA;AAAA;AAAA,UAGM,oBAAA;EAAA,SACN,OAAO;AAAA;AAAA,UAGD,gBAAA;EAAA,SACN,OAAA;EAAA,SACA,IAAI;AAAA;AAAA,UAGE,oBAAA;EAAA,SACN,OAAA;EAAA,SACA,UAAA;IAAA,SACE,KAAA;IAAA,SACA,OAAA;EAAA;EAAA,SAEF,IAAA;EAAA,SACA,QAAA,GAAW,iBAAA;EAAA,SACX,QAAA,GAAW,iBAAiB;EAAA,SAC5B,UAAA;AAAA;AAAU;AAOrB;;;AAPqB,UAOJ,eAAA;EAAA,SACN,OAAA,WAAkB,gBAAA;EAAA,SAClB,UAAA,GAAa,oBAAA;EAAA,SACb,OAAA,YAAmB,gBAAA;EAAA,SACnB,WAAA,YAAuB,oBAAA;AAAA;;;;;;UAQjB,eAAA;EAAA,SACN,IAAA;EAAA,SACA,OAAO;AAAA"}
@@ -1,4 +1,4 @@
1
- import { r as CreateTableCall } from "./op-factory-call-z4TT72k3.mjs";
1
+ import { a as DropColumnCall, l as RecreateTableCall, n as CreateIndexCall, o as DropIndexCall, r as CreateTableCall, s as DropTableCall, t as AddColumnCall } from "./op-factory-call-DmdfD1yd.mjs";
2
2
  import { blindCast } from "@prisma-next/utils/casts";
3
3
  import { Migration } from "@prisma-next/family-sql/migration";
4
4
  import { CliStructuredError } from "@prisma-next/errors/control";
@@ -39,35 +39,54 @@ function errorSqliteMigrationStackMissing() {
39
39
  * target-local identity.
40
40
  *
41
41
  * The constructor materializes a single SQLite `SqlControlAdapter` from
42
- * `stack.adapter.create(stack)` and stores it; the protected `createTable`
43
- * instance method forwards to `CreateTableCall` with that stored adapter,
44
- * so user migrations can write `this.createTable({...})` without threading
45
- * the adapter through every call.
42
+ * `stack.adapter.create(stack)` and stores it; the protected instance methods
43
+ * forward to the corresponding `*Call` with that stored adapter, so user
44
+ * migrations can write `this.createTable({...})` without threading the adapter
45
+ * through every call.
46
46
  */
47
47
  var SqliteMigration = class extends Migration {
48
48
  targetId = "sqlite";
49
49
  /**
50
50
  * Materialized SQLite control adapter, created once per migration
51
51
  * instance from the injected stack. `undefined` only when the migration
52
- * was instantiated without a stack (test fixtures); `createTable`
53
- * throws in that case to surface the misuse.
52
+ * was instantiated without a stack (test fixtures); the operation methods
53
+ * throw in that case to surface the misuse.
54
54
  */
55
55
  controlAdapter;
56
56
  constructor(stack) {
57
57
  super(stack);
58
58
  this.controlAdapter = stack?.adapter ? blindCast(stack.adapter.create(stack)) : void 0;
59
59
  }
60
- /**
61
- * Emit a `CREATE TABLE` migration operation. Builds a typed DDL node from
62
- * the supplied options and lowers it through the stored control adapter.
63
- * Throws if no adapter is present (i.e. migration instantiated without a stack).
64
- */
65
60
  createTable(options) {
66
61
  if (!this.controlAdapter) throw errorSqliteMigrationStackMissing();
67
62
  return new CreateTableCall(options.table, options.columns, options.constraints).toOp(this.controlAdapter);
68
63
  }
64
+ dropTable(options) {
65
+ if (!this.controlAdapter) throw errorSqliteMigrationStackMissing();
66
+ return new DropTableCall(options.table).toOp(this.controlAdapter);
67
+ }
68
+ addColumn(options) {
69
+ if (!this.controlAdapter) throw errorSqliteMigrationStackMissing();
70
+ return new AddColumnCall(options.table, options.column).toOp(this.controlAdapter);
71
+ }
72
+ dropColumn(options) {
73
+ if (!this.controlAdapter) throw errorSqliteMigrationStackMissing();
74
+ return new DropColumnCall(options.table, options.column).toOp(this.controlAdapter);
75
+ }
76
+ createIndex(options) {
77
+ if (!this.controlAdapter) throw errorSqliteMigrationStackMissing();
78
+ return new CreateIndexCall(options.table, options.index, options.columns).toOp(this.controlAdapter);
79
+ }
80
+ dropIndex(options) {
81
+ if (!this.controlAdapter) throw errorSqliteMigrationStackMissing();
82
+ return new DropIndexCall(options.table, options.index).toOp(this.controlAdapter);
83
+ }
84
+ recreateTable(options) {
85
+ if (!this.controlAdapter) throw errorSqliteMigrationStackMissing();
86
+ return new RecreateTableCall(options).toOp(this.controlAdapter);
87
+ }
69
88
  };
70
89
  //#endregion
71
90
  export { SqliteMigration as t };
72
91
 
73
- //# sourceMappingURL=sqlite-migration-DhW4ycZV.mjs.map
92
+ //# sourceMappingURL=sqlite-migration-A0rwqPOG.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite-migration-A0rwqPOG.mjs","names":["SqlMigration"],"sources":["../src/core/errors.ts","../src/core/migrations/sqlite-migration.ts"],"sourcesContent":["import { CliStructuredError } from '@prisma-next/errors/control';\n\n/**\n * A `SqliteMigration` instance method that needs the materialized control\n * adapter (currently only `this.createTable(...)`) was invoked, but the\n * migration was constructed without a `ControlStack`. Concrete authoring\n * usage always goes through the migration CLI entrypoint, which assembles\n * a stack from the loaded `prisma-next.config.ts`; reaching this error\n * means a test fixture or ad-hoc consumer instantiated `SqliteMigration`\n * with the no-arg form (legal for `operations` / `describe` introspection\n * only).\n *\n * Distinct from `PN-MIG-2001` (placeholder not filled) because the missing\n * input is the stack itself, not the per-operation contract.\n *\n * Lives in `@prisma-next/target-sqlite/errors` rather than the shared\n * framework migration errors module because the failure is target-specific:\n * the contract it talks about (`SqliteMigration`, the SQLite control\n * adapter, the SQLite-target stack) only exists in this package.\n */\nexport function errorSqliteMigrationStackMissing(): CliStructuredError {\n return new CliStructuredError('2008', 'SqliteMigration.createTable requires a control adapter', {\n domain: 'MIG',\n why: 'SqliteMigration.createTable was invoked on an instance constructed without a ControlStack. The stored controlAdapter is undefined, so createTable cannot lower its DDL node.',\n fix: 'Construct the migration via the migration CLI entrypoint (which assembles a ControlStack from the loaded prisma-next.config.ts), or pass a ControlStack containing a SQLite adapter to the migration constructor in test fixtures.',\n meta: {},\n });\n}\n","import type {\n MigrationOperationClass,\n SqlMigrationPlanOperation,\n} from '@prisma-next/family-sql/control';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport { Migration as SqlMigration } from '@prisma-next/family-sql/migration';\nimport type { ControlStack } from '@prisma-next/framework-components/control';\nimport type { DdlColumn, DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { errorSqliteMigrationStackMissing } from '../errors';\nimport {\n AddColumnCall,\n CreateIndexCall,\n CreateTableCall,\n DropColumnCall,\n DropIndexCall,\n DropTableCall,\n RecreateTableCall,\n} from './op-factory-call';\nimport type { SqliteColumnSpec, SqliteIndexSpec, SqliteTableSpec } from './operations/shared';\nimport type { SqlitePlanTargetDetails } from './planner-target-details';\n\ntype Op = SqlMigrationPlanOperation<SqlitePlanTargetDetails>;\n\n/**\n * Target-owned base class for SQLite migrations. Fixes the `SqlMigration`\n * generic to `SqlitePlanTargetDetails` and the abstract `targetId` to the\n * SQLite literal, so both user-authored migrations and renderer-generated\n * scaffolds can extend `SqliteMigration` directly without redeclaring\n * target-local identity.\n *\n * The constructor materializes a single SQLite `SqlControlAdapter` from\n * `stack.adapter.create(stack)` and stores it; the protected instance methods\n * forward to the corresponding `*Call` with that stored adapter, so user\n * migrations can write `this.createTable({...})` without threading the adapter\n * through every call.\n */\nexport abstract class SqliteMigration extends SqlMigration<SqlitePlanTargetDetails, 'sqlite'> {\n readonly targetId = 'sqlite' as const;\n\n /**\n * Materialized SQLite control adapter, created once per migration\n * instance from the injected stack. `undefined` only when the migration\n * was instantiated without a stack (test fixtures); the operation methods\n * throw in that case to surface the misuse.\n */\n protected readonly controlAdapter: SqlControlAdapter<'sqlite'> | undefined;\n\n constructor(stack?: ControlStack<'sql', 'sqlite'>) {\n super(stack);\n this.controlAdapter = stack?.adapter\n ? blindCast<\n SqlControlAdapter<'sqlite'>,\n 'The SQLite descriptor create() returns SqlControlAdapter<sqlite>; typed as wider ControlAdapterInstance at the framework boundary'\n >(stack.adapter.create(stack))\n : undefined;\n }\n\n protected createTable(options: {\n readonly table: string;\n readonly ifNotExists?: boolean;\n readonly columns: readonly DdlColumn[];\n readonly constraints?: readonly DdlTableConstraint[];\n }): Promise<Op> {\n if (!this.controlAdapter) {\n throw errorSqliteMigrationStackMissing();\n }\n return new CreateTableCall(options.table, options.columns, options.constraints).toOp(\n this.controlAdapter,\n );\n }\n\n protected dropTable(options: { readonly table: string }): Promise<Op> {\n if (!this.controlAdapter) {\n throw errorSqliteMigrationStackMissing();\n }\n return new DropTableCall(options.table).toOp(this.controlAdapter);\n }\n\n protected addColumn(options: {\n readonly table: string;\n readonly column: SqliteColumnSpec;\n }): Promise<Op> {\n if (!this.controlAdapter) {\n throw errorSqliteMigrationStackMissing();\n }\n return new AddColumnCall(options.table, options.column).toOp(this.controlAdapter);\n }\n\n protected dropColumn(options: { readonly table: string; readonly column: string }): Promise<Op> {\n if (!this.controlAdapter) {\n throw errorSqliteMigrationStackMissing();\n }\n return new DropColumnCall(options.table, options.column).toOp(this.controlAdapter);\n }\n\n protected createIndex(options: {\n readonly table: string;\n readonly index: string;\n readonly columns: readonly string[];\n }): Promise<Op> {\n if (!this.controlAdapter) {\n throw errorSqliteMigrationStackMissing();\n }\n return new CreateIndexCall(options.table, options.index, options.columns).toOp(\n this.controlAdapter,\n );\n }\n\n protected dropIndex(options: { readonly table: string; readonly index: string }): Promise<Op> {\n if (!this.controlAdapter) {\n throw errorSqliteMigrationStackMissing();\n }\n return new DropIndexCall(options.table, options.index).toOp(this.controlAdapter);\n }\n\n protected recreateTable(options: {\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 operationClass: MigrationOperationClass;\n }): Promise<Op> {\n if (!this.controlAdapter) {\n throw errorSqliteMigrationStackMissing();\n }\n return new RecreateTableCall(options).toOp(this.controlAdapter);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,mCAAuD;CACrE,OAAO,IAAI,mBAAmB,QAAQ,0DAA0D;EAC9F,QAAQ;EACR,KAAK;EACL,KAAK;EACL,MAAM,CAAC;CACT,CAAC;AACH;;;;;;;;;;;;;;;;ACUA,IAAsB,kBAAtB,cAA8CA,UAAgD;CAC5F,WAAoB;;;;;;;CAQpB;CAEA,YAAY,OAAuC;EACjD,MAAM,KAAK;EACX,KAAK,iBA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