@prisma-next/target-sqlite 0.14.0-dev.6 → 0.14.0-dev.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/contract-free.mjs +1 -1
  2. package/dist/control.d.mts +3 -4
  3. package/dist/control.d.mts.map +1 -1
  4. package/dist/control.mjs +16 -27
  5. package/dist/control.mjs.map +1 -1
  6. package/dist/{descriptor-meta-DxmEeTJ-.mjs → descriptor-meta-D1fap-5t.mjs} +4 -11
  7. package/dist/descriptor-meta-D1fap-5t.mjs.map +1 -0
  8. package/dist/descriptor-meta-runtime-BkXK3OjD.mjs +12 -0
  9. package/dist/descriptor-meta-runtime-BkXK3OjD.mjs.map +1 -0
  10. package/dist/migration.d.mts +2 -2
  11. package/dist/migration.mjs +2 -2
  12. package/dist/native-type-normalizer.mjs +13 -1
  13. package/dist/native-type-normalizer.mjs.map +1 -0
  14. package/dist/{op-factory-call-DmdfD1yd.mjs → op-factory-call-Do03QgD9.mjs} +134 -117
  15. package/dist/op-factory-call-Do03QgD9.mjs.map +1 -0
  16. package/dist/op-factory-call.d.mts +2 -2
  17. package/dist/op-factory-call.d.mts.map +1 -1
  18. package/dist/op-factory-call.mjs +1 -1
  19. package/dist/pack.mjs +1 -1
  20. package/dist/planner-DGhzXuGh.mjs +848 -0
  21. package/dist/planner-DGhzXuGh.mjs.map +1 -0
  22. package/dist/{planner-produced-sqlite-migration-0xPEm3R1.mjs → planner-produced-sqlite-migration-BDzhFAoW.mjs} +46 -17
  23. package/dist/planner-produced-sqlite-migration-BDzhFAoW.mjs.map +1 -0
  24. package/dist/{planner-produced-sqlite-migration-CpgsY-M9.d.mts → planner-produced-sqlite-migration-o1qUzwLk.d.mts} +3 -3
  25. package/dist/{planner-produced-sqlite-migration-CpgsY-M9.d.mts.map → planner-produced-sqlite-migration-o1qUzwLk.d.mts.map} +1 -1
  26. package/dist/planner-produced-sqlite-migration.d.mts +1 -1
  27. package/dist/planner-produced-sqlite-migration.mjs +1 -1
  28. package/dist/planner.d.mts +47 -11
  29. package/dist/planner.d.mts.map +1 -1
  30. package/dist/planner.mjs +1 -1
  31. package/dist/runtime.d.mts +6 -4
  32. package/dist/runtime.d.mts.map +1 -1
  33. package/dist/runtime.mjs +3 -3
  34. package/dist/{shared-Dhc8mLK1.d.mts → shared-C6sM-wel.d.mts} +2 -2
  35. package/dist/{shared-Dhc8mLK1.d.mts.map → shared-C6sM-wel.d.mts.map} +1 -1
  36. package/dist/{sqlite-contract-serializer--iaDgC8e.mjs → sqlite-contract-view-BEwi0mUC.mjs} +34 -9
  37. package/dist/sqlite-contract-view-BEwi0mUC.mjs.map +1 -0
  38. package/dist/sqlite-contract-view-J32K82Gi.d.mts +29 -0
  39. package/dist/sqlite-contract-view-J32K82Gi.d.mts.map +1 -0
  40. package/dist/sqlite-migration-BNiSiP0z.mjs +123 -0
  41. package/dist/sqlite-migration-BNiSiP0z.mjs.map +1 -0
  42. package/dist/{sqlite-migration-DVfhQwN_.d.mts → sqlite-migration-BYbzskpE.d.mts} +35 -6
  43. package/dist/sqlite-migration-BYbzskpE.d.mts.map +1 -0
  44. package/package.json +18 -18
  45. package/src/core/control-target.ts +13 -18
  46. package/src/core/errors.ts +14 -12
  47. package/src/core/migrations/column-ddl-rendering.ts +177 -0
  48. package/src/core/migrations/diff-database-schema.ts +230 -0
  49. package/src/core/migrations/issue-planner.ts +361 -488
  50. package/src/core/migrations/op-factory-call.ts +5 -0
  51. package/src/core/migrations/operations/tables.ts +107 -68
  52. package/src/core/migrations/planner-strategies.ts +118 -137
  53. package/src/core/migrations/planner.ts +117 -30
  54. package/src/core/migrations/render-typescript.ts +42 -15
  55. package/src/core/migrations/runner.ts +4 -10
  56. package/src/core/migrations/sqlite-migration.ts +69 -31
  57. package/src/core/sqlite-contract-serializer.ts +29 -14
  58. package/src/core/sqlite-contract-view.ts +41 -0
  59. package/src/core/sqlite-schema-verifier.ts +6 -3
  60. package/src/core/sqlite-unbound-database.ts +8 -8
  61. package/src/exports/runtime.ts +1 -0
  62. package/dist/descriptor-meta-DxmEeTJ-.mjs.map +0 -1
  63. package/dist/native-type-normalizer-CiSyVmMP.mjs +0 -14
  64. package/dist/native-type-normalizer-CiSyVmMP.mjs.map +0 -1
  65. package/dist/op-factory-call-DmdfD1yd.mjs.map +0 -1
  66. package/dist/planner-Ciq8p_dL.mjs +0 -622
  67. package/dist/planner-Ciq8p_dL.mjs.map +0 -1
  68. package/dist/planner-produced-sqlite-migration-0xPEm3R1.mjs.map +0 -1
  69. package/dist/sqlite-contract-serializer--iaDgC8e.mjs.map +0 -1
  70. package/dist/sqlite-migration-A0rwqPOG.mjs +0 -92
  71. package/dist/sqlite-migration-A0rwqPOG.mjs.map +0 -1
  72. package/dist/sqlite-migration-DVfhQwN_.d.mts.map +0 -1
@@ -1,622 +0,0 @@
1
- import { t as parseSqliteDefault } from "./default-normalizer-DuoHj9-O.mjs";
2
- import { t as normalizeSqliteNativeType } from "./native-type-normalizer-CiSyVmMP.mjs";
3
- import { t as CONTROL_TABLE_NAMES } from "./control-tables-7KwMyJ6i.mjs";
4
- import { a as DropColumnCall, d as buildRecreateSummary, f as buildColumnDefaultSql, g as resolveColumnTypeMetadata, i as DataTransformCall, l as RecreateTableCall, m as isInlineAutoincrementPrimaryKey, n as CreateIndexCall, o as DropIndexCall, p as buildColumnTypeSql, r as CreateTableCall, s as DropTableCall, t as AddColumnCall, u as buildRecreatePostchecks } from "./op-factory-call-DmdfD1yd.mjs";
5
- import { t as TypeScriptRenderableSqliteMigration } from "./planner-produced-sqlite-migration-0xPEm3R1.mjs";
6
- import { DdlColumn, ForeignKeyConstraint, FunctionColumnDefault, LiteralColumnDefault, PrimaryKeyConstraint, UniqueConstraint } from "@prisma-next/sql-relational-core/ast";
7
- import { extractCodecControlHooks, planFieldEventOperations, plannerFailure } from "@prisma-next/family-sql/control";
8
- import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
9
- import { verifySqlSchema } from "@prisma-next/family-sql/schema-verify";
10
- import { defaultIndexName } from "@prisma-next/sql-schema-ir/naming";
11
- import { blindCast } from "@prisma-next/utils/casts";
12
- import { ifDefined } from "@prisma-next/utils/defined";
13
- import { notOk, ok } from "@prisma-next/utils/result";
14
- //#region src/core/migrations/planner-strategies.ts
15
- /**
16
- * Look up a storage table by its explicit namespace coordinate. Returns
17
- * `undefined` when the namespace has no table by that name (or no such
18
- * namespace exists). Callers that get `undefined` MUST treat it as an
19
- * explicit conflict rather than silently falling back to a name-only
20
- * walk across namespaces — the SQLite target currently has a single
21
- * namespace, but this helper enforces the explicit-coordinate
22
- * discipline so a future multi-namespace SQLite shape inherits the
23
- * conflict-on-stale-coordinate behaviour the Postgres planner already
24
- * has.
25
- */
26
- function tableAt(storage, namespaceId, tableName) {
27
- const ns = storage.namespaces[namespaceId];
28
- return ns !== void 0 ? ns.entries.table?.[tableName] : void 0;
29
- }
30
- /**
31
- * Default namespace coordinate for an issue that does not carry one
32
- * explicitly. Hand-crafted unit-test issues fall back to `__unbound__`,
33
- * the only namespace any single-namespace contract carries —
34
- * verifier-emitted issues for legacy single-namespace contracts already
35
- * stamp this id explicitly. Typed structurally so issue variants
36
- * without a `namespaceId` slot flow through to the same fallback.
37
- */
38
- function resolveNamespaceIdForIssue(issue) {
39
- return issue.namespaceId ?? UNBOUND_NAMESPACE_ID;
40
- }
41
- const WIDENING_ISSUE_KINDS = new Set(["default_mismatch", "default_missing"]);
42
- const DESTRUCTIVE_ISSUE_KINDS = new Set([
43
- "extra_default",
44
- "type_mismatch",
45
- "primary_key_mismatch",
46
- "foreign_key_mismatch",
47
- "unique_constraint_mismatch",
48
- "extra_foreign_key",
49
- "extra_unique_constraint",
50
- "extra_primary_key"
51
- ]);
52
- function classifyIssue(issue) {
53
- if (issue.kind === "enum_values_changed") return null;
54
- if (!issue.table) return null;
55
- if (issue.kind === "nullability_mismatch") return issue.expected === "true" ? "widening" : "destructive";
56
- if (WIDENING_ISSUE_KINDS.has(issue.kind)) return "widening";
57
- if (DESTRUCTIVE_ISSUE_KINDS.has(issue.kind)) return "destructive";
58
- return null;
59
- }
60
- /**
61
- * Groups recreate-eligible issues by table, decides per-table operation class
62
- * (destructive wins over widening), and emits one `RecreateTableCall` per
63
- * table. Returns unchanged-or-smaller issue list — issues the strategy
64
- * consumed are removed so `mapIssueToCall` doesn't double-handle them.
65
- */
66
- const recreateTableStrategy = (issues, ctx) => {
67
- const byTable = /* @__PURE__ */ new Map();
68
- const consumed = /* @__PURE__ */ new Set();
69
- for (const issue of issues) {
70
- const cls = classifyIssue(issue);
71
- if (!cls) continue;
72
- if (issue.kind === "enum_values_changed") continue;
73
- if (!issue.table) continue;
74
- const table = issue.table;
75
- const entry = byTable.get(table);
76
- if (entry) {
77
- entry.issues.push(issue);
78
- if (cls === "destructive") entry.hasDestructive = true;
79
- } else byTable.set(table, {
80
- issues: [issue],
81
- hasDestructive: cls === "destructive",
82
- namespaceId: resolveNamespaceIdForIssue(issue)
83
- });
84
- consumed.add(issue);
85
- }
86
- if (byTable.size === 0) return { kind: "no_match" };
87
- const calls = [];
88
- for (const [tableName, entry] of byTable) {
89
- const contractTable = tableAt(ctx.toContract.storage, entry.namespaceId, tableName);
90
- const schemaTable = ctx.schema.tables[tableName];
91
- if (!contractTable || !schemaTable) continue;
92
- const operationClass = entry.hasDestructive ? "destructive" : "widening";
93
- const tableSpec = toTableSpec(contractTable, ctx.storageTypes);
94
- const seenIndexColumnKeys = /* @__PURE__ */ new Set();
95
- const indexes = [];
96
- for (const idx of contractTable.indexes) {
97
- const key = idx.columns.join(",");
98
- if (seenIndexColumnKeys.has(key)) continue;
99
- seenIndexColumnKeys.add(key);
100
- indexes.push({
101
- name: idx.name ?? defaultIndexName(tableName, idx.columns),
102
- columns: idx.columns
103
- });
104
- }
105
- for (const fk of contractTable.foreignKeys) {
106
- if (fk.index === false) continue;
107
- const key = fk.source.columns.join(",");
108
- if (seenIndexColumnKeys.has(key)) continue;
109
- seenIndexColumnKeys.add(key);
110
- indexes.push({
111
- name: defaultIndexName(tableName, fk.source.columns),
112
- columns: fk.source.columns
113
- });
114
- }
115
- calls.push(new RecreateTableCall({
116
- tableName,
117
- contractTable: tableSpec,
118
- schemaColumnNames: Object.keys(schemaTable.columns),
119
- indexes,
120
- summary: buildRecreateSummary(tableName, entry.issues),
121
- postchecks: buildRecreatePostchecks(tableName, entry.issues, tableSpec),
122
- operationClass
123
- }));
124
- }
125
- return {
126
- kind: "match",
127
- issues: issues.filter((i) => !consumed.has(i)),
128
- calls,
129
- recipe: true
130
- };
131
- };
132
- /**
133
- * When the policy allows `'data'` and the contract tightens one or more
134
- * columns from nullable to NOT NULL, emit a `DataTransformCall` stub per
135
- * tightened column. The user fills the backfill `UPDATE` in the rendered
136
- * `migration.ts` before the subsequent `RecreateTableCall` copies data into
137
- * the tightened schema (whose `INSERT INTO temp SELECT … FROM old` would
138
- * otherwise fail at runtime if any `NULL`s remain).
139
- *
140
- * Does NOT consume the tightening issue — `recreateTableStrategy` still
141
- * needs it to produce the actual recreate that enforces the NOT NULL at
142
- * the schema level. The backfill op and the recreate op end up in the
143
- * recipe slot in strategy order (backfill first, recreate second), which
144
- * matches the required execution order.
145
- *
146
- * Mirrors Postgres's `nullableTighteningCallStrategy` / `'data'`-class
147
- * gating. When `'data'` is not in the policy (the default `db update` /
148
- * `db init` path), the strategy short-circuits and the recreate alone
149
- * runs with its current destructive-class gating — preserving today's
150
- * behavior where a tightening blows up at runtime if NULLs are present.
151
- */
152
- const nullabilityTighteningBackfillStrategy = (issues, ctx) => {
153
- if (!ctx.policy.allowedOperationClasses.includes("data")) return { kind: "no_match" };
154
- const calls = [];
155
- for (const issue of issues) {
156
- if (issue.kind !== "nullability_mismatch") continue;
157
- if (!issue.table || !issue.column) continue;
158
- if (issue.expected === "true") continue;
159
- const namespaceId = resolveNamespaceIdForIssue(issue);
160
- const column = tableAt(ctx.toContract.storage, namespaceId, issue.table)?.columns[issue.column];
161
- if (!column || column.nullable === true) continue;
162
- calls.push(new DataTransformCall(`data_migration.backfill-${issue.table}-${issue.column}`, `Backfill NULLs in "${issue.table}"."${issue.column}" before NOT NULL tightening`, issue.table, issue.column));
163
- }
164
- if (calls.length === 0) return { kind: "no_match" };
165
- return {
166
- kind: "match",
167
- issues,
168
- calls,
169
- recipe: true
170
- };
171
- };
172
- const sqlitePlannerStrategies = [nullabilityTighteningBackfillStrategy, recreateTableStrategy];
173
- //#endregion
174
- //#region src/core/migrations/issue-planner.ts
175
- const ISSUE_KIND_ORDER = {
176
- extra_foreign_key: 10,
177
- extra_unique_constraint: 11,
178
- extra_primary_key: 12,
179
- extra_index: 13,
180
- extra_default: 14,
181
- extra_column: 15,
182
- extra_table: 16,
183
- missing_table: 20,
184
- missing_column: 30,
185
- type_mismatch: 40,
186
- nullability_mismatch: 41,
187
- default_missing: 42,
188
- default_mismatch: 43,
189
- primary_key_mismatch: 50,
190
- unique_constraint_mismatch: 51,
191
- index_mismatch: 52,
192
- foreign_key_mismatch: 60
193
- };
194
- function issueOrder(issue) {
195
- return ISSUE_KIND_ORDER[issue.kind] ?? 99;
196
- }
197
- function issueKey(issue) {
198
- return `${"table" in issue && typeof issue.table === "string" ? issue.table : ""}\u0000${"column" in issue && typeof issue.column === "string" ? issue.column : ""}\u0000${"indexOrConstraint" in issue && typeof issue.indexOrConstraint === "string" ? issue.indexOrConstraint : ""}`;
199
- }
200
- function issueConflict(kind, summary, location) {
201
- return {
202
- kind,
203
- summary,
204
- why: "Use `migration new` to author a custom migration for this change.",
205
- ...location ? { location } : {}
206
- };
207
- }
208
- function conflictKindForIssue(issue) {
209
- switch (issue.kind) {
210
- case "type_mismatch": return "typeMismatch";
211
- case "nullability_mismatch": return "nullabilityConflict";
212
- case "primary_key_mismatch":
213
- case "unique_constraint_mismatch":
214
- case "index_mismatch":
215
- case "extra_primary_key":
216
- case "extra_unique_constraint": return "indexIncompatible";
217
- case "foreign_key_mismatch":
218
- case "extra_foreign_key": return "foreignKeyConflict";
219
- default: return "missingButNonAdditive";
220
- }
221
- }
222
- function issueLocation(issue) {
223
- if (issue.kind === "enum_values_changed") return void 0;
224
- const location = {};
225
- if (issue.table) location.table = issue.table;
226
- if (issue.column) location.column = issue.column;
227
- if (issue.indexOrConstraint) location.constraint = issue.indexOrConstraint;
228
- return Object.keys(location).length > 0 ? location : void 0;
229
- }
230
- function conflictForDisallowedCall(call, allowed) {
231
- const summary = `Operation "${call.label}" requires class "${call.operationClass}", but policy allows only: ${allowed.join(", ")}`;
232
- const location = locationForCall(call);
233
- return {
234
- kind: conflictKindForCall(call),
235
- summary,
236
- why: "Use `migration new` to author a custom migration for this change.",
237
- ...location ? { location } : {}
238
- };
239
- }
240
- function conflictKindForCall(call) {
241
- switch (call.factoryName) {
242
- case "createIndex":
243
- case "dropIndex": return "indexIncompatible";
244
- default: return "missingButNonAdditive";
245
- }
246
- }
247
- function locationForCall(call) {
248
- const location = {};
249
- if ("tableName" in call) location.table = call.tableName;
250
- if ("columnName" in call) location.column = call.columnName;
251
- if ("indexName" in call) location.index = call.indexName;
252
- return Object.keys(location).length > 0 ? location : void 0;
253
- }
254
- function isMissing(issue) {
255
- if (issue.kind === "enum_values_changed") return false;
256
- return issue.actual === void 0;
257
- }
258
- /**
259
- * Resolves codec / `typeRef` / default rendering into a flat
260
- * `SqliteColumnSpec`. Mirrors Postgres's `toColumnSpec`. Once a column is
261
- * flattened, downstream Calls and operation factories never see
262
- * `StorageColumn` again — they deal in pre-rendered SQL fragments.
263
- */
264
- function toColumnSpec(name, column, storageTypes, inlineAutoincrementPrimaryKey = false) {
265
- return {
266
- name,
267
- typeSql: buildColumnTypeSql(column, blindCast(storageTypes)),
268
- defaultSql: buildColumnDefaultSql(column.default),
269
- nullable: column.nullable,
270
- ...inlineAutoincrementPrimaryKey ? { inlineAutoincrementPrimaryKey: true } : {}
271
- };
272
- }
273
- /**
274
- * Flattens a `StorageTable` into a `SqliteTableSpec` ready for
275
- * `CreateTableCall` / `RecreateTableCall`. Sole-column AUTOINCREMENT
276
- * primary keys are detected here and marked on the column spec so the
277
- * renderer emits `INTEGER PRIMARY KEY AUTOINCREMENT` inline.
278
- */
279
- function toTableSpec(table, storageTypes) {
280
- const columns = Object.entries(table.columns).map(([name, column]) => toColumnSpec(name, column, storageTypes, isInlineAutoincrementPrimaryKey(table, name)));
281
- const uniques = table.uniques.map((u) => ({
282
- columns: u.columns,
283
- ...u.name !== void 0 ? { name: u.name } : {}
284
- }));
285
- const foreignKeys = table.foreignKeys.map((fk) => ({
286
- columns: fk.source.columns,
287
- references: {
288
- table: fk.target.tableName,
289
- columns: fk.target.columns
290
- },
291
- constraint: fk.constraint !== false,
292
- ...fk.name !== void 0 ? { name: fk.name } : {},
293
- ...fk.onDelete !== void 0 ? { onDelete: fk.onDelete } : {},
294
- ...fk.onUpdate !== void 0 ? { onUpdate: fk.onUpdate } : {}
295
- }));
296
- return {
297
- columns,
298
- ...table.primaryKey ? { primaryKey: { columns: table.primaryKey.columns } } : {},
299
- uniques,
300
- foreignKeys
301
- };
302
- }
303
- function sqliteDefaultToDdlColumnDefault(columnDefault) {
304
- if (!columnDefault) return void 0;
305
- switch (columnDefault.kind) {
306
- case "literal": return new LiteralColumnDefault(columnDefault.value);
307
- case "function":
308
- if (columnDefault.expression === "autoincrement()") return void 0;
309
- return new FunctionColumnDefault(columnDefault.expression);
310
- default: throw new Error(`sqliteDefaultToDdlColumnDefault: unhandled kind "${blindCast(columnDefault).kind}"`);
311
- }
312
- }
313
- /**
314
- * Converts a `StorageTable` to the `DdlColumn[]` + `DdlTableConstraint[]`
315
- * pair used by `CreateTableCall`. This is the structured form consumed by
316
- * the DDL lowering path; `toTableSpec` / `toColumnSpec` remain in use for
317
- * `RecreateTableCall` and `AddColumnCall` (Phase 2).
318
- */
319
- function tableToDdlParts(table, storageTypes) {
320
- const columns = Object.entries(table.columns).map(([name, column]) => {
321
- const inlineAutoincrement = isInlineAutoincrementPrimaryKey(table, name);
322
- const typeSql = buildColumnTypeSql(column, blindCast(storageTypes));
323
- if (inlineAutoincrement) return new DdlColumn({
324
- name,
325
- type: `${typeSql} PRIMARY KEY AUTOINCREMENT`
326
- });
327
- const colDefault = sqliteDefaultToDdlColumnDefault(column.default);
328
- const resolved = resolveColumnTypeMetadata(column, blindCast(storageTypes));
329
- const codecRef = resolved.codecId ? {
330
- codecId: resolved.codecId,
331
- ...resolved.typeParams !== void 0 ? { typeParams: blindCast(resolved.typeParams) } : {}
332
- } : void 0;
333
- return new DdlColumn({
334
- name,
335
- type: typeSql,
336
- ...!column.nullable ? { notNull: true } : {},
337
- ...colDefault !== void 0 ? { default: colDefault } : {},
338
- ...codecRef !== void 0 ? { codecRef } : {}
339
- });
340
- });
341
- const constraints = [];
342
- const hasInlinePk = Object.entries(table.columns).some(([name]) => isInlineAutoincrementPrimaryKey(table, name));
343
- if (table.primaryKey && !hasInlinePk) constraints.push(new PrimaryKeyConstraint({ columns: table.primaryKey.columns }));
344
- for (const u of table.uniques) constraints.push(new UniqueConstraint({
345
- columns: u.columns,
346
- ...u.name !== void 0 ? { name: u.name } : {}
347
- }));
348
- for (const fk of table.foreignKeys) {
349
- if (fk.constraint === false) continue;
350
- constraints.push(new ForeignKeyConstraint({
351
- columns: fk.source.columns,
352
- refTable: fk.target.tableName,
353
- refColumns: fk.target.columns,
354
- ...ifDefined("name", fk.name),
355
- ...ifDefined("onDelete", fk.onDelete),
356
- ...ifDefined("onUpdate", fk.onUpdate)
357
- }));
358
- }
359
- return {
360
- columns,
361
- constraints
362
- };
363
- }
364
- const DEFAULT_POLICY = { allowedOperationClasses: [
365
- "additive",
366
- "widening",
367
- "destructive",
368
- "data"
369
- ] };
370
- function emptySchemaIR() {
371
- return { tables: {} };
372
- }
373
- function mapIssueToCall(issue, ctx) {
374
- switch (issue.kind) {
375
- case "missing_table": {
376
- if (!issue.table) return notOk(issueConflict("unsupportedOperation", "Missing table issue has no table name"));
377
- const namespaceId = resolveNamespaceIdForIssue(issue);
378
- const contractTable = tableAt(ctx.toContract.storage, namespaceId, issue.table);
379
- if (!contractTable) return notOk(issueConflict("unsupportedOperation", `Table "${issue.table}" in namespace "${namespaceId}" reported missing but not found in destination contract`));
380
- const { columns: ddlColumns, constraints: ddlConstraints } = tableToDdlParts(contractTable, ctx.storageTypes);
381
- const calls = [new CreateTableCall(issue.table, ddlColumns, ddlConstraints.length > 0 ? ddlConstraints : void 0)];
382
- const declaredIndexColumnKeys = /* @__PURE__ */ new Set();
383
- for (const index of contractTable.indexes) {
384
- const indexName = index.name ?? defaultIndexName(issue.table, index.columns);
385
- declaredIndexColumnKeys.add(index.columns.join(","));
386
- calls.push(new CreateIndexCall(issue.table, indexName, index.columns));
387
- }
388
- for (const fk of contractTable.foreignKeys) {
389
- if (fk.index === false) continue;
390
- if (declaredIndexColumnKeys.has(fk.source.columns.join(","))) continue;
391
- const indexName = defaultIndexName(issue.table, fk.source.columns);
392
- calls.push(new CreateIndexCall(issue.table, indexName, fk.source.columns));
393
- }
394
- return ok(calls);
395
- }
396
- case "missing_column": {
397
- if (!issue.table || !issue.column) return notOk(issueConflict("unsupportedOperation", "Missing column issue has no table/column name"));
398
- const namespaceId = resolveNamespaceIdForIssue(issue);
399
- const contractTable2 = tableAt(ctx.toContract.storage, namespaceId, issue.table);
400
- const column = contractTable2?.columns[issue.column];
401
- if (!column) return notOk(issueConflict("unsupportedOperation", `Column "${issue.table}"."${issue.column}" not in destination contract`));
402
- const contractTable = contractTable2;
403
- const columnSpec = toColumnSpec(issue.column, column, ctx.storageTypes, contractTable ? isInlineAutoincrementPrimaryKey(contractTable, issue.column) : false);
404
- return ok([new AddColumnCall(issue.table, columnSpec)]);
405
- }
406
- case "index_mismatch": {
407
- if (!issue.table) return notOk(issueConflict("indexIncompatible", "Index issue has no table name"));
408
- if (!isMissing(issue) || !issue.expected) return notOk(issueConflict("indexIncompatible", `Index on "${issue.table}" differs (expected: ${issue.expected}, actual: ${issue.actual})`, { table: issue.table }));
409
- const namespaceId = resolveNamespaceIdForIssue(issue);
410
- const columns = issue.expected.split(", ");
411
- const contractTable = tableAt(ctx.toContract.storage, namespaceId, issue.table);
412
- if (!contractTable) return notOk(issueConflict("unsupportedOperation", `Table "${issue.table}" not found in destination contract`));
413
- const indexName = contractTable.indexes.find((idx) => idx.columns.join(",") === columns.join(","))?.name ?? defaultIndexName(issue.table, columns);
414
- return ok([new CreateIndexCall(issue.table, indexName, columns)]);
415
- }
416
- case "extra_table":
417
- if (!issue.table) return notOk(issueConflict("unsupportedOperation", "Extra table issue has no table name"));
418
- if (CONTROL_TABLE_NAMES.has(issue.table)) return ok([]);
419
- return ok([new DropTableCall(issue.table)]);
420
- case "extra_column":
421
- if (!issue.table || !issue.column) return notOk(issueConflict("unsupportedOperation", "Extra column issue has no table/column name"));
422
- return ok([new DropColumnCall(issue.table, issue.column)]);
423
- case "extra_index":
424
- if (!issue.table || !issue.indexOrConstraint) return notOk(issueConflict("unsupportedOperation", "Extra index issue has no table/index name"));
425
- return ok([new DropIndexCall(issue.table, issue.indexOrConstraint)]);
426
- case "enum_values_changed": return notOk(issueConflict("unsupportedOperation", "Received enum_values_changed against a SQLite schema (sql.enums: false) — verifier bug"));
427
- case "type_mismatch":
428
- case "nullability_mismatch":
429
- case "default_mismatch":
430
- case "default_missing":
431
- case "extra_default":
432
- case "primary_key_mismatch":
433
- case "unique_constraint_mismatch":
434
- case "foreign_key_mismatch":
435
- case "extra_foreign_key":
436
- case "extra_unique_constraint":
437
- case "extra_primary_key": return notOk(issueConflict(conflictKindForIssue(issue), issue.message, issueLocation(issue)));
438
- default: return notOk(issueConflict("unsupportedOperation", `Unhandled issue kind: ${issue.kind}`));
439
- }
440
- }
441
- function classifyCall(call) {
442
- switch (call.factoryName) {
443
- case "createTable": return "create-table";
444
- case "addColumn": return "add-column";
445
- case "createIndex": return "create-index";
446
- case "dropColumn": return "drop-column";
447
- case "dropIndex": return "drop-index";
448
- case "dropTable": return "drop-table";
449
- case "recreateTable": return null;
450
- default: return null;
451
- }
452
- }
453
- function planIssues(options) {
454
- const policyProvided = options.policy !== void 0;
455
- const policy = options.policy ?? DEFAULT_POLICY;
456
- const schema = options.schema ?? emptySchemaIR();
457
- const frameworkComponents = options.frameworkComponents ?? [];
458
- const context = {
459
- toContract: options.toContract,
460
- fromContract: options.fromContract,
461
- codecHooks: options.codecHooks,
462
- storageTypes: options.storageTypes,
463
- schema,
464
- policy,
465
- frameworkComponents
466
- };
467
- const strategies = options.strategies ?? sqlitePlannerStrategies;
468
- let remaining = options.issues;
469
- const recipeCalls = [];
470
- const bucketableCalls = [];
471
- for (const strategy of strategies) {
472
- const result = strategy(remaining, context);
473
- if (result.kind === "match") {
474
- remaining = result.issues;
475
- if (result.recipe) recipeCalls.push(...result.calls);
476
- else bucketableCalls.push(...result.calls);
477
- }
478
- }
479
- const sorted = [...remaining].sort((a, b) => {
480
- const kindDelta = issueOrder(a) - issueOrder(b);
481
- if (kindDelta !== 0) return kindDelta;
482
- const keyA = issueKey(a);
483
- const keyB = issueKey(b);
484
- return keyA < keyB ? -1 : keyA > keyB ? 1 : 0;
485
- });
486
- const defaultCalls = [];
487
- const conflicts = [];
488
- for (const issue of sorted) {
489
- const result = mapIssueToCall(issue, context);
490
- if (result.ok) defaultCalls.push(...result.value);
491
- else conflicts.push(result.failure);
492
- }
493
- const allowed = policy.allowedOperationClasses;
494
- let gatedRecipe = recipeCalls;
495
- let gatedBucketable = bucketableCalls;
496
- let gatedDefault = defaultCalls;
497
- if (policyProvided) {
498
- const sink = (acc) => (call) => {
499
- if (allowed.includes(call.operationClass)) {
500
- acc.push(call);
501
- return;
502
- }
503
- conflicts.push(conflictForDisallowedCall(call, allowed));
504
- };
505
- const gatedRecipeBucket = [];
506
- const gatedBucketableBucket = [];
507
- const gatedDefaultBucket = [];
508
- recipeCalls.forEach(sink(gatedRecipeBucket));
509
- bucketableCalls.forEach(sink(gatedBucketableBucket));
510
- defaultCalls.forEach(sink(gatedDefaultBucket));
511
- gatedRecipe = gatedRecipeBucket;
512
- gatedBucketable = gatedBucketableBucket;
513
- gatedDefault = gatedDefaultBucket;
514
- }
515
- if (conflicts.length > 0) return notOk(conflicts);
516
- const combined = [...gatedDefault, ...gatedBucketable];
517
- const byCategory = (cat) => combined.filter((c) => classifyCall(c) === cat);
518
- return ok({ calls: [
519
- ...byCategory("create-table"),
520
- ...byCategory("add-column"),
521
- ...byCategory("create-index"),
522
- ...gatedRecipe,
523
- ...byCategory("drop-column"),
524
- ...byCategory("drop-index"),
525
- ...byCategory("drop-table")
526
- ] });
527
- }
528
- //#endregion
529
- //#region src/core/migrations/planner.ts
530
- function createSqliteMigrationPlanner(lowerer) {
531
- return new SqliteMigrationPlanner(lowerer);
532
- }
533
- /**
534
- * SQLite migration planner — a thin wrapper over `planIssues`.
535
- *
536
- * `plan()` verifies the live schema against the target contract (producing
537
- * `SchemaIssue[]`) and delegates to `planIssues` with the registered
538
- * strategies. Strategies absorb groups of related issues into composite
539
- * recipes (e.g. recreating a table to apply type/nullability/default/
540
- * constraint changes at once); anything not absorbed by a strategy flows
541
- * through `mapIssueToCall` in the issue planner as a one-off call.
542
- *
543
- * FK-backing indexes are surfaced by `verifySqlSchema`'s index expansion
544
- * (see `verify-sql-schema.ts:459-469`), so `mapIssueToCall` handles them
545
- * uniformly alongside user-declared indexes.
546
- */
547
- var SqliteMigrationPlanner = class {
548
- #lowerer;
549
- constructor(lowerer) {
550
- this.#lowerer = lowerer;
551
- }
552
- plan(options) {
553
- return this.planSql(options);
554
- }
555
- emptyMigration(context, spaceId) {
556
- return new TypeScriptRenderableSqliteMigration([], {
557
- from: context.fromHash,
558
- to: context.toHash
559
- }, spaceId, void 0, this.#lowerer);
560
- }
561
- planSql(options) {
562
- const policyResult = this.ensureAdditivePolicy(options.policy);
563
- if (policyResult) return policyResult;
564
- const schemaIssues = this.collectSchemaIssues(options);
565
- const codecHooks = extractCodecControlHooks(options.frameworkComponents);
566
- const storageTypes = options.contract.storage.types ?? {};
567
- const result = planIssues({
568
- issues: schemaIssues,
569
- toContract: options.contract,
570
- fromContract: options.fromContract,
571
- codecHooks,
572
- storageTypes,
573
- schema: options.schema,
574
- policy: options.policy,
575
- frameworkComponents: options.frameworkComponents,
576
- strategies: sqlitePlannerStrategies
577
- });
578
- if (!result.ok) return plannerFailure(result.failure);
579
- const fieldEventOps = planFieldEventOperations({
580
- priorContract: options.fromContract,
581
- newContract: options.contract,
582
- codecHooks
583
- });
584
- const calls = [...result.value.calls, ...fieldEventOps];
585
- const destination = {
586
- storageHash: options.contract.storage.storageHash,
587
- ...options.contract.profileHash !== void 0 ? { profileHash: options.contract.profileHash } : {}
588
- };
589
- return {
590
- kind: "success",
591
- plan: new TypeScriptRenderableSqliteMigration(calls, {
592
- from: options.fromContract?.storage.storageHash ?? null,
593
- to: options.contract.storage.storageHash
594
- }, options.spaceId, destination, this.#lowerer)
595
- };
596
- }
597
- ensureAdditivePolicy(policy) {
598
- if (!policy.allowedOperationClasses.includes("additive")) return plannerFailure([{
599
- kind: "unsupportedOperation",
600
- summary: "Migration planner requires additive operations be allowed",
601
- why: "The planner requires the \"additive\" operation class to be allowed in the policy."
602
- }]);
603
- return null;
604
- }
605
- collectSchemaIssues(options) {
606
- const allowed = options.policy.allowedOperationClasses;
607
- const strict = allowed.includes("widening") || allowed.includes("destructive");
608
- return verifySqlSchema({
609
- contract: options.contract,
610
- schema: options.schema,
611
- strict,
612
- typeMetadataRegistry: /* @__PURE__ */ new Map(),
613
- frameworkComponents: options.frameworkComponents,
614
- normalizeDefault: parseSqliteDefault,
615
- normalizeNativeType: normalizeSqliteNativeType
616
- }).schema.issues;
617
- }
618
- };
619
- //#endregion
620
- export { createSqliteMigrationPlanner as n, SqliteMigrationPlanner as t };
621
-
622
- //# sourceMappingURL=planner-Ciq8p_dL.mjs.map