@prisma-next/target-sqlite 0.10.0-dev.9 → 0.11.0-dev.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/control.mjs +1 -1
- package/dist/{op-factory-call-BRp16Nsr.mjs → op-factory-call-BnPhI25-.mjs} +2 -2
- package/dist/op-factory-call-BnPhI25-.mjs.map +1 -0
- package/dist/op-factory-call.mjs +1 -1
- package/dist/{planner-B1bodAgY.mjs → planner-B9-16QqD.mjs} +3 -3
- package/dist/{planner-B1bodAgY.mjs.map → planner-B9-16QqD.mjs.map} +1 -1
- package/dist/{planner-produced-sqlite-migration-C_TzWbT0.mjs → planner-produced-sqlite-migration-BqzfeOFu.mjs} +5 -5
- package/dist/planner-produced-sqlite-migration-BqzfeOFu.mjs.map +1 -0
- package/dist/planner-produced-sqlite-migration.mjs +1 -1
- package/dist/planner.mjs +1 -1
- package/package.json +18 -18
- package/src/core/migrations/op-factory-call.ts +1 -1
- package/src/core/migrations/render-typescript.ts +4 -4
- package/src/exports/migration.ts +3 -3
- package/dist/op-factory-call-BRp16Nsr.mjs.map +0 -1
- package/dist/planner-produced-sqlite-migration-C_TzWbT0.mjs.map +0 -1
package/dist/control.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { t as sqliteTargetDescriptorMeta } from "./descriptor-meta-CE2Kbn9b.mjs"
|
|
|
2
2
|
import { t as parseSqliteDefault } from "./default-normalizer-3Fccw7yw.mjs";
|
|
3
3
|
import { t as normalizeSqliteNativeType } from "./native-type-normalizer-BlN5XfD-.mjs";
|
|
4
4
|
import { d as renderDefaultLiteral } from "./tables-DGRRJasz.mjs";
|
|
5
|
-
import { n as createSqliteMigrationPlanner } from "./planner-
|
|
5
|
+
import { n as createSqliteMigrationPlanner } from "./planner-B9-16QqD.mjs";
|
|
6
6
|
import { a as buildLedgerInsertStatement, c as ensureMarkerTableStatement, i as MARKER_TABLE_NAME, l as readMarkerStatement, o as buildWriteMarkerStatements, s as ensureLedgerTableStatement } from "./statement-builders-Dne-LkAV.mjs";
|
|
7
7
|
import { contractToSchemaIR, runnerFailure, runnerSuccess } from "@prisma-next/family-sql/control";
|
|
8
8
|
import { SqlStorage } from "@prisma-next/sql-contract/types";
|
|
@@ -14,7 +14,7 @@ import { TsExpression, jsonToTsSource } from "@prisma-next/ts-render";
|
|
|
14
14
|
* TypeScript scaffold is fully self-contained and does not need access to a
|
|
15
15
|
* `storageTypes` map at runtime.
|
|
16
16
|
*/
|
|
17
|
-
const TARGET_MIGRATION_MODULE = "@prisma-next/
|
|
17
|
+
const TARGET_MIGRATION_MODULE = "@prisma-next/sqlite/migration";
|
|
18
18
|
var SqliteOpFactoryCallNode = class extends TsExpression {
|
|
19
19
|
importRequirements() {
|
|
20
20
|
return [{
|
|
@@ -276,4 +276,4 @@ var RawSqlCall = class extends SqliteOpFactoryCallNode {
|
|
|
276
276
|
//#endregion
|
|
277
277
|
export { DropColumnCall as a, RawSqlCall as c, DataTransformCall as i, RecreateTableCall as l, CreateIndexCall as n, DropIndexCall as o, CreateTableCall as r, DropTableCall as s, AddColumnCall as t };
|
|
278
278
|
|
|
279
|
-
//# sourceMappingURL=op-factory-call-
|
|
279
|
+
//# sourceMappingURL=op-factory-call-BnPhI25-.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"op-factory-call-BnPhI25-.mjs","names":[],"sources":["../src/core/migrations/op-factory-call.ts"],"sourcesContent":["/**\n * SQLite migration IR: one concrete `*Call` class per pure factory under\n * `operations/`, plus a shared `SqliteOpFactoryCallNode` abstract base.\n *\n * Each call class carries fully-resolved literal arguments (flat\n * `SqliteColumnSpec` / `SqliteTableSpec` etc.) — codec / `typeRef` / default\n * expansion happens upstream in the issue-planner / strategies, mirroring\n * the Postgres `ColumnSpec` pattern. As a result, `toOp()` and\n * `renderTypeScript()` both pass the same flat data through; the rendered\n * TypeScript scaffold is fully self-contained and does not need access to a\n * `storageTypes` map at runtime.\n */\n\nimport { errorUnfilledPlaceholder } from '@prisma-next/errors/migration';\nimport type {\n MigrationOperationClass,\n SqlMigrationPlanOperation,\n} from '@prisma-next/family-sql/control';\nimport type { OpFactoryCall as FrameworkOpFactoryCall } from '@prisma-next/framework-components/control';\nimport { type ImportRequirement, jsonToTsSource, TsExpression } from '@prisma-next/ts-render';\nimport { addColumn, dropColumn } from './operations/columns';\nimport { createIndex, dropIndex } from './operations/indexes';\nimport type { SqliteColumnSpec, SqliteIndexSpec, SqliteTableSpec } from './operations/shared';\nimport { createTable, dropTable, recreateTable } from './operations/tables';\nimport type { SqlitePlanTargetDetails } from './planner-target-details';\n\ntype Op = SqlMigrationPlanOperation<SqlitePlanTargetDetails>;\n\nconst TARGET_MIGRATION_MODULE = '@prisma-next/sqlite/migration';\n\nabstract class SqliteOpFactoryCallNode extends TsExpression implements FrameworkOpFactoryCall {\n abstract readonly factoryName: string;\n abstract readonly operationClass: MigrationOperationClass;\n abstract readonly label: string;\n abstract toOp(): Op;\n\n importRequirements(): readonly ImportRequirement[] {\n return [{ moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: this.factoryName }];\n }\n\n protected freeze(): void {\n Object.freeze(this);\n }\n}\n\n// ============================================================================\n// Table\n// ============================================================================\n\nexport class CreateTableCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'createTable' as const;\n readonly operationClass = 'additive' as const;\n readonly tableName: string;\n readonly spec: SqliteTableSpec;\n readonly label: string;\n\n constructor(tableName: string, spec: SqliteTableSpec) {\n super();\n this.tableName = tableName;\n this.spec = spec;\n this.label = `Create table ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return createTable(this.tableName, this.spec);\n }\n\n renderTypeScript(): string {\n return `createTable(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.spec)})`;\n }\n}\n\nexport class DropTableCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'dropTable' as const;\n readonly operationClass = 'destructive' as const;\n readonly tableName: string;\n readonly label: string;\n\n constructor(tableName: string) {\n super();\n this.tableName = tableName;\n this.label = `Drop table ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropTable(this.tableName);\n }\n\n renderTypeScript(): string {\n return `dropTable(${jsonToTsSource(this.tableName)})`;\n }\n}\n\nexport class RecreateTableCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'recreateTable' as const;\n readonly operationClass: MigrationOperationClass;\n readonly tableName: string;\n readonly contractTable: SqliteTableSpec;\n readonly schemaColumnNames: readonly string[];\n readonly indexes: readonly SqliteIndexSpec[];\n readonly summary: string;\n readonly postchecks: readonly { readonly description: string; readonly sql: string }[];\n readonly label: string;\n\n constructor(args: {\n tableName: string;\n contractTable: SqliteTableSpec;\n schemaColumnNames: readonly string[];\n indexes: readonly SqliteIndexSpec[];\n summary: string;\n postchecks: readonly { readonly description: string; readonly sql: string }[];\n operationClass: MigrationOperationClass;\n }) {\n super();\n this.tableName = args.tableName;\n this.contractTable = args.contractTable;\n this.schemaColumnNames = args.schemaColumnNames;\n this.indexes = args.indexes;\n this.summary = args.summary;\n this.postchecks = args.postchecks;\n this.operationClass = args.operationClass;\n this.label = `Recreate table ${args.tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return recreateTable({\n tableName: this.tableName,\n contractTable: this.contractTable,\n schemaColumnNames: this.schemaColumnNames,\n indexes: this.indexes,\n summary: this.summary,\n postchecks: this.postchecks,\n operationClass: this.operationClass,\n });\n }\n\n renderTypeScript(): string {\n const args = {\n tableName: this.tableName,\n contractTable: this.contractTable,\n schemaColumnNames: this.schemaColumnNames,\n indexes: this.indexes,\n summary: this.summary,\n postchecks: this.postchecks,\n operationClass: this.operationClass,\n };\n return `recreateTable(${jsonToTsSource(args)})`;\n }\n}\n\n// ============================================================================\n// Column\n// ============================================================================\n\nexport class AddColumnCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'addColumn' as const;\n readonly operationClass = 'additive' as const;\n readonly tableName: string;\n readonly columnName: string;\n readonly column: SqliteColumnSpec;\n readonly label: string;\n\n constructor(tableName: string, column: SqliteColumnSpec) {\n super();\n this.tableName = tableName;\n this.columnName = column.name;\n this.column = column;\n this.label = `Add column ${column.name} on ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return addColumn(this.tableName, this.column);\n }\n\n renderTypeScript(): string {\n return `addColumn(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.column)})`;\n }\n}\n\nexport class DropColumnCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'dropColumn' as const;\n readonly operationClass = 'destructive' as const;\n readonly tableName: string;\n readonly columnName: string;\n readonly label: string;\n\n constructor(tableName: string, columnName: string) {\n super();\n this.tableName = tableName;\n this.columnName = columnName;\n this.label = `Drop column ${columnName} on ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropColumn(this.tableName, this.columnName);\n }\n\n renderTypeScript(): string {\n return `dropColumn(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.columnName)})`;\n }\n}\n\n// ============================================================================\n// Index\n// ============================================================================\n\nexport class CreateIndexCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'createIndex' as const;\n readonly operationClass = 'additive' as const;\n readonly tableName: string;\n readonly indexName: string;\n readonly columns: readonly string[];\n readonly label: string;\n\n constructor(tableName: string, indexName: string, columns: readonly string[]) {\n super();\n this.tableName = tableName;\n this.indexName = indexName;\n this.columns = columns;\n this.label = `Create index ${indexName} on ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return createIndex(this.tableName, this.indexName, this.columns);\n }\n\n renderTypeScript(): string {\n return `createIndex(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.indexName)}, ${jsonToTsSource(this.columns)})`;\n }\n}\n\nexport class DropIndexCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'dropIndex' as const;\n readonly operationClass = 'destructive' as const;\n readonly tableName: string;\n readonly indexName: string;\n readonly label: string;\n\n constructor(tableName: string, indexName: string) {\n super();\n this.tableName = tableName;\n this.indexName = indexName;\n this.label = `Drop index ${indexName} on ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropIndex(this.tableName, this.indexName);\n }\n\n renderTypeScript(): string {\n return `dropIndex(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.indexName)})`;\n }\n}\n\n// ============================================================================\n// Data transform\n// ============================================================================\n\n/**\n * A planner-generated data-transform stub. The current default strategy\n * (`nullabilityTighteningBackfillStrategy`) emits one of these with a\n * backfill-flavored `id`/`label` when the policy allows `'data'` and the\n * contract tightens a column's nullability, but the op itself is generic —\n * any future strategy that needs a placeholder data step can construct one\n * with its own id/label.\n *\n * `toOp()` always throws `PN-MIG-2001`: the planner cannot lower a stubbed\n * transform to a runtime op — the user must edit the rendered\n * `migration.ts` and re-emit.\n */\nexport class DataTransformCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'dataTransform' as const;\n readonly operationClass = 'data' as const;\n readonly id: string;\n readonly label: string;\n readonly tableName: string;\n readonly columnName: string;\n\n constructor(id: string, label: string, tableName: string, columnName: string) {\n super();\n this.id = id;\n this.label = label;\n this.tableName = tableName;\n this.columnName = columnName;\n this.freeze();\n }\n\n toOp(): Op {\n throw errorUnfilledPlaceholder(this.label);\n }\n\n renderTypeScript(): string {\n const slot = `${this.tableName}-${this.columnName}-backfill-sql`;\n return [\n 'dataTransform({',\n ` id: ${jsonToTsSource(this.id)},`,\n ` label: ${jsonToTsSource(this.label)},`,\n ` table: ${jsonToTsSource(this.tableName)},`,\n ` description: ${jsonToTsSource(`Backfill NULL ${this.columnName} values in ${this.tableName}`)},`,\n ` run: () => placeholder(${jsonToTsSource(slot)}),`,\n '})',\n ].join('\\n');\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [\n { moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: this.factoryName },\n { moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: 'placeholder' },\n ];\n }\n}\n\n// ============================================================================\n// Raw SQL\n// ============================================================================\n\n/**\n * Laundered pre-built operation. Mirrors Postgres's `RawSqlCall`: wraps an\n * already-materialized `SqlMigrationPlanOperation` (typically produced by a\n * SQL-family helper or a codec lifecycle hook) so the planner can carry it\n * alongside structured call IR. `toOp()` returns the stored op unchanged;\n * `renderTypeScript()` emits `rawSql({...})` with the op serialized as a\n * JSON literal — round-tripping requires every field on the op to be\n * JSON-serializable (no closures).\n */\nexport class RawSqlCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'rawSql' as const;\n readonly operationClass: MigrationOperationClass;\n readonly label: string;\n readonly op: Op;\n\n constructor(op: Op) {\n super();\n this.op = op;\n this.label = op.label;\n this.operationClass = op.operationClass;\n this.freeze();\n }\n\n toOp(): Op {\n return this.op;\n }\n\n renderTypeScript(): string {\n return `rawSql(${jsonToTsSource(this.op)})`;\n }\n}\n\n// ============================================================================\n// Union\n// ============================================================================\n\nexport type SqliteOpFactoryCall =\n | CreateTableCall\n | DropTableCall\n | RecreateTableCall\n | AddColumnCall\n | DropColumnCall\n | CreateIndexCall\n | DropIndexCall\n | DataTransformCall\n | RawSqlCall;\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAM,0BAA0B;AAEhC,IAAe,0BAAf,cAA+C,aAA+C;CAM5F,qBAAmD;EACjD,OAAO,CAAC;GAAE,iBAAiB;GAAyB,QAAQ,KAAK;GAAa,CAAC;;CAGjF,SAAyB;EACvB,OAAO,OAAO,KAAK;;;AAQvB,IAAa,kBAAb,cAAqC,wBAAwB;CAC3D,cAAuB;CACvB,iBAA0B;CAC1B;CACA;CACA;CAEA,YAAY,WAAmB,MAAuB;EACpD,OAAO;EACP,KAAK,YAAY;EACjB,KAAK,OAAO;EACZ,KAAK,QAAQ,gBAAgB;EAC7B,KAAK,QAAQ;;CAGf,OAAW;EACT,OAAO,YAAY,KAAK,WAAW,KAAK,KAAK;;CAG/C,mBAA2B;EACzB,OAAO,eAAe,eAAe,KAAK,UAAU,CAAC,IAAI,eAAe,KAAK,KAAK,CAAC;;;AAIvF,IAAa,gBAAb,cAAmC,wBAAw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AC,IAAI,eAAe,KAAK,UAAU,CAAC;;;;;;;;;;;;;;;AAoB1F,IAAa,oBAAb,cAAuC,wBAAwB;CAC7D,cAAuB;CACvB,iBAA0B;CAC1B;CACA;CACA;CACA;CAEA,YAAY,IAAY,OAAe,WAAmB,YAAoB;EAC5E,OAAO;EACP,KAAK,KAAK;EACV,KAAK,QAAQ;EACb,KAAK,YAAY;EACjB,KAAK,aAAa;EAClB,KAAK,QAAQ;;CAGf,OAAW;EACT,MAAM,yBAAyB,KAAK,MAAM;;CAG5C,mBAA2B;EACzB,MAAM,OAAO,GAAG,KAAK,UAAU,GAAG,KAAK,WAAW;EAClD,OAAO;GACL;GACA,SAAS,eAAe,KAAK,GAAG,CAAC;GACjC,YAAY,eAAe,KAAK,MAAM,CAAC;GACvC,YAAY,eAAe,KAAK,UAAU,CAAC;GAC3C,kBAAkB,eAAe,iBAAiB,KAAK,WAAW,aAAa,KAAK,YAAY,CAAC;GACjG,4BAA4B,eAAe,KAAK,CAAC;GACjD;GACD,CAAC,KAAK,KAAK;;CAGd,qBAA4D;EAC1D,OAAO,CACL;GAAE,iBAAiB;GAAyB,QAAQ,KAAK;GAAa,EACtE;GAAE,iBAAiB;GAAyB,QAAQ;GAAe,CACpE;;;;;;;;;;;;AAiBL,IAAa,aAAb,cAAgC,wBAAwB;CACtD,cAAuB;CACvB;CACA;CACA;CAEA,YAAY,IAAQ;EAClB,OAAO;EACP,KAAK,KAAK;EACV,KAAK,QAAQ,GAAG;EAChB,KAAK,iBAAiB,GAAG;EACzB,KAAK,QAAQ;;CAGf,OAAW;EACT,OAAO,KAAK;;CAGd,mBAA2B;EACzB,OAAO,UAAU,eAAe,KAAK,GAAG,CAAC"}
|
package/dist/op-factory-call.mjs
CHANGED
|
@@ -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-
|
|
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-BnPhI25-.mjs";
|
|
2
2
|
export { AddColumnCall, CreateIndexCall, CreateTableCall, DataTransformCall, DropColumnCall, DropIndexCall, DropTableCall, RawSqlCall, RecreateTableCall };
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { t as parseSqliteDefault } from "./default-normalizer-3Fccw7yw.mjs";
|
|
2
2
|
import { t as normalizeSqliteNativeType } from "./native-type-normalizer-BlN5XfD-.mjs";
|
|
3
3
|
import { c as buildColumnDefaultSql, l as buildColumnTypeSql, n as buildRecreateSummary, t as buildRecreatePostchecks, u as isInlineAutoincrementPrimaryKey } from "./tables-DGRRJasz.mjs";
|
|
4
|
-
import { a as DropColumnCall, i as DataTransformCall, l as RecreateTableCall, n as CreateIndexCall, o as DropIndexCall, r as CreateTableCall, s as DropTableCall, t as AddColumnCall } from "./op-factory-call-
|
|
4
|
+
import { a as DropColumnCall, i as DataTransformCall, l as RecreateTableCall, n as CreateIndexCall, o as DropIndexCall, r as CreateTableCall, s as DropTableCall, t as AddColumnCall } from "./op-factory-call-BnPhI25-.mjs";
|
|
5
5
|
import { n as CONTROL_TABLE_NAMES } from "./statement-builders-Dne-LkAV.mjs";
|
|
6
|
-
import { t as TypeScriptRenderableSqliteMigration } from "./planner-produced-sqlite-migration-
|
|
6
|
+
import { t as TypeScriptRenderableSqliteMigration } from "./planner-produced-sqlite-migration-BqzfeOFu.mjs";
|
|
7
7
|
import { extractCodecControlHooks, planFieldEventOperations, plannerFailure } from "@prisma-next/family-sql/control";
|
|
8
8
|
import { verifySqlSchema } from "@prisma-next/family-sql/schema-verify";
|
|
9
9
|
import { defaultIndexName } from "@prisma-next/sql-schema-ir/naming";
|
|
@@ -551,4 +551,4 @@ var SqliteMigrationPlanner = class {
|
|
|
551
551
|
//#endregion
|
|
552
552
|
export { createSqliteMigrationPlanner as n, SqliteMigrationPlanner as t };
|
|
553
553
|
|
|
554
|
-
//# sourceMappingURL=planner-
|
|
554
|
+
//# sourceMappingURL=planner-B9-16QqD.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"planner-B1bodAgY.mjs","names":[],"sources":["../src/core/migrations/planner-strategies.ts","../src/core/migrations/issue-planner.ts","../src/core/migrations/planner.ts"],"sourcesContent":["/**\n * SQLite migration strategies.\n *\n * Each strategy examines the issue list, consumes issues it handles, and\n * returns the `SqliteOpFactoryCall[]` to address them. The issue planner\n * runs each strategy in order and routes whatever's left through\n * `mapIssueToCall`.\n *\n * SQLite has no enums, no data-safe backfill, and no component-declared\n * database dependencies. The only recipe that needs strategy-level\n * multi-issue consumption is `recreateTable` (added in a later phase), which\n * absorbs type/nullability/default/constraint mismatches for a given table\n * into a single recreate operation.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n MigrationOperationClass,\n MigrationOperationPolicy,\n} from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type {\n PostgresEnumStorageEntry,\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 | PostgresEnumStorageEntry>>;\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 return storage.namespaces[namespaceId]?.tables[tableName] as StorageTable | 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 } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlPlannerConflict,\n SqlPlannerConflictLocation,\n} from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport type {\n PostgresEnumStorageEntry,\n SqlStorage,\n StorageColumn,\n StorageTable,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { defaultIndexName } from '@prisma-next/sql-schema-ir/naming';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport {\n AddColumnCall,\n CreateIndexCall,\n CreateTableCall,\n DropColumnCall,\n DropIndexCall,\n DropTableCall,\n type SqliteOpFactoryCall,\n} from './op-factory-call';\nimport type {\n SqliteColumnSpec,\n SqliteForeignKeySpec,\n SqliteTableSpec,\n SqliteUniqueSpec,\n} from './operations/shared';\nimport {\n buildColumnDefaultSql,\n buildColumnTypeSql,\n isInlineAutoincrementPrimaryKey,\n} from './planner-ddl-builders';\nimport {\n type CallMigrationStrategy,\n resolveNamespaceIdForIssue,\n type StrategyContext,\n sqlitePlannerStrategies,\n tableAt,\n} from './planner-strategies';\nimport { CONTROL_TABLE_NAMES } from './statement-builders';\n\nexport type { CallMigrationStrategy, StrategyContext };\n\n// ============================================================================\n// Issue kind ordering (dependency order)\n// ============================================================================\n\nconst ISSUE_KIND_ORDER: Record<string, number> = {\n // Drops (reconciliation — clear the way for creates)\n extra_foreign_key: 10,\n extra_unique_constraint: 11,\n extra_primary_key: 12,\n extra_index: 13,\n extra_default: 14,\n extra_column: 15,\n extra_table: 16,\n\n // Tables before columns\n missing_table: 20,\n\n // Columns before constraints\n missing_column: 30,\n\n // Reconciliation alters (on existing objects)\n type_mismatch: 40,\n nullability_mismatch: 41,\n default_missing: 42,\n default_mismatch: 43,\n\n // Constraints after columns exist\n primary_key_mismatch: 50,\n unique_constraint_mismatch: 51,\n index_mismatch: 52,\n foreign_key_mismatch: 60,\n};\n\nfunction issueOrder(issue: SchemaIssue): number {\n return ISSUE_KIND_ORDER[issue.kind] ?? 99;\n}\n\nfunction issueKey(issue: SchemaIssue): string {\n const table = 'table' in issue && typeof issue.table === 'string' ? issue.table : '';\n const column = 'column' in issue && typeof issue.column === 'string' ? issue.column : '';\n const name =\n 'indexOrConstraint' in issue && typeof issue.indexOrConstraint === 'string'\n ? issue.indexOrConstraint\n : '';\n return `${table}\\u0000${column}\\u0000${name}`;\n}\n\n// ============================================================================\n// Conflict helpers\n// ============================================================================\n\nfunction issueConflict(\n kind: SqlPlannerConflict['kind'],\n summary: string,\n location?: SqlPlannerConflict['location'],\n): SqlPlannerConflict {\n return {\n kind,\n summary,\n why: 'Use `migration new` to author a custom migration for this change.',\n ...(location ? { location } : {}),\n };\n}\n\nfunction conflictKindForIssue(issue: SchemaIssue): SqlPlannerConflict['kind'] {\n switch (issue.kind) {\n case 'type_mismatch':\n return 'typeMismatch';\n case 'nullability_mismatch':\n return 'nullabilityConflict';\n case 'primary_key_mismatch':\n case 'unique_constraint_mismatch':\n case 'index_mismatch':\n case 'extra_primary_key':\n case 'extra_unique_constraint':\n return 'indexIncompatible';\n case 'foreign_key_mismatch':\n case 'extra_foreign_key':\n return 'foreignKeyConflict';\n default:\n return 'missingButNonAdditive';\n }\n}\n\nfunction issueLocation(issue: SchemaIssue): SqlPlannerConflictLocation | undefined {\n if (issue.kind === 'enum_values_changed') return undefined;\n const location: {\n table?: string;\n column?: string;\n constraint?: string;\n } = {};\n if (issue.table) location.table = issue.table;\n if (issue.column) location.column = issue.column;\n if (issue.indexOrConstraint) location.constraint = issue.indexOrConstraint;\n return Object.keys(location).length > 0 ? (location as SqlPlannerConflictLocation) : undefined;\n}\n\nfunction conflictForDisallowedCall(\n call: SqliteOpFactoryCall,\n allowed: readonly string[],\n): SqlPlannerConflict {\n const summary = `Operation \"${call.label}\" requires class \"${call.operationClass}\", but policy allows only: ${allowed.join(', ')}`;\n const location = locationForCall(call);\n return {\n kind: conflictKindForCall(call),\n summary,\n why: 'Use `migration new` to author a custom migration for this change.',\n ...(location ? { location } : {}),\n };\n}\n\nfunction conflictKindForCall(call: SqliteOpFactoryCall): SqlPlannerConflict['kind'] {\n switch (call.factoryName) {\n case 'createIndex':\n case 'dropIndex':\n return 'indexIncompatible';\n default:\n return 'missingButNonAdditive';\n }\n}\n\nfunction locationForCall(call: SqliteOpFactoryCall): SqlPlannerConflictLocation | undefined {\n const location: { table?: string; column?: string; index?: string } = {};\n if ('tableName' in call) location.table = call.tableName;\n if ('columnName' in call) location.column = call.columnName;\n if ('indexName' in call) location.index = call.indexName;\n return Object.keys(location).length > 0 ? (location as SqlPlannerConflictLocation) : undefined;\n}\n\nfunction isMissing(issue: SchemaIssue): boolean {\n if (issue.kind === 'enum_values_changed') return false;\n return issue.actual === undefined;\n}\n\n// ============================================================================\n// StorageTable / StorageColumn → flat SqliteTableSpec\n// ============================================================================\n\n/**\n * Resolves codec / `typeRef` / default rendering into a flat\n * `SqliteColumnSpec`. Mirrors Postgres's `toColumnSpec`. Once a column is\n * flattened, downstream Calls and operation factories never see\n * `StorageColumn` again — they deal in pre-rendered SQL fragments.\n */\nexport function toColumnSpec(\n name: string,\n column: StorageColumn,\n storageTypes: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>,\n inlineAutoincrementPrimaryKey = false,\n): SqliteColumnSpec {\n const typeSql = buildColumnTypeSql(\n column,\n storageTypes as Record<string, StorageTypeInstance | PostgresEnumStorageEntry>,\n );\n const defaultSql = buildColumnDefaultSql(column.default);\n return {\n name,\n typeSql,\n defaultSql,\n nullable: column.nullable,\n ...(inlineAutoincrementPrimaryKey ? { inlineAutoincrementPrimaryKey: true } : {}),\n };\n}\n\n/**\n * Flattens a `StorageTable` into a `SqliteTableSpec` ready for\n * `CreateTableCall` / `RecreateTableCall`. Sole-column AUTOINCREMENT\n * primary keys are detected here and marked on the column spec so the\n * renderer emits `INTEGER PRIMARY KEY AUTOINCREMENT` inline.\n */\nexport function toTableSpec(\n table: StorageTable,\n storageTypes: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>,\n): SqliteTableSpec {\n const columns: SqliteColumnSpec[] = Object.entries(table.columns).map(([name, column]) =>\n toColumnSpec(name, column, storageTypes, isInlineAutoincrementPrimaryKey(table, name)),\n );\n const uniques: SqliteUniqueSpec[] = table.uniques.map((u) => ({\n columns: u.columns,\n ...(u.name !== undefined ? { name: u.name } : {}),\n }));\n const foreignKeys: SqliteForeignKeySpec[] = table.foreignKeys.map((fk) => ({\n columns: fk.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// Issue planner\n// ============================================================================\n\nexport interface IssuePlannerOptions {\n readonly issues: readonly SchemaIssue[];\n readonly toContract: Contract<SqlStorage>;\n readonly fromContract: Contract<SqlStorage> | null;\n readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;\n readonly storageTypes: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>;\n readonly schema?: SqlSchemaIR;\n readonly policy?: MigrationOperationPolicy;\n readonly frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n readonly strategies?: readonly CallMigrationStrategy[];\n}\n\nexport interface IssuePlannerValue {\n readonly calls: readonly SqliteOpFactoryCall[];\n}\n\nconst DEFAULT_POLICY: MigrationOperationPolicy = {\n allowedOperationClasses: ['additive', 'widening', 'destructive', 'data'],\n};\n\nfunction emptySchemaIR(): SqlSchemaIR {\n return { tables: {} };\n}\n\n// ============================================================================\n// Issue → Call mapping (per-issue default path)\n// ============================================================================\n\nfunction mapIssueToCall(\n issue: SchemaIssue,\n ctx: StrategyContext,\n): Result<readonly SqliteOpFactoryCall[], SqlPlannerConflict> {\n switch (issue.kind) {\n case 'missing_table': {\n if (!issue.table) {\n return notOk(\n issueConflict('unsupportedOperation', 'Missing table issue has no table name'),\n );\n }\n const 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 tableSpec = toTableSpec(contractTable, ctx.storageTypes);\n const calls: SqliteOpFactoryCall[] = [new CreateTableCall(issue.table, tableSpec)];\n const declaredIndexColumnKeys = new Set<string>();\n for (const index of contractTable.indexes) {\n const indexName = index.name ?? defaultIndexName(issue.table, index.columns);\n declaredIndexColumnKeys.add(index.columns.join(','));\n calls.push(new CreateIndexCall(issue.table, indexName, index.columns));\n }\n for (const fk of contractTable.foreignKeys) {\n if (fk.index === false) continue;\n if (declaredIndexColumnKeys.has(fk.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 { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationPlanner,\n MigrationScaffoldContext,\n SchemaIssue,\n} from '@prisma-next/framework-components/control';\nimport { parseSqliteDefault } from '../default-normalizer';\nimport { normalizeSqliteNativeType } from '../native-type-normalizer';\nimport { planIssues } from './issue-planner';\nimport {\n type SqliteMigrationDestinationInfo,\n TypeScriptRenderableSqliteMigration,\n} from './planner-produced-sqlite-migration';\nimport { sqlitePlannerStrategies } from './planner-strategies';\nimport type { SqlitePlanTargetDetails } from './planner-target-details';\n\nexport function createSqliteMigrationPlanner(): SqliteMigrationPlanner {\n return new SqliteMigrationPlanner();\n}\n\nexport type SqlitePlanResult =\n | { readonly kind: 'success'; readonly plan: TypeScriptRenderableSqliteMigration }\n | SqlPlannerFailureResult;\n\n/**\n * SQLite migration planner — a thin wrapper over `planIssues`.\n *\n * `plan()` verifies the live schema against the target contract (producing\n * `SchemaIssue[]`) and delegates to `planIssues` with the registered\n * strategies. Strategies absorb groups of related issues into composite\n * recipes (e.g. recreating a table to apply type/nullability/default/\n * constraint changes at once); anything not absorbed by a strategy flows\n * through `mapIssueToCall` in the issue planner as a one-off call.\n *\n * FK-backing indexes are surfaced by `verifySqlSchema`'s index expansion\n * (see `verify-sql-schema.ts:459-469`), so `mapIssueToCall` handles them\n * uniformly alongside user-declared indexes.\n */\nexport class SqliteMigrationPlanner\n implements SqlMigrationPlanner<SqlitePlanTargetDetails>, MigrationPlanner<'sql', 'sqlite'>\n{\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n /**\n * The \"from\" contract (state the planner assumes the database starts at),\n * or `null` for reconciliation flows.\n *\n * Typed as the framework `Contract | null` to satisfy the\n * `MigrationPlanner` interface contract; `planSql` narrows to the SQL\n * shape via `SqlMigrationPlannerPlanOptions`. Used to populate\n * `describe().from` on the produced plan as\n * `fromContract?.storage.storageHash ?? null`.\n */\n readonly fromContract: Contract | null;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n /**\n * Contract space this plan applies to. Stamped onto the produced\n * {@link TypeScriptRenderableSqliteMigration.spaceId} so the runner keys\n * the marker row by the right space.\n */\n readonly spaceId: string;\n }): SqlitePlanResult {\n return this.planSql(options as SqlMigrationPlannerPlanOptions);\n }\n\n emptyMigration(\n context: MigrationScaffoldContext,\n spaceId: string,\n ): TypeScriptRenderableSqliteMigration {\n return new TypeScriptRenderableSqliteMigration(\n [],\n {\n from: context.fromHash,\n to: context.toHash,\n },\n spaceId,\n );\n }\n\n private planSql(options: SqlMigrationPlannerPlanOptions): SqlitePlanResult {\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) return policyResult;\n\n const schemaIssues = this.collectSchemaIssues(options);\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n const storageTypes = options.contract.storage.types ?? {};\n\n const result = planIssues({\n issues: schemaIssues,\n toContract: options.contract,\n fromContract: options.fromContract,\n codecHooks,\n storageTypes,\n schema: options.schema,\n policy: options.policy,\n frameworkComponents: options.frameworkComponents,\n strategies: sqlitePlannerStrategies,\n });\n\n if (!result.ok) {\n return plannerFailure(result.failure);\n }\n\n // Codec lifecycle hook (T2.2): inline `onFieldEvent`-emitted ops after\n // structural DDL. Sub-spec § 5 fixes the ordering as\n // `structural → added → dropped → altered`, with within-group sorting by\n // `(tableName, fieldName)` deterministic for byte-stable re-emits.\n // Hook fires only at the application emitter — extension-space planning\n // (M2 R2) never reaches this helper.\n const fieldEventOps = planFieldEventOperations({\n priorContract: options.fromContract,\n newContract: options.contract,\n codecHooks,\n });\n // Codec-emitted calls already conform to `OpFactoryCall` — render +\n // toOp + importRequirements ride directly through the same emit path\n // as structural ops, no `RawSqlCall` wrap.\n const calls = [...result.value.calls, ...fieldEventOps];\n\n const destination: SqliteMigrationDestinationInfo = {\n storageHash: options.contract.storage.storageHash,\n ...(options.contract.profileHash !== undefined\n ? { profileHash: options.contract.profileHash }\n : {}),\n };\n\n return {\n kind: 'success' as const,\n plan: new TypeScriptRenderableSqliteMigration(\n calls,\n {\n from: options.fromContract?.storage.storageHash ?? null,\n to: options.contract.storage.storageHash,\n },\n options.spaceId,\n destination,\n ),\n };\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy): SqlPlannerFailureResult | null {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n\n private collectSchemaIssues(options: SqlMigrationPlannerPlanOptions): readonly SchemaIssue[] {\n const allowed = options.policy.allowedOperationClasses;\n const strict = allowed.includes('widening') || allowed.includes('destructive');\n const verifyResult = verifySqlSchema({\n contract: options.contract,\n schema: options.schema,\n strict,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parseSqliteDefault,\n normalizeNativeType: normalizeSqliteNativeType,\n });\n return verifyResult.schema.issues;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAgB,QACd,SACA,aACA,WAC0B;CAC1B,OAAO,QAAQ,WAAW,cAAc,OAAO;;;;;;;;;;AAWjD,SAAgB,2BAA2B,OAAkD;CAC3F,OAAO,MAAM,eAAe;;AAmB9B,MAAM,uBAAuB,IAAI,IAAyB,CAAC,oBAAoB,kBAAkB,CAAC;AAElG,MAAM,0BAA0B,IAAI,IAAyB;CAC3D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAS,cAAc,OAAuD;CAC5E,IAAI,MAAM,SAAS,uBAAuB,OAAO;CACjD,IAAI,CAAC,MAAM,OAAO,OAAO;CACzB,IAAI,MAAM,SAAS,w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AC;EAEJ,OAAO;;CAGT,oBAA4B,SAAiE;EAC3F,MAAM,UAAU,QAAQ,OAAO;EAC/B,MAAM,SAAS,QAAQ,SAAS,WAAW,IAAI,QAAQ,SAAS,cAAc;EAU9E,OATqB,gBAAgB;GACnC,UAAU,QAAQ;GAClB,QAAQ,QAAQ;GAChB;GACA,sCAAsB,IAAI,KAAK;GAC/B,qBAAqB,QAAQ;GAC7B,kBAAkB;GAClB,qBAAqB;GACtB,CACkB,CAAC,OAAO"}
|
|
1
|
+
{"version":3,"file":"planner-B9-16QqD.mjs","names":[],"sources":["../src/core/migrations/planner-strategies.ts","../src/core/migrations/issue-planner.ts","../src/core/migrations/planner.ts"],"sourcesContent":["/**\n * SQLite migration strategies.\n *\n * Each strategy examines the issue list, consumes issues it handles, and\n * returns the `SqliteOpFactoryCall[]` to address them. The issue planner\n * runs each strategy in order and routes whatever's left through\n * `mapIssueToCall`.\n *\n * SQLite has no enums, no data-safe backfill, and no component-declared\n * database dependencies. The only recipe that needs strategy-level\n * multi-issue consumption is `recreateTable` (added in a later phase), which\n * absorbs type/nullability/default/constraint mismatches for a given table\n * into a single recreate operation.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n MigrationOperationClass,\n MigrationOperationPolicy,\n} from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type {\n PostgresEnumStorageEntry,\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 | PostgresEnumStorageEntry>>;\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 return storage.namespaces[namespaceId]?.tables[tableName] as StorageTable | 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 } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlPlannerConflict,\n SqlPlannerConflictLocation,\n} from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport type {\n PostgresEnumStorageEntry,\n SqlStorage,\n StorageColumn,\n StorageTable,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { defaultIndexName } from '@prisma-next/sql-schema-ir/naming';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport {\n AddColumnCall,\n CreateIndexCall,\n CreateTableCall,\n DropColumnCall,\n DropIndexCall,\n DropTableCall,\n type SqliteOpFactoryCall,\n} from './op-factory-call';\nimport type {\n SqliteColumnSpec,\n SqliteForeignKeySpec,\n SqliteTableSpec,\n SqliteUniqueSpec,\n} from './operations/shared';\nimport {\n buildColumnDefaultSql,\n buildColumnTypeSql,\n isInlineAutoincrementPrimaryKey,\n} from './planner-ddl-builders';\nimport {\n type CallMigrationStrategy,\n resolveNamespaceIdForIssue,\n type StrategyContext,\n sqlitePlannerStrategies,\n tableAt,\n} from './planner-strategies';\nimport { CONTROL_TABLE_NAMES } from './statement-builders';\n\nexport type { CallMigrationStrategy, StrategyContext };\n\n// ============================================================================\n// Issue kind ordering (dependency order)\n// ============================================================================\n\nconst ISSUE_KIND_ORDER: Record<string, number> = {\n // Drops (reconciliation — clear the way for creates)\n extra_foreign_key: 10,\n extra_unique_constraint: 11,\n extra_primary_key: 12,\n extra_index: 13,\n extra_default: 14,\n extra_column: 15,\n extra_table: 16,\n\n // Tables before columns\n missing_table: 20,\n\n // Columns before constraints\n missing_column: 30,\n\n // Reconciliation alters (on existing objects)\n type_mismatch: 40,\n nullability_mismatch: 41,\n default_missing: 42,\n default_mismatch: 43,\n\n // Constraints after columns exist\n primary_key_mismatch: 50,\n unique_constraint_mismatch: 51,\n index_mismatch: 52,\n foreign_key_mismatch: 60,\n};\n\nfunction issueOrder(issue: SchemaIssue): number {\n return ISSUE_KIND_ORDER[issue.kind] ?? 99;\n}\n\nfunction issueKey(issue: SchemaIssue): string {\n const table = 'table' in issue && typeof issue.table === 'string' ? issue.table : '';\n const column = 'column' in issue && typeof issue.column === 'string' ? issue.column : '';\n const name =\n 'indexOrConstraint' in issue && typeof issue.indexOrConstraint === 'string'\n ? issue.indexOrConstraint\n : '';\n return `${table}\\u0000${column}\\u0000${name}`;\n}\n\n// ============================================================================\n// Conflict helpers\n// ============================================================================\n\nfunction issueConflict(\n kind: SqlPlannerConflict['kind'],\n summary: string,\n location?: SqlPlannerConflict['location'],\n): SqlPlannerConflict {\n return {\n kind,\n summary,\n why: 'Use `migration new` to author a custom migration for this change.',\n ...(location ? { location } : {}),\n };\n}\n\nfunction conflictKindForIssue(issue: SchemaIssue): SqlPlannerConflict['kind'] {\n switch (issue.kind) {\n case 'type_mismatch':\n return 'typeMismatch';\n case 'nullability_mismatch':\n return 'nullabilityConflict';\n case 'primary_key_mismatch':\n case 'unique_constraint_mismatch':\n case 'index_mismatch':\n case 'extra_primary_key':\n case 'extra_unique_constraint':\n return 'indexIncompatible';\n case 'foreign_key_mismatch':\n case 'extra_foreign_key':\n return 'foreignKeyConflict';\n default:\n return 'missingButNonAdditive';\n }\n}\n\nfunction issueLocation(issue: SchemaIssue): SqlPlannerConflictLocation | undefined {\n if (issue.kind === 'enum_values_changed') return undefined;\n const location: {\n table?: string;\n column?: string;\n constraint?: string;\n } = {};\n if (issue.table) location.table = issue.table;\n if (issue.column) location.column = issue.column;\n if (issue.indexOrConstraint) location.constraint = issue.indexOrConstraint;\n return Object.keys(location).length > 0 ? (location as SqlPlannerConflictLocation) : undefined;\n}\n\nfunction conflictForDisallowedCall(\n call: SqliteOpFactoryCall,\n allowed: readonly string[],\n): SqlPlannerConflict {\n const summary = `Operation \"${call.label}\" requires class \"${call.operationClass}\", but policy allows only: ${allowed.join(', ')}`;\n const location = locationForCall(call);\n return {\n kind: conflictKindForCall(call),\n summary,\n why: 'Use `migration new` to author a custom migration for this change.',\n ...(location ? { location } : {}),\n };\n}\n\nfunction conflictKindForCall(call: SqliteOpFactoryCall): SqlPlannerConflict['kind'] {\n switch (call.factoryName) {\n case 'createIndex':\n case 'dropIndex':\n return 'indexIncompatible';\n default:\n return 'missingButNonAdditive';\n }\n}\n\nfunction locationForCall(call: SqliteOpFactoryCall): SqlPlannerConflictLocation | undefined {\n const location: { table?: string; column?: string; index?: string } = {};\n if ('tableName' in call) location.table = call.tableName;\n if ('columnName' in call) location.column = call.columnName;\n if ('indexName' in call) location.index = call.indexName;\n return Object.keys(location).length > 0 ? (location as SqlPlannerConflictLocation) : undefined;\n}\n\nfunction isMissing(issue: SchemaIssue): boolean {\n if (issue.kind === 'enum_values_changed') return false;\n return issue.actual === undefined;\n}\n\n// ============================================================================\n// StorageTable / StorageColumn → flat SqliteTableSpec\n// ============================================================================\n\n/**\n * Resolves codec / `typeRef` / default rendering into a flat\n * `SqliteColumnSpec`. Mirrors Postgres's `toColumnSpec`. Once a column is\n * flattened, downstream Calls and operation factories never see\n * `StorageColumn` again — they deal in pre-rendered SQL fragments.\n */\nexport function toColumnSpec(\n name: string,\n column: StorageColumn,\n storageTypes: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>,\n inlineAutoincrementPrimaryKey = false,\n): SqliteColumnSpec {\n const typeSql = buildColumnTypeSql(\n column,\n storageTypes as Record<string, StorageTypeInstance | PostgresEnumStorageEntry>,\n );\n const defaultSql = buildColumnDefaultSql(column.default);\n return {\n name,\n typeSql,\n defaultSql,\n nullable: column.nullable,\n ...(inlineAutoincrementPrimaryKey ? { inlineAutoincrementPrimaryKey: true } : {}),\n };\n}\n\n/**\n * Flattens a `StorageTable` into a `SqliteTableSpec` ready for\n * `CreateTableCall` / `RecreateTableCall`. Sole-column AUTOINCREMENT\n * primary keys are detected here and marked on the column spec so the\n * renderer emits `INTEGER PRIMARY KEY AUTOINCREMENT` inline.\n */\nexport function toTableSpec(\n table: StorageTable,\n storageTypes: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>,\n): SqliteTableSpec {\n const columns: SqliteColumnSpec[] = Object.entries(table.columns).map(([name, column]) =>\n toColumnSpec(name, column, storageTypes, isInlineAutoincrementPrimaryKey(table, name)),\n );\n const uniques: SqliteUniqueSpec[] = table.uniques.map((u) => ({\n columns: u.columns,\n ...(u.name !== undefined ? { name: u.name } : {}),\n }));\n const foreignKeys: SqliteForeignKeySpec[] = table.foreignKeys.map((fk) => ({\n columns: fk.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// Issue planner\n// ============================================================================\n\nexport interface IssuePlannerOptions {\n readonly issues: readonly SchemaIssue[];\n readonly toContract: Contract<SqlStorage>;\n readonly fromContract: Contract<SqlStorage> | null;\n readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;\n readonly storageTypes: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>;\n readonly schema?: SqlSchemaIR;\n readonly policy?: MigrationOperationPolicy;\n readonly frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n readonly strategies?: readonly CallMigrationStrategy[];\n}\n\nexport interface IssuePlannerValue {\n readonly calls: readonly SqliteOpFactoryCall[];\n}\n\nconst DEFAULT_POLICY: MigrationOperationPolicy = {\n allowedOperationClasses: ['additive', 'widening', 'destructive', 'data'],\n};\n\nfunction emptySchemaIR(): SqlSchemaIR {\n return { tables: {} };\n}\n\n// ============================================================================\n// Issue → Call mapping (per-issue default path)\n// ============================================================================\n\nfunction mapIssueToCall(\n issue: SchemaIssue,\n ctx: StrategyContext,\n): Result<readonly SqliteOpFactoryCall[], SqlPlannerConflict> {\n switch (issue.kind) {\n case 'missing_table': {\n if (!issue.table) {\n return notOk(\n issueConflict('unsupportedOperation', 'Missing table issue has no table name'),\n );\n }\n const 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 tableSpec = toTableSpec(contractTable, ctx.storageTypes);\n const calls: SqliteOpFactoryCall[] = [new CreateTableCall(issue.table, tableSpec)];\n const declaredIndexColumnKeys = new Set<string>();\n for (const index of contractTable.indexes) {\n const indexName = index.name ?? defaultIndexName(issue.table, index.columns);\n declaredIndexColumnKeys.add(index.columns.join(','));\n calls.push(new CreateIndexCall(issue.table, indexName, index.columns));\n }\n for (const fk of contractTable.foreignKeys) {\n if (fk.index === false) continue;\n if (declaredIndexColumnKeys.has(fk.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 { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationPlanner,\n MigrationScaffoldContext,\n SchemaIssue,\n} from '@prisma-next/framework-components/control';\nimport { parseSqliteDefault } from '../default-normalizer';\nimport { normalizeSqliteNativeType } from '../native-type-normalizer';\nimport { planIssues } from './issue-planner';\nimport {\n type SqliteMigrationDestinationInfo,\n TypeScriptRenderableSqliteMigration,\n} from './planner-produced-sqlite-migration';\nimport { sqlitePlannerStrategies } from './planner-strategies';\nimport type { SqlitePlanTargetDetails } from './planner-target-details';\n\nexport function createSqliteMigrationPlanner(): SqliteMigrationPlanner {\n return new SqliteMigrationPlanner();\n}\n\nexport type SqlitePlanResult =\n | { readonly kind: 'success'; readonly plan: TypeScriptRenderableSqliteMigration }\n | SqlPlannerFailureResult;\n\n/**\n * SQLite migration planner — a thin wrapper over `planIssues`.\n *\n * `plan()` verifies the live schema against the target contract (producing\n * `SchemaIssue[]`) and delegates to `planIssues` with the registered\n * strategies. Strategies absorb groups of related issues into composite\n * recipes (e.g. recreating a table to apply type/nullability/default/\n * constraint changes at once); anything not absorbed by a strategy flows\n * through `mapIssueToCall` in the issue planner as a one-off call.\n *\n * FK-backing indexes are surfaced by `verifySqlSchema`'s index expansion\n * (see `verify-sql-schema.ts:459-469`), so `mapIssueToCall` handles them\n * uniformly alongside user-declared indexes.\n */\nexport class SqliteMigrationPlanner\n implements SqlMigrationPlanner<SqlitePlanTargetDetails>, MigrationPlanner<'sql', 'sqlite'>\n{\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n /**\n * The \"from\" contract (state the planner assumes the database starts at),\n * or `null` for reconciliation flows.\n *\n * Typed as the framework `Contract | null` to satisfy the\n * `MigrationPlanner` interface contract; `planSql` narrows to the SQL\n * shape via `SqlMigrationPlannerPlanOptions`. Used to populate\n * `describe().from` on the produced plan as\n * `fromContract?.storage.storageHash ?? null`.\n */\n readonly fromContract: Contract | null;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n /**\n * Contract space this plan applies to. Stamped onto the produced\n * {@link TypeScriptRenderableSqliteMigration.spaceId} so the runner keys\n * the marker row by the right space.\n */\n readonly spaceId: string;\n }): SqlitePlanResult {\n return this.planSql(options as SqlMigrationPlannerPlanOptions);\n }\n\n emptyMigration(\n context: MigrationScaffoldContext,\n spaceId: string,\n ): TypeScriptRenderableSqliteMigration {\n return new TypeScriptRenderableSqliteMigration(\n [],\n {\n from: context.fromHash,\n to: context.toHash,\n },\n spaceId,\n );\n }\n\n private planSql(options: SqlMigrationPlannerPlanOptions): SqlitePlanResult {\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) return policyResult;\n\n const schemaIssues = this.collectSchemaIssues(options);\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n const storageTypes = options.contract.storage.types ?? {};\n\n const result = planIssues({\n issues: schemaIssues,\n toContract: options.contract,\n fromContract: options.fromContract,\n codecHooks,\n storageTypes,\n schema: options.schema,\n policy: options.policy,\n frameworkComponents: options.frameworkComponents,\n strategies: sqlitePlannerStrategies,\n });\n\n if (!result.ok) {\n return plannerFailure(result.failure);\n }\n\n // Codec lifecycle hook (T2.2): inline `onFieldEvent`-emitted ops after\n // structural DDL. Sub-spec § 5 fixes the ordering as\n // `structural → added → dropped → altered`, with within-group sorting by\n // `(tableName, fieldName)` deterministic for byte-stable re-emits.\n // Hook fires only at the application emitter — extension-space planning\n // (M2 R2) never reaches this helper.\n const fieldEventOps = planFieldEventOperations({\n priorContract: options.fromContract,\n newContract: options.contract,\n codecHooks,\n });\n // Codec-emitted calls already conform to `OpFactoryCall` — render +\n // toOp + importRequirements ride directly through the same emit path\n // as structural ops, no `RawSqlCall` wrap.\n const calls = [...result.value.calls, ...fieldEventOps];\n\n const destination: SqliteMigrationDestinationInfo = {\n storageHash: options.contract.storage.storageHash,\n ...(options.contract.profileHash !== undefined\n ? { profileHash: options.contract.profileHash }\n : {}),\n };\n\n return {\n kind: 'success' as const,\n plan: new TypeScriptRenderableSqliteMigration(\n calls,\n {\n from: options.fromContract?.storage.storageHash ?? null,\n to: options.contract.storage.storageHash,\n },\n options.spaceId,\n destination,\n ),\n };\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy): SqlPlannerFailureResult | null {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n\n private collectSchemaIssues(options: SqlMigrationPlannerPlanOptions): readonly SchemaIssue[] {\n const allowed = options.policy.allowedOperationClasses;\n const strict = allowed.includes('widening') || allowed.includes('destructive');\n const verifyResult = verifySqlSchema({\n contract: options.contract,\n schema: options.schema,\n strict,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parseSqliteDefault,\n normalizeNativeType: normalizeSqliteNativeType,\n });\n return verifyResult.schema.issues;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAgB,QACd,SACA,aACA,WAC0B;CAC1B,OAAO,QAAQ,WAAW,cAAc,OAAO;;;;;;;;;;AAWjD,SAAgB,2BAA2B,OAAkD;CAC3F,OAAO,MAAM,eAAe;;AAmB9B,MAAM,uBAAuB,IAAI,IAAyB,CAAC,oBAAoB,kBAAkB,CAAC;AAElG,MAAM,0BAA0B,IAAI,IAAyB;CAC3D;CACA;CACA;CACA;CACA;CACA;CACA;CACA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;;CAGH,qBAA6B,QAAkE;EAC7F,IAAI,CAAC,OAAO,wBAAwB,SAAS,WAAW,EACtD,OAAO,eAAe,CACpB;GACE,MAAM;GACN,SAAS;GACT,KAAK;GACN,CACF,CAAC;EAEJ,OAAO;;CAGT,oBAA4B,SAAiE;EAC3F,MAAM,UAAU,QAAQ,OAAO;EAC/B,MAAM,SAAS,QAAQ,SAAS,WAAW,IAAI,QAAQ,SAAS,cAAc;EAU9E,OATqB,gBAAgB;GACnC,UAAU,QAAQ;GAClB,QAAQ,QAAQ;GAChB;GACA,sCAAsB,IAAI,KAAK;GAC/B,qBAAqB,QAAQ;GAC7B,kBAAkB;GAClB,qBAAqB;GACtB,CACkB,CAAC,OAAO"}
|
|
@@ -6,11 +6,11 @@ import { detectScaffoldRuntime, shebangLineFor } from "@prisma-next/migration-to
|
|
|
6
6
|
//#region src/core/migrations/render-typescript.ts
|
|
7
7
|
/**
|
|
8
8
|
* Always-present base imports for the rendered scaffold. Both come from
|
|
9
|
-
* `@prisma-next/
|
|
9
|
+
* `@prisma-next/sqlite/migration` so an authored SQLite
|
|
10
10
|
* `migration.ts` only needs a single dependency for its base class and
|
|
11
11
|
* its CLI entrypoint. Mirrors Postgres's `BASE_IMPORTS`.
|
|
12
12
|
*
|
|
13
|
-
* - `Migration` — the
|
|
13
|
+
* - `Migration` — the facade re-export fixes the `SqlMigration`
|
|
14
14
|
* generic to `SqlitePlanTargetDetails` and the abstract `targetId` to
|
|
15
15
|
* `'sqlite'`.
|
|
16
16
|
* - `MigrationCLI` — the migration-file CLI entrypoint, re-exported from
|
|
@@ -18,10 +18,10 @@ import { detectScaffoldRuntime, shebangLineFor } from "@prisma-next/migration-to
|
|
|
18
18
|
* assembles a `ControlStack`, and instantiates the migration class.
|
|
19
19
|
*/
|
|
20
20
|
const BASE_IMPORTS = [{
|
|
21
|
-
moduleSpecifier: "@prisma-next/
|
|
21
|
+
moduleSpecifier: "@prisma-next/sqlite/migration",
|
|
22
22
|
symbol: "Migration"
|
|
23
23
|
}, {
|
|
24
|
-
moduleSpecifier: "@prisma-next/
|
|
24
|
+
moduleSpecifier: "@prisma-next/sqlite/migration",
|
|
25
25
|
symbol: "MigrationCLI"
|
|
26
26
|
}];
|
|
27
27
|
function renderCallsToTypeScript(calls, meta) {
|
|
@@ -107,4 +107,4 @@ var TypeScriptRenderableSqliteMigration = class extends SqliteMigration {
|
|
|
107
107
|
//#endregion
|
|
108
108
|
export { TypeScriptRenderableSqliteMigration as t };
|
|
109
109
|
|
|
110
|
-
//# sourceMappingURL=planner-produced-sqlite-migration-
|
|
110
|
+
//# sourceMappingURL=planner-produced-sqlite-migration-BqzfeOFu.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"planner-produced-sqlite-migration-BqzfeOFu.mjs","names":["#calls","#meta","#destination","#spaceId"],"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, jsonToTsSource, renderImports } from '@prisma-next/ts-render';\n\nexport interface RenderMigrationMeta {\n readonly from: string | null;\n readonly to: string;\n readonly labels?: readonly 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 if (meta.labels && meta.labels.length > 0) {\n lines.push(` labels: ${jsonToTsSource(meta.labels)},`);\n }\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 {\n MigrationPlanWithAuthoringSurface,\n OpFactoryCall,\n} from '@prisma-next/framework-components/control';\nimport type { MigrationMeta } from '@prisma-next/migration-tools/migration';\nimport { ifDefined } from '@prisma-next/utils/defined';\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\n constructor(\n calls: readonly OpFactoryCall[],\n meta: MigrationMeta,\n spaceId: string,\n destination?: SqliteMigrationDestinationInfo,\n ) {\n super();\n this.#calls = calls;\n this.#meta = meta;\n this.#spaceId = spaceId;\n this.#destination = destination ?? { storageHash: meta.to };\n }\n\n override get operations(): readonly Op[] {\n return renderOps(this.#calls);\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 ...ifDefined('labels', this.#meta.labels),\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6BA,MAAM,eAA6C,CACjD;CAAE,iBAAiB;CAAiC,QAAQ;CAAa,EACzE;CAAE,iBAAiB;CAAiC,QAAQ;CAAgB,CAC7E;AAED,SAAgB,wBACd,OACA,MACQ;CACR,MAAM,UAAU,aAAa,MAAM;CACnC,MAAM,iBAAiB,MAAM,KAAK,MAAM,EAAE,kBAAkB,CAAC,CAAC,KAAK,MAAM;CAEzE,OAAO;EACL,eAAe,uBAAuB,CAAC;EACvC;EACA;EACA;EACA,oB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AI,UAAkB;EACpB,OAAO,KAAKC;;CAGd,mBAA2B;EACzB,OAAO,wBAAwB,KAAKH,QAAQ;GAC1C,MAAM,KAAKC,MAAM;GACjB,IAAI,KAAKA,MAAM;GACf,GAAG,UAAU,UAAU,KAAKA,MAAM,OAAO;GAC1C,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as TypeScriptRenderableSqliteMigration } from "./planner-produced-sqlite-migration-
|
|
1
|
+
import { t as TypeScriptRenderableSqliteMigration } from "./planner-produced-sqlite-migration-BqzfeOFu.mjs";
|
|
2
2
|
export { TypeScriptRenderableSqliteMigration };
|
package/dist/planner.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as createSqliteMigrationPlanner, t as SqliteMigrationPlanner } from "./planner-
|
|
1
|
+
import { n as createSqliteMigrationPlanner, t as SqliteMigrationPlanner } from "./planner-B9-16QqD.mjs";
|
|
2
2
|
export { SqliteMigrationPlanner, createSqliteMigrationPlanner };
|
package/package.json
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/target-sqlite",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0-dev.1",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"dependencies": {
|
|
8
|
-
"@prisma-next/cli": "0.
|
|
9
|
-
"@prisma-next/contract": "0.
|
|
10
|
-
"@prisma-next/errors": "0.
|
|
11
|
-
"@prisma-next/family-sql": "0.
|
|
12
|
-
"@prisma-next/framework-components": "0.
|
|
13
|
-
"@prisma-next/migration-tools": "0.
|
|
14
|
-
"@prisma-next/sql-contract": "0.
|
|
15
|
-
"@prisma-next/sql-errors": "0.
|
|
16
|
-
"@prisma-next/sql-relational-core": "0.
|
|
17
|
-
"@prisma-next/sql-runtime": "0.
|
|
18
|
-
"@prisma-next/sql-schema-ir": "0.
|
|
19
|
-
"@prisma-next/ts-render": "0.
|
|
20
|
-
"@prisma-next/utils": "0.
|
|
8
|
+
"@prisma-next/cli": "0.11.0-dev.1",
|
|
9
|
+
"@prisma-next/contract": "0.11.0-dev.1",
|
|
10
|
+
"@prisma-next/errors": "0.11.0-dev.1",
|
|
11
|
+
"@prisma-next/family-sql": "0.11.0-dev.1",
|
|
12
|
+
"@prisma-next/framework-components": "0.11.0-dev.1",
|
|
13
|
+
"@prisma-next/migration-tools": "0.11.0-dev.1",
|
|
14
|
+
"@prisma-next/sql-contract": "0.11.0-dev.1",
|
|
15
|
+
"@prisma-next/sql-errors": "0.11.0-dev.1",
|
|
16
|
+
"@prisma-next/sql-relational-core": "0.11.0-dev.1",
|
|
17
|
+
"@prisma-next/sql-runtime": "0.11.0-dev.1",
|
|
18
|
+
"@prisma-next/sql-schema-ir": "0.11.0-dev.1",
|
|
19
|
+
"@prisma-next/ts-render": "0.11.0-dev.1",
|
|
20
|
+
"@prisma-next/utils": "0.11.0-dev.1",
|
|
21
21
|
"@standard-schema/spec": "1.1.0"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
|
-
"@prisma-next/driver-sqlite": "0.
|
|
25
|
-
"@prisma-next/test-utils": "0.
|
|
26
|
-
"@prisma-next/tsconfig": "0.
|
|
27
|
-
"@prisma-next/tsdown": "0.
|
|
24
|
+
"@prisma-next/driver-sqlite": "0.11.0-dev.1",
|
|
25
|
+
"@prisma-next/test-utils": "0.11.0-dev.1",
|
|
26
|
+
"@prisma-next/tsconfig": "0.11.0-dev.1",
|
|
27
|
+
"@prisma-next/tsdown": "0.11.0-dev.1",
|
|
28
28
|
"tsdown": "0.22.0",
|
|
29
29
|
"typescript": "5.9.3",
|
|
30
30
|
"vitest": "4.1.6"
|
|
@@ -26,7 +26,7 @@ import type { SqlitePlanTargetDetails } from './planner-target-details';
|
|
|
26
26
|
|
|
27
27
|
type Op = SqlMigrationPlanOperation<SqlitePlanTargetDetails>;
|
|
28
28
|
|
|
29
|
-
const TARGET_MIGRATION_MODULE = '@prisma-next/
|
|
29
|
+
const TARGET_MIGRATION_MODULE = '@prisma-next/sqlite/migration';
|
|
30
30
|
|
|
31
31
|
abstract class SqliteOpFactoryCallNode extends TsExpression implements FrameworkOpFactoryCall {
|
|
32
32
|
abstract readonly factoryName: string;
|
|
@@ -16,11 +16,11 @@ export interface RenderMigrationMeta {
|
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
18
|
* Always-present base imports for the rendered scaffold. Both come from
|
|
19
|
-
* `@prisma-next/
|
|
19
|
+
* `@prisma-next/sqlite/migration` so an authored SQLite
|
|
20
20
|
* `migration.ts` only needs a single dependency for its base class and
|
|
21
21
|
* its CLI entrypoint. Mirrors Postgres's `BASE_IMPORTS`.
|
|
22
22
|
*
|
|
23
|
-
* - `Migration` — the
|
|
23
|
+
* - `Migration` — the facade re-export fixes the `SqlMigration`
|
|
24
24
|
* generic to `SqlitePlanTargetDetails` and the abstract `targetId` to
|
|
25
25
|
* `'sqlite'`.
|
|
26
26
|
* - `MigrationCLI` — the migration-file CLI entrypoint, re-exported from
|
|
@@ -28,8 +28,8 @@ export interface RenderMigrationMeta {
|
|
|
28
28
|
* assembles a `ControlStack`, and instantiates the migration class.
|
|
29
29
|
*/
|
|
30
30
|
const BASE_IMPORTS: readonly ImportRequirement[] = [
|
|
31
|
-
{ moduleSpecifier: '@prisma-next/
|
|
32
|
-
{ moduleSpecifier: '@prisma-next/
|
|
31
|
+
{ moduleSpecifier: '@prisma-next/sqlite/migration', symbol: 'Migration' },
|
|
32
|
+
{ moduleSpecifier: '@prisma-next/sqlite/migration', symbol: 'MigrationCLI' },
|
|
33
33
|
];
|
|
34
34
|
|
|
35
35
|
export function renderCallsToTypeScript(
|
package/src/exports/migration.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// Re-exported so a SQLite `migration.ts` only needs the single
|
|
2
|
-
// `@prisma-next/
|
|
3
|
-
//
|
|
2
|
+
// `@prisma-next/sqlite/migration` import for its base class and the CLI
|
|
3
|
+
// entrypoint, mirroring how `placeholder` is surfaced here. The
|
|
4
4
|
// renderer emits the entrypoint call as
|
|
5
5
|
// `MigrationCLI.run(import.meta.url, M)`.
|
|
6
6
|
export { MigrationCLI } from '@prisma-next/cli/migration-cli';
|
|
7
7
|
// Re-exported so user-edited migration.ts files only need to depend on
|
|
8
|
-
// `@prisma-next/
|
|
8
|
+
// `@prisma-next/sqlite/migration` to fill in planner-emitted
|
|
9
9
|
// `placeholder("…")` slots, instead of pulling in `@prisma-next/errors`
|
|
10
10
|
// directly. The planner emits an import from this same module.
|
|
11
11
|
export { placeholder } from '@prisma-next/errors/migration';
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"op-factory-call-BRp16Nsr.mjs","names":[],"sources":["../src/core/migrations/op-factory-call.ts"],"sourcesContent":["/**\n * SQLite migration IR: one concrete `*Call` class per pure factory under\n * `operations/`, plus a shared `SqliteOpFactoryCallNode` abstract base.\n *\n * Each call class carries fully-resolved literal arguments (flat\n * `SqliteColumnSpec` / `SqliteTableSpec` etc.) — codec / `typeRef` / default\n * expansion happens upstream in the issue-planner / strategies, mirroring\n * the Postgres `ColumnSpec` pattern. As a result, `toOp()` and\n * `renderTypeScript()` both pass the same flat data through; the rendered\n * TypeScript scaffold is fully self-contained and does not need access to a\n * `storageTypes` map at runtime.\n */\n\nimport { errorUnfilledPlaceholder } from '@prisma-next/errors/migration';\nimport type {\n MigrationOperationClass,\n SqlMigrationPlanOperation,\n} from '@prisma-next/family-sql/control';\nimport type { OpFactoryCall as FrameworkOpFactoryCall } from '@prisma-next/framework-components/control';\nimport { type ImportRequirement, jsonToTsSource, TsExpression } from '@prisma-next/ts-render';\nimport { addColumn, dropColumn } from './operations/columns';\nimport { createIndex, dropIndex } from './operations/indexes';\nimport type { SqliteColumnSpec, SqliteIndexSpec, SqliteTableSpec } from './operations/shared';\nimport { createTable, dropTable, recreateTable } from './operations/tables';\nimport type { SqlitePlanTargetDetails } from './planner-target-details';\n\ntype Op = SqlMigrationPlanOperation<SqlitePlanTargetDetails>;\n\nconst TARGET_MIGRATION_MODULE = '@prisma-next/target-sqlite/migration';\n\nabstract class SqliteOpFactoryCallNode extends TsExpression implements FrameworkOpFactoryCall {\n abstract readonly factoryName: string;\n abstract readonly operationClass: MigrationOperationClass;\n abstract readonly label: string;\n abstract toOp(): Op;\n\n importRequirements(): readonly ImportRequirement[] {\n return [{ moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: this.factoryName }];\n }\n\n protected freeze(): void {\n Object.freeze(this);\n }\n}\n\n// ============================================================================\n// Table\n// ============================================================================\n\nexport class CreateTableCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'createTable' as const;\n readonly operationClass = 'additive' as const;\n readonly tableName: string;\n readonly spec: SqliteTableSpec;\n readonly label: string;\n\n constructor(tableName: string, spec: SqliteTableSpec) {\n super();\n this.tableName = tableName;\n this.spec = spec;\n this.label = `Create table ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return createTable(this.tableName, this.spec);\n }\n\n renderTypeScript(): string {\n return `createTable(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.spec)})`;\n }\n}\n\nexport class DropTableCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'dropTable' as const;\n readonly operationClass = 'destructive' as const;\n readonly tableName: string;\n readonly label: string;\n\n constructor(tableName: string) {\n super();\n this.tableName = tableName;\n this.label = `Drop table ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropTable(this.tableName);\n }\n\n renderTypeScript(): string {\n return `dropTable(${jsonToTsSource(this.tableName)})`;\n }\n}\n\nexport class RecreateTableCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'recreateTable' as const;\n readonly operationClass: MigrationOperationClass;\n readonly tableName: string;\n readonly contractTable: SqliteTableSpec;\n readonly schemaColumnNames: readonly string[];\n readonly indexes: readonly SqliteIndexSpec[];\n readonly summary: string;\n readonly postchecks: readonly { readonly description: string; readonly sql: string }[];\n readonly label: string;\n\n constructor(args: {\n tableName: string;\n contractTable: SqliteTableSpec;\n schemaColumnNames: readonly string[];\n indexes: readonly SqliteIndexSpec[];\n summary: string;\n postchecks: readonly { readonly description: string; readonly sql: string }[];\n operationClass: MigrationOperationClass;\n }) {\n super();\n this.tableName = args.tableName;\n this.contractTable = args.contractTable;\n this.schemaColumnNames = args.schemaColumnNames;\n this.indexes = args.indexes;\n this.summary = args.summary;\n this.postchecks = args.postchecks;\n this.operationClass = args.operationClass;\n this.label = `Recreate table ${args.tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return recreateTable({\n tableName: this.tableName,\n contractTable: this.contractTable,\n schemaColumnNames: this.schemaColumnNames,\n indexes: this.indexes,\n summary: this.summary,\n postchecks: this.postchecks,\n operationClass: this.operationClass,\n });\n }\n\n renderTypeScript(): string {\n const args = {\n tableName: this.tableName,\n contractTable: this.contractTable,\n schemaColumnNames: this.schemaColumnNames,\n indexes: this.indexes,\n summary: this.summary,\n postchecks: this.postchecks,\n operationClass: this.operationClass,\n };\n return `recreateTable(${jsonToTsSource(args)})`;\n }\n}\n\n// ============================================================================\n// Column\n// ============================================================================\n\nexport class AddColumnCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'addColumn' as const;\n readonly operationClass = 'additive' as const;\n readonly tableName: string;\n readonly columnName: string;\n readonly column: SqliteColumnSpec;\n readonly label: string;\n\n constructor(tableName: string, column: SqliteColumnSpec) {\n super();\n this.tableName = tableName;\n this.columnName = column.name;\n this.column = column;\n this.label = `Add column ${column.name} on ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return addColumn(this.tableName, this.column);\n }\n\n renderTypeScript(): string {\n return `addColumn(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.column)})`;\n }\n}\n\nexport class DropColumnCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'dropColumn' as const;\n readonly operationClass = 'destructive' as const;\n readonly tableName: string;\n readonly columnName: string;\n readonly label: string;\n\n constructor(tableName: string, columnName: string) {\n super();\n this.tableName = tableName;\n this.columnName = columnName;\n this.label = `Drop column ${columnName} on ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropColumn(this.tableName, this.columnName);\n }\n\n renderTypeScript(): string {\n return `dropColumn(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.columnName)})`;\n }\n}\n\n// ============================================================================\n// Index\n// ============================================================================\n\nexport class CreateIndexCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'createIndex' as const;\n readonly operationClass = 'additive' as const;\n readonly tableName: string;\n readonly indexName: string;\n readonly columns: readonly string[];\n readonly label: string;\n\n constructor(tableName: string, indexName: string, columns: readonly string[]) {\n super();\n this.tableName = tableName;\n this.indexName = indexName;\n this.columns = columns;\n this.label = `Create index ${indexName} on ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return createIndex(this.tableName, this.indexName, this.columns);\n }\n\n renderTypeScript(): string {\n return `createIndex(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.indexName)}, ${jsonToTsSource(this.columns)})`;\n }\n}\n\nexport class DropIndexCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'dropIndex' as const;\n readonly operationClass = 'destructive' as const;\n readonly tableName: string;\n readonly indexName: string;\n readonly label: string;\n\n constructor(tableName: string, indexName: string) {\n super();\n this.tableName = tableName;\n this.indexName = indexName;\n this.label = `Drop index ${indexName} on ${tableName}`;\n this.freeze();\n }\n\n toOp(): Op {\n return dropIndex(this.tableName, this.indexName);\n }\n\n renderTypeScript(): string {\n return `dropIndex(${jsonToTsSource(this.tableName)}, ${jsonToTsSource(this.indexName)})`;\n }\n}\n\n// ============================================================================\n// Data transform\n// ============================================================================\n\n/**\n * A planner-generated data-transform stub. The current default strategy\n * (`nullabilityTighteningBackfillStrategy`) emits one of these with a\n * backfill-flavored `id`/`label` when the policy allows `'data'` and the\n * contract tightens a column's nullability, but the op itself is generic —\n * any future strategy that needs a placeholder data step can construct one\n * with its own id/label.\n *\n * `toOp()` always throws `PN-MIG-2001`: the planner cannot lower a stubbed\n * transform to a runtime op — the user must edit the rendered\n * `migration.ts` and re-emit.\n */\nexport class DataTransformCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'dataTransform' as const;\n readonly operationClass = 'data' as const;\n readonly id: string;\n readonly label: string;\n readonly tableName: string;\n readonly columnName: string;\n\n constructor(id: string, label: string, tableName: string, columnName: string) {\n super();\n this.id = id;\n this.label = label;\n this.tableName = tableName;\n this.columnName = columnName;\n this.freeze();\n }\n\n toOp(): Op {\n throw errorUnfilledPlaceholder(this.label);\n }\n\n renderTypeScript(): string {\n const slot = `${this.tableName}-${this.columnName}-backfill-sql`;\n return [\n 'dataTransform({',\n ` id: ${jsonToTsSource(this.id)},`,\n ` label: ${jsonToTsSource(this.label)},`,\n ` table: ${jsonToTsSource(this.tableName)},`,\n ` description: ${jsonToTsSource(`Backfill NULL ${this.columnName} values in ${this.tableName}`)},`,\n ` run: () => placeholder(${jsonToTsSource(slot)}),`,\n '})',\n ].join('\\n');\n }\n\n override importRequirements(): readonly ImportRequirement[] {\n return [\n { moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: this.factoryName },\n { moduleSpecifier: TARGET_MIGRATION_MODULE, symbol: 'placeholder' },\n ];\n }\n}\n\n// ============================================================================\n// Raw SQL\n// ============================================================================\n\n/**\n * Laundered pre-built operation. Mirrors Postgres's `RawSqlCall`: wraps an\n * already-materialized `SqlMigrationPlanOperation` (typically produced by a\n * SQL-family helper or a codec lifecycle hook) so the planner can carry it\n * alongside structured call IR. `toOp()` returns the stored op unchanged;\n * `renderTypeScript()` emits `rawSql({...})` with the op serialized as a\n * JSON literal — round-tripping requires every field on the op to be\n * JSON-serializable (no closures).\n */\nexport class RawSqlCall extends SqliteOpFactoryCallNode {\n readonly factoryName = 'rawSql' as const;\n readonly operationClass: MigrationOperationClass;\n readonly label: string;\n readonly op: Op;\n\n constructor(op: Op) {\n super();\n this.op = op;\n this.label = op.label;\n this.operationClass = op.operationClass;\n this.freeze();\n }\n\n toOp(): Op {\n return this.op;\n }\n\n renderTypeScript(): string {\n return `rawSql(${jsonToTsSource(this.op)})`;\n }\n}\n\n// ============================================================================\n// Union\n// ============================================================================\n\nexport type SqliteOpFactoryCall =\n | CreateTableCall\n | DropTableCall\n | RecreateTableCall\n | AddColumnCall\n | DropColumnCall\n | CreateIndexCall\n | DropIndexCall\n | DataTransformCall\n | RawSqlCall;\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAM,0BAA0B;AAEhC,IAAe,0BAAf,cAA+C,aAA+C;CAM5F,qBAAmD;EACjD,OAAO,CAAC;GAAE,iBAAiB;GAAyB,QAAQ,KAAK;GAAa,CAAC;;CAGjF,SAAyB;EACvB,OAAO,OAAO,KAAK;;;AAQvB,IAAa,kBAAb,cAAqC,wBAAwB;CAC3D,cAAuB;CACvB,iBAA0B;CAC1B;CACA;CACA;CAEA,YAAY,WAAmB,MAAuB;EACpD,OAAO;EACP,KAAK,YAAY;EACjB,KAAK,OAAO;EACZ,KAAK,QAAQ,gBAAgB;EAC7B,KAAK,QAAQ;;CAGf,OAAW;EACT,OAAO,YAAY,KAAK,WAAW,KAAK,KAAK;;CAG/C,mBAA2B;EACzB,OAAO,eAAe,eAAe,KAAK,UAAU,CAAC,IAAI,eAAe,KAAK,KAAK,CAAC;;;AAIvF,IAAa,gBAAb,cAAmC,wBAAwB;CACzD,cAAuB;CACvB,iBAA0B;CAC1B;CACA;CAEA,YAAY,WAAmB;EAC7B,OAAO;EACP,KAAK,YAAY;EACjB,KAAK,QAAQ,cAAc;EAC3B,KAAK,QAAQ;;CAGf,OAAW;EACT,OAAO,UAAU,KAAK,UAAU;;CAGlC,mBAA2B;EACzB,OAAO,aAAa,eAAe,KAAK,UAAU,CAAC;;;AAIvD,IAAa,oBAAb,cAAuC,wBAAwB;CAC7D,cAAuB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,MAQT;EACD,OAAO;EACP,KAAK,YAA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U,GAAG,KAAK,WAAW;EAClD,OAAO;GACL;GACA,SAAS,eAAe,KAAK,GAAG,CAAC;GACjC,YAAY,eAAe,KAAK,MAAM,CAAC;GACvC,YAAY,eAAe,KAAK,UAAU,CAAC;GAC3C,kBAAkB,eAAe,iBAAiB,KAAK,WAAW,aAAa,KAAK,YAAY,CAAC;GACjG,4BAA4B,eAAe,KAAK,CAAC;GACjD;GACD,CAAC,KAAK,KAAK;;CAGd,qBAA4D;EAC1D,OAAO,CACL;GAAE,iBAAiB;GAAyB,QAAQ,KAAK;GAAa,EACtE;GAAE,iBAAiB;GAAyB,QAAQ;GAAe,CACpE;;;;;;;;;;;;AAiBL,IAAa,aAAb,cAAgC,wBAAwB;CACtD,cAAuB;CACvB;CACA;CACA;CAEA,YAAY,IAAQ;EAClB,OAAO;EACP,KAAK,KAAK;EACV,KAAK,QAAQ,GAAG;EAChB,KAAK,iBAAiB,GAAG;EACzB,KAAK,QAAQ;;CAGf,OAAW;EACT,OAAO,KAAK;;CAGd,mBAA2B;EACzB,OAAO,UAAU,eAAe,KAAK,GAAG,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"planner-produced-sqlite-migration-C_TzWbT0.mjs","names":["#calls","#meta","#destination","#spaceId"],"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, jsonToTsSource, renderImports } from '@prisma-next/ts-render';\n\nexport interface RenderMigrationMeta {\n readonly from: string | null;\n readonly to: string;\n readonly labels?: readonly string[];\n}\n\n/**\n * Always-present base imports for the rendered scaffold. Both come from\n * `@prisma-next/target-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 target-owned 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/target-sqlite/migration', symbol: 'Migration' },\n { moduleSpecifier: '@prisma-next/target-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 if (meta.labels && meta.labels.length > 0) {\n lines.push(` labels: ${jsonToTsSource(meta.labels)},`);\n }\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 {\n MigrationPlanWithAuthoringSurface,\n OpFactoryCall,\n} from '@prisma-next/framework-components/control';\nimport type { MigrationMeta } from '@prisma-next/migration-tools/migration';\nimport { ifDefined } from '@prisma-next/utils/defined';\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\n constructor(\n calls: readonly OpFactoryCall[],\n meta: MigrationMeta,\n spaceId: string,\n destination?: SqliteMigrationDestinationInfo,\n ) {\n super();\n this.#calls = calls;\n this.#meta = meta;\n this.#spaceId = spaceId;\n this.#destination = destination ?? { storageHash: meta.to };\n }\n\n override get operations(): readonly Op[] {\n return renderOps(this.#calls);\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 ...ifDefined('labels', this.#meta.labels),\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6BA,MAAM,eAA6C,CACjD;CAAE,i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