@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
@@ -0,0 +1,848 @@
1
+ import { a as DropColumnCall, d as buildRecreateSummary, h as renderDefaultLiteral, i as DataTransformCall, l as RecreateTableCall, m as buildColumnTypeSql, n as CreateIndexCall, o as DropIndexCall, p as buildColumnDefaultSql, r as CreateTableCall, s as DropTableCall, t as AddColumnCall, u as buildRecreatePostchecks } from "./op-factory-call-Do03QgD9.mjs";
2
+ import { t as CONTROL_TABLE_NAMES } from "./control-tables-7KwMyJ6i.mjs";
3
+ import { t as TypeScriptRenderableSqliteMigration } from "./planner-produced-sqlite-migration-BDzhFAoW.mjs";
4
+ import { DdlColumn, ForeignKeyConstraint, FunctionColumnDefault, LiteralColumnDefault, PrimaryKeyConstraint, UniqueConstraint } from "@prisma-next/sql-relational-core/ast";
5
+ import { RelationalSchemaNodeKind, SqlSchemaIR, relationalNodeGranularity } from "@prisma-next/sql-schema-ir/types";
6
+ import { UNBOUND_NAMESPACE_ID, entityAt } from "@prisma-next/framework-components/ir";
7
+ import { buildNativeTypeExpander, contractToSchemaIR, extractCodecControlHooks, planFieldEventOperations, plannerFailure } from "@prisma-next/family-sql/control";
8
+ import { verifySqlSchemaByDiff } from "@prisma-next/family-sql/diff";
9
+ import { diffSchemas } from "@prisma-next/framework-components/control";
10
+ import { blindCast } from "@prisma-next/utils/casts";
11
+ import { ifDefined } from "@prisma-next/utils/defined";
12
+ import { defaultIndexName } from "@prisma-next/sql-schema-ir/naming";
13
+ import { notOk, ok } from "@prisma-next/utils/result";
14
+ //#region src/core/migrations/diff-database-schema.ts
15
+ /** Renders a column default for the SQLite dialect. */
16
+ function sqliteRenderDefault(def, _column) {
17
+ if (def.kind === "function") {
18
+ if (def.expression === "now()") return "datetime('now')";
19
+ return def.expression;
20
+ }
21
+ return renderDefaultLiteral(def.value);
22
+ }
23
+ /**
24
+ * The SQLite expected-side projection: contract → flat relational schema IR.
25
+ *
26
+ * `extras` thread the plan-time derivation input: the native-type expander,
27
+ * so the expected side carries resolved native types (like the verify
28
+ * side). Every expected column also carries its `codecRef` unconditionally
29
+ * (Decision 5) — the planner's op-builders resolve DDL rendering from it at
30
+ * plan time, so no separate render stamper is threaded here.
31
+ */
32
+ function sqliteContractToSchema(contract, extras) {
33
+ return contractToSchemaIR(contract, {
34
+ annotationNamespace: "sqlite",
35
+ renderDefault: sqliteRenderDefault,
36
+ ...ifDefined("expandNativeType", extras?.expandNativeType)
37
+ });
38
+ }
39
+ /**
40
+ * The SQLite schema verify: the full-tree node-diff verdict wrapped in the
41
+ * issue-based result envelope. Used by the runner's post-apply check; the
42
+ * family `verifySchema` runs the same composition via the descriptor hook.
43
+ */
44
+ function verifySqliteDatabaseSchema(input) {
45
+ return verifySqlSchemaByDiff({
46
+ contract: input.contract,
47
+ schema: input.actualSchema,
48
+ strict: input.strict,
49
+ frameworkComponents: input.frameworkComponents,
50
+ diffSchema: diffSqliteSchema,
51
+ granularityOf: relationalNodeGranularity
52
+ });
53
+ }
54
+ /**
55
+ * Resolves a verdict-diff issue's subject table's declared control policy
56
+ * directly from the contract. SQLite's expected tree is flat, so the issue
57
+ * path carries no namespace segment — `path[1]` is the table name (`path[0]`
58
+ * is the tree root's own id); every contract namespace is searched for that
59
+ * table name (table names are globally unique in the flat tree — duplicates
60
+ * across namespaces are rejected earlier, at `contractToSchemaIR`).
61
+ */
62
+ function resolveControlPolicy(issue, contract) {
63
+ const tableName = issue.path[1];
64
+ if (tableName === void 0) return void 0;
65
+ for (const namespaceId of Object.keys(contract.storage.namespaces)) {
66
+ const table = entityAt(contract.storage, {
67
+ namespaceId,
68
+ entityKind: "table",
69
+ entityName: tableName
70
+ });
71
+ if (table !== void 0) return table.control;
72
+ }
73
+ }
74
+ /**
75
+ * The SQLite full-tree node diff for the family verify verdict: derive the
76
+ * expected flat tree with resolved leaf values (expander threaded so
77
+ * parameterized types compare expanded; FK nodes born with the flat empty
78
+ * `resolvedReferencedNamespace`), and run the generic differ over the trees
79
+ * as derived. Flat targets need no ownership scoping. The codec `verifyType`
80
+ * hooks run once per contract namespace with tables, each against the sole
81
+ * flat actual root — exactly the legacy per-namespace pairing.
82
+ */
83
+ function diffSqliteSchema(input) {
84
+ const expandNativeType = buildNativeTypeExpander(input.frameworkComponents);
85
+ const expected = sqliteContractToSchema(input.contract, { ...ifDefined("expandNativeType", expandNativeType) });
86
+ const actual = input.schema instanceof SqlSchemaIR ? input.schema : blindCast(input.schema);
87
+ return {
88
+ issues: diffSchemas(expected, actual),
89
+ resolveControlPolicy: (issue) => resolveControlPolicy(issue, input.contract),
90
+ namespacePairs: Object.values(input.contract.storage.namespaces).filter((ns) => Object.keys(ns.entries.table ?? {}).length > 0).map(() => ({ actual }))
91
+ };
92
+ }
93
+ /**
94
+ * The SQLite planner's diff input: the same tree-building
95
+ * `diffSqliteSchema` uses (expander threaded, FK nodes born flat). One differ
96
+ * drives both verify and plan over the trees as derived; this is the plan-side
97
+ * derivation — column DDL resolves from each expected column's `codecRef` at
98
+ * plan time (`column-ddl-rendering.ts`), so no separate render stamping happens here.
99
+ */
100
+ function buildSqlitePlanDiff(input) {
101
+ const expandNativeType = buildNativeTypeExpander(input.frameworkComponents);
102
+ const expected = sqliteContractToSchema(input.contract, { ...ifDefined("expandNativeType", expandNativeType) });
103
+ const actual = new SqlSchemaIR(withRecordKeyNames(input.actualSchema));
104
+ return {
105
+ expected,
106
+ actual,
107
+ issues: diffSchemas(expected, actual)
108
+ };
109
+ }
110
+ /**
111
+ * Every schema-tree builder in this codebase derives a table's / column's
112
+ * `name` from the record key it's stored under (`contractToSchemaIR`,
113
+ * the SQLite introspection adapter) rather than trusting a redundant
114
+ * embedded field — the record key IS the identity. Mirrors that discipline
115
+ * for the actual/live tree before construction, so `SqlTableIR.id` /
116
+ * `SqlColumnIR.id` (both derived from `.name`) are always correct without
117
+ * requiring every caller to duplicate the key onto the value. A no-op for a
118
+ * tree that already carries matching names (the real introspection adapter
119
+ * always does).
120
+ */
121
+ function withRecordKeyNames(actualSchema) {
122
+ const raw = blindCast(actualSchema);
123
+ const tables = {};
124
+ for (const [tableName, table] of Object.entries(raw.tables ?? {})) {
125
+ const rawTable = blindCast(table);
126
+ const columns = {};
127
+ for (const [columnName, column] of Object.entries(blindCast(table).columns ?? {})) columns[columnName] = {
128
+ ...blindCast(column),
129
+ name: columnName
130
+ };
131
+ tables[tableName] = {
132
+ ...rawTable,
133
+ name: tableName,
134
+ columns,
135
+ foreignKeys: rawTable.foreignKeys ?? [],
136
+ uniques: rawTable.uniques ?? [],
137
+ indexes: rawTable.indexes ?? []
138
+ };
139
+ }
140
+ return { tables };
141
+ }
142
+ //#endregion
143
+ //#region src/core/migrations/column-ddl-rendering.ts
144
+ /**
145
+ * Reconstructs the `StorageColumn`-shaped fields `buildColumnTypeSql` /
146
+ * `buildColumnDefaultSql` expect, from a column node's own stamped codec
147
+ * identity (`codecRef` / `codecBaseNativeType`, Decision 5) — never the
148
+ * contract. SQLite's type renderer only uppercases the resolved base type
149
+ * (no parameterized expansion, no named-type quoting), so `typeRef` is
150
+ * deliberately left unset here: setting it would send `buildColumnTypeSql`
151
+ * back through a live `storageTypes` lookup the node's fields have already
152
+ * resolved past, which throws for an unrecognized reference (unlike
153
+ * Postgres's lenient fallback).
154
+ */
155
+ function columnLike(column) {
156
+ if (column.codecRef === void 0 || column.codecBaseNativeType === void 0) throw new Error(`columnLike: expected column "${column.name}" carries no codec identity — the expected tree must be derived via contractToSchemaIR for planning`);
157
+ return {
158
+ nativeType: column.codecBaseNativeType,
159
+ codecId: column.codecRef.codecId,
160
+ nullable: column.nullable,
161
+ ...(column.many ?? column.codecRef.many) !== void 0 ? { many: column.many ?? column.codecRef.many } : {},
162
+ ...column.codecRef.typeParams !== void 0 ? { typeParams: blindCast(column.codecRef.typeParams) } : {},
163
+ ...column.resolvedDefault !== void 0 ? { default: column.resolvedDefault } : {}
164
+ };
165
+ }
166
+ function sqliteDefaultToDdlColumnDefault(columnDefault) {
167
+ if (!columnDefault) return void 0;
168
+ switch (columnDefault.kind) {
169
+ case "literal": return new LiteralColumnDefault(columnDefault.value);
170
+ case "function":
171
+ if (columnDefault.expression === "autoincrement()") return void 0;
172
+ return new FunctionColumnDefault(columnDefault.expression);
173
+ default: throw new Error(`sqliteDefaultToDdlColumnDefault: unhandled kind "${blindCast(columnDefault).kind}"`);
174
+ }
175
+ }
176
+ /**
177
+ * True when the column is rendered inline as `INTEGER PRIMARY KEY
178
+ * AUTOINCREMENT` — the sole member of the table's primary key with an
179
+ * `autoincrement()` default. Node-based sibling of the retired
180
+ * `isInlineAutoincrementPrimaryKey` (which read the raw `StorageTable`);
181
+ * reads the table/column nodes instead.
182
+ */
183
+ function isInlineAutoincrementPrimaryKeyNode(table, column) {
184
+ if (table.primaryKey?.columns.length !== 1) return false;
185
+ if (table.primaryKey.columns[0] !== column.name) return false;
186
+ return column.resolvedDefault?.kind === "function" && column.resolvedDefault.expression === "autoincrement()";
187
+ }
188
+ /**
189
+ * Builds the flat `SqliteColumnSpec` `AddColumnCall` / `RecreateTableCall`
190
+ * need, resolved from the column node's codec identity — the same builders
191
+ * the pre-`plan(start, end)` op-path called, so the output is
192
+ * byte-identical.
193
+ */
194
+ function columnSpecFromNode(column, inline) {
195
+ const like = columnLike(column);
196
+ const typeSql = buildColumnTypeSql(like, {});
197
+ const defaultSql = buildColumnDefaultSql(like.default);
198
+ return {
199
+ name: column.name,
200
+ typeSql,
201
+ defaultSql,
202
+ nullable: column.nullable,
203
+ ...inline ? { inlineAutoincrementPrimaryKey: true } : {}
204
+ };
205
+ }
206
+ /**
207
+ * Builds the `DdlColumn` the `CreateTableCall` path needs, resolved from the
208
+ * column node's codec identity.
209
+ */
210
+ function ddlColumnFromNode(column, inline) {
211
+ const like = columnLike(column);
212
+ const typeSql = buildColumnTypeSql(like, {});
213
+ if (inline) return new DdlColumn({
214
+ name: column.name,
215
+ type: `${typeSql} PRIMARY KEY AUTOINCREMENT`
216
+ });
217
+ const colDefault = sqliteDefaultToDdlColumnDefault(like.default);
218
+ return new DdlColumn({
219
+ name: column.name,
220
+ type: typeSql,
221
+ ...!column.nullable ? { notNull: true } : {},
222
+ ...colDefault !== void 0 ? { default: colDefault } : {},
223
+ ...column.codecRef !== void 0 ? { codecRef: column.codecRef } : {}
224
+ });
225
+ }
226
+ /**
227
+ * Builds the table-level constraints (PK / unique / FK) for a `CreateTable`
228
+ * path from the table node — the node-sourced sibling of the retired
229
+ * contract-based `tableToDdlParts`'s constraint half.
230
+ */
231
+ function tableConstraintsFromNode(table, hasInlinePk) {
232
+ const constraints = [];
233
+ if (table.primaryKey && !hasInlinePk) constraints.push(new PrimaryKeyConstraint({ columns: table.primaryKey.columns }));
234
+ for (const u of table.uniques) constraints.push(new UniqueConstraint({
235
+ columns: u.columns,
236
+ ...u.name !== void 0 ? { name: u.name } : {}
237
+ }));
238
+ for (const fk of table.foreignKeys) constraints.push(new ForeignKeyConstraint({
239
+ columns: fk.columns,
240
+ refTable: fk.referencedTable,
241
+ refColumns: fk.referencedColumns,
242
+ ...fk.name !== void 0 ? { name: fk.name } : {},
243
+ ...fk.onDelete !== void 0 ? { onDelete: fk.onDelete } : {},
244
+ ...fk.onUpdate !== void 0 ? { onUpdate: fk.onUpdate } : {}
245
+ }));
246
+ return constraints;
247
+ }
248
+ //#endregion
249
+ //#region src/core/migrations/planner-strategies.ts
250
+ /**
251
+ * Classifies a node issue into the operation class a recreate absorbing it
252
+ * would need, or `null` when the strategy doesn't handle this node/reason at
253
+ * all (table/column not-found-or-not-expected, and index issues — those are
254
+ * standalone ops, never folded into a recreate).
255
+ *
256
+ * Column drift is a single `not-equal` issue now (type AND nullability
257
+ * compared together by `SqlColumnIR.isEqualTo`), so this reads both fields
258
+ * off the node pair directly rather than trusting a separate issue kind per
259
+ * attribute: a type change is always destructive; a pure nullability change
260
+ * is destructive when tightening (NOT NULL required) and widening when
261
+ * relaxing.
262
+ */
263
+ function classifyNodeIssue(issue) {
264
+ const node = issue.expected ?? issue.actual;
265
+ if (node === void 0) return null;
266
+ switch (blindCast(node).nodeKind) {
267
+ case RelationalSchemaNodeKind.column: {
268
+ if (issue.reason !== "not-equal") return null;
269
+ const expected = blindCast(issue.expected);
270
+ if (columnTypeChanged(expected, blindCast(issue.actual))) return "destructive";
271
+ return expected.nullable ? "widening" : "destructive";
272
+ }
273
+ case RelationalSchemaNodeKind.columnDefault: return issue.reason === "not-expected" ? "destructive" : "widening";
274
+ case RelationalSchemaNodeKind.primaryKey:
275
+ case RelationalSchemaNodeKind.foreignKey:
276
+ case RelationalSchemaNodeKind.unique: return "destructive";
277
+ default: return null;
278
+ }
279
+ }
280
+ /**
281
+ * Groups recreate-eligible issues by table, decides per-table operation class
282
+ * (destructive wins over widening), and emits one `RecreateTableCall` per
283
+ * table. Returns unchanged-or-smaller issue list — issues the strategy
284
+ * consumed are removed so `mapNodeIssueToCall` doesn't double-handle them.
285
+ *
286
+ * The full desired/live table shapes come from `ctx.expected`/`ctx.actual`
287
+ * directly (keyed by table name — SQLite is a flat, single-namespace target)
288
+ * rather than from any individual issue, since a single drifted attribute's
289
+ * issue only carries that attribute's own node, never the whole table.
290
+ */
291
+ const recreateTableStrategy = (issues, ctx) => {
292
+ const byTable = /* @__PURE__ */ new Map();
293
+ const consumed = /* @__PURE__ */ new Set();
294
+ for (const issue of issues) {
295
+ const cls = classifyNodeIssue(issue);
296
+ if (!cls) continue;
297
+ const tableName = issue.path[1];
298
+ if (tableName === void 0) continue;
299
+ const entry = byTable.get(tableName);
300
+ if (entry) {
301
+ entry.issues.push(issue);
302
+ if (cls === "destructive") entry.hasDestructive = true;
303
+ } else byTable.set(tableName, {
304
+ issues: [issue],
305
+ hasDestructive: cls === "destructive"
306
+ });
307
+ consumed.add(issue);
308
+ }
309
+ if (byTable.size === 0) return { kind: "no_match" };
310
+ const calls = [];
311
+ for (const [tableName, entry] of byTable) {
312
+ const expectedTable = ctx.expected.tables[tableName];
313
+ const actualTable = ctx.actual.tables[tableName];
314
+ if (!expectedTable || !actualTable) continue;
315
+ const operationClass = entry.hasDestructive ? "destructive" : "widening";
316
+ const tableSpec = tableSpecFromNode(expectedTable);
317
+ const indexes = expectedTable.indexes.map((idx) => ({
318
+ name: idx.name ?? defaultIndexName(tableName, idx.columns),
319
+ columns: idx.columns
320
+ }));
321
+ calls.push(new RecreateTableCall({
322
+ tableName,
323
+ contractTable: tableSpec,
324
+ schemaColumnNames: Object.keys(actualTable.columns),
325
+ indexes,
326
+ summary: buildRecreateSummary(tableName, entry.issues),
327
+ postchecks: buildRecreatePostchecks(tableName, entry.issues, tableSpec),
328
+ operationClass
329
+ }));
330
+ }
331
+ return {
332
+ kind: "match",
333
+ issues: issues.filter((i) => !consumed.has(i)),
334
+ calls,
335
+ recipe: true
336
+ };
337
+ };
338
+ /**
339
+ * When the policy allows `'data'` and the expected tree tightens one or more
340
+ * columns from nullable to NOT NULL, emit a `DataTransformCall` stub per
341
+ * tightened column. The user fills the backfill `UPDATE` in the rendered
342
+ * `migration.ts` before the subsequent `RecreateTableCall` copies data into
343
+ * the tightened schema (whose `INSERT INTO temp SELECT … FROM old` would
344
+ * otherwise fail at runtime if any `NULL`s remain).
345
+ *
346
+ * Does NOT consume the tightening issue — `recreateTableStrategy` still
347
+ * needs it to produce the actual recreate that enforces the NOT NULL at
348
+ * the schema level. The backfill op and the recreate op end up in the
349
+ * recipe slot in strategy order (backfill first, recreate second), which
350
+ * matches the required execution order.
351
+ *
352
+ * Mirrors Postgres's `nullableTighteningCallStrategy` / `'data'`-class
353
+ * gating. When `'data'` is not in the policy (the default `db update` /
354
+ * `db init` path), the strategy short-circuits and the recreate alone
355
+ * runs with its current destructive-class gating — preserving today's
356
+ * behavior where a tightening blows up at runtime if NULLs are present.
357
+ */
358
+ const nullabilityTighteningBackfillStrategy = (issues, ctx) => {
359
+ if (!ctx.policy.allowedOperationClasses.includes("data")) return { kind: "no_match" };
360
+ const calls = [];
361
+ for (const issue of issues) {
362
+ if (issue.reason !== "not-equal" || issue.expected === void 0 || issue.actual === void 0) continue;
363
+ if (blindCast(issue.expected).nodeKind !== RelationalSchemaNodeKind.column) continue;
364
+ const expectedColumn = blindCast(issue.expected);
365
+ const actualColumn = blindCast(issue.actual);
366
+ if (expectedColumn.nullable === actualColumn.nullable) continue;
367
+ if (expectedColumn.nullable) continue;
368
+ const tableName = issue.path[1];
369
+ if (tableName === void 0) continue;
370
+ calls.push(new DataTransformCall(`data_migration.backfill-${tableName}-${expectedColumn.name}`, `Backfill NULLs in "${tableName}"."${expectedColumn.name}" before NOT NULL tightening`, tableName, expectedColumn.name));
371
+ }
372
+ if (calls.length === 0) return { kind: "no_match" };
373
+ return {
374
+ kind: "match",
375
+ issues,
376
+ calls,
377
+ recipe: true
378
+ };
379
+ };
380
+ const sqlitePlannerStrategies = [nullabilityTighteningBackfillStrategy, recreateTableStrategy];
381
+ //#endregion
382
+ //#region src/core/migrations/issue-planner.ts
383
+ /**
384
+ * Re-keys the legacy `ISSUE_KIND_ORDER` (kind string → priority number) on
385
+ * `(nodeKind, reason)`. Numbers are preserved from the legacy table so the
386
+ * dependency intent stays legible; the final emission order is actually
387
+ * fixed downstream by category bucketing (create-table → add-column →
388
+ * create-index → recreate → drop-column → drop-index → drop-table), so this
389
+ * only breaks ties within a single bucket.
390
+ */
391
+ function nodeIssueOrder(issue) {
392
+ const node = issueNode(issue);
393
+ if (node === void 0) return 99;
394
+ switch (node.nodeKind) {
395
+ case RelationalSchemaNodeKind.foreignKey: return issue.reason === "not-expected" ? 10 : 60;
396
+ case RelationalSchemaNodeKind.unique: return issue.reason === "not-expected" ? 11 : 51;
397
+ case RelationalSchemaNodeKind.primaryKey: return issue.reason === "not-expected" ? 12 : 50;
398
+ case RelationalSchemaNodeKind.index: return issue.reason === "not-expected" ? 13 : 52;
399
+ case RelationalSchemaNodeKind.columnDefault:
400
+ if (issue.reason === "not-expected") return 14;
401
+ return issue.reason === "not-found" ? 42 : 43;
402
+ case RelationalSchemaNodeKind.column:
403
+ if (issue.reason === "not-expected") return 15;
404
+ return issue.reason === "not-found" ? 30 : 40;
405
+ case RelationalSchemaNodeKind.table: return issue.reason === "not-expected" ? 16 : 20;
406
+ case RelationalSchemaNodeKind.check:
407
+ if (issue.reason === "not-found") return 53;
408
+ return issue.reason === "not-expected" ? 54 : 55;
409
+ default: return 99;
410
+ }
411
+ }
412
+ /** Deterministic tiebreak within an order bucket: the diff path itself already encodes table → child → grandchild. */
413
+ function nodeIssueKey(issue) {
414
+ return issue.path.join(" ");
415
+ }
416
+ /**
417
+ * The generic differ is total: a missing/extra table (or column) emits an
418
+ * issue for itself AND for every node in its subtree (columns, defaults,
419
+ * constraints, indexes). `CreateTableCall`/`DropTableCall` and
420
+ * `AddColumnCall`/`DropColumnCall` already account for the whole subtree
421
+ * (reading it directly off the table/column node), so the nested issues are
422
+ * redundant — coalescing them is "the planner's responsibility" the differ's
423
+ * own contract assigns (`schema-diff.ts`). Drops any issue whose path is a
424
+ * strict descendant of a `not-found`/`not-expected` issue's path.
425
+ */
426
+ function coalesceSubtreeIssues(issues) {
427
+ const collapsingPaths = issues.filter((issue) => issue.reason === "not-found" || issue.reason === "not-expected").map((issue) => issue.path);
428
+ if (collapsingPaths.length === 0) return issues;
429
+ return issues.filter((issue) => !collapsingPaths.some((ancestor) => isStrictDescendantPath(issue.path, ancestor)));
430
+ }
431
+ function isStrictDescendantPath(path, ancestor) {
432
+ if (path.length <= ancestor.length) return false;
433
+ for (let i = 0; i < ancestor.length; i += 1) if (path[i] !== ancestor[i]) return false;
434
+ return true;
435
+ }
436
+ function issueNode(issue) {
437
+ const node = issue.expected ?? issue.actual;
438
+ if (node === void 0) return void 0;
439
+ return blindCast(node);
440
+ }
441
+ /** Whether the expected/actual native type (resolved, or raw+many fallback) differs — mirrors `SqlColumnIR.isEqualTo`'s type comparison. */
442
+ function columnTypeChanged(expected, actual) {
443
+ if (expected.resolvedNativeType !== void 0 && actual.resolvedNativeType !== void 0) return expected.resolvedNativeType !== actual.resolvedNativeType;
444
+ return expected.nativeType !== actual.nativeType || Boolean(expected.many) !== Boolean(actual.many);
445
+ }
446
+ /**
447
+ * Builds the flat `SqliteTableSpec` `RecreateTableCall` needs from the
448
+ * expected table node — the node-sourced equivalent of the retired
449
+ * `toTableSpec` (which read a raw contract `StorageTable`). Every column's
450
+ * spec is resolved from its `codecRef` via `columnSpecFromNode`.
451
+ */
452
+ function tableSpecFromNode(table) {
453
+ const columns = Object.values(table.columns).map((c) => columnSpecFromNode(c, isInlineAutoincrementPrimaryKeyNode(table, c)));
454
+ const uniques = table.uniques.map((u) => ({
455
+ columns: u.columns,
456
+ ...u.name !== void 0 ? { name: u.name } : {}
457
+ }));
458
+ const foreignKeys = table.foreignKeys.map((fk) => ({
459
+ columns: fk.columns,
460
+ references: {
461
+ table: fk.referencedTable,
462
+ columns: fk.referencedColumns
463
+ },
464
+ constraint: true,
465
+ ...fk.name !== void 0 ? { name: fk.name } : {},
466
+ ...fk.onDelete !== void 0 ? { onDelete: fk.onDelete } : {},
467
+ ...fk.onUpdate !== void 0 ? { onUpdate: fk.onUpdate } : {}
468
+ }));
469
+ return {
470
+ columns,
471
+ ...table.primaryKey ? { primaryKey: { columns: table.primaryKey.columns } } : {},
472
+ uniques,
473
+ foreignKeys
474
+ };
475
+ }
476
+ function issueConflict(kind, summary, location) {
477
+ return {
478
+ kind,
479
+ summary,
480
+ why: "Use `migration new` to author a custom migration for this change.",
481
+ ...location ? { location } : {}
482
+ };
483
+ }
484
+ function issueLocation(tableName, columnName) {
485
+ return columnName !== void 0 ? {
486
+ table: tableName,
487
+ column: columnName
488
+ } : { table: tableName };
489
+ }
490
+ /**
491
+ * Conflict kind for a node kind that `recreateTableStrategy` absorbs for
492
+ * every reachable production issue. Reaching `mapNodeIssueToCall` for one of
493
+ * these means the recreate strategy didn't run — mirrors the legacy
494
+ * `conflictKindForIssue` per-kind categorization.
495
+ */
496
+ function absorbedConflictKind(nodeKind) {
497
+ switch (nodeKind) {
498
+ case RelationalSchemaNodeKind.primaryKey:
499
+ case RelationalSchemaNodeKind.unique: return "indexIncompatible";
500
+ case RelationalSchemaNodeKind.foreignKey: return "foreignKeyConflict";
501
+ default: return "missingButNonAdditive";
502
+ }
503
+ }
504
+ /**
505
+ * Builds the `CreateTableCall` + per-index `CreateIndexCall`s for a
506
+ * newly-expected table. Reads only the table node's own children — indexes
507
+ * (declared + FK-backing, deduped) are already merged and ordered at
508
+ * derivation (`contractToSchemaIR`'s `convertTable`).
509
+ */
510
+ function buildCreateTableCalls(table) {
511
+ const columns = Object.values(table.columns).map((c) => ddlColumnFromNode(c, isInlineAutoincrementPrimaryKeyNode(table, c)));
512
+ const constraints = tableConstraintsFromNode(table, Object.values(table.columns).some((c) => isInlineAutoincrementPrimaryKeyNode(table, c)));
513
+ const calls = [new CreateTableCall(table.name, columns, constraints.length > 0 ? constraints : void 0)];
514
+ for (const index of table.indexes) {
515
+ const indexName = index.name ?? defaultIndexName(table.name, index.columns);
516
+ calls.push(new CreateIndexCall(table.name, indexName, index.columns));
517
+ }
518
+ return calls;
519
+ }
520
+ function mapTableIssue(issue) {
521
+ if (issue.reason === "not-found") return ok(buildCreateTableCalls(blindCast(issue.expected)));
522
+ if (issue.reason === "not-expected") {
523
+ const table = blindCast(issue.actual);
524
+ if (CONTROL_TABLE_NAMES.has(table.name)) return ok([]);
525
+ return ok([new DropTableCall(table.name)]);
526
+ }
527
+ return notOk(issueConflict("unsupportedOperation", `Unexpected table drift: ${issue.path.join("/")}`));
528
+ }
529
+ function mapColumnIssue(issue, ctx) {
530
+ const tableName = issue.path[1];
531
+ if (tableName === void 0) return notOk(issueConflict("unsupportedOperation", `Column issue has no table in its path: ${issue.path.join("/")}`));
532
+ if (issue.reason === "not-found") {
533
+ const column = blindCast(issue.expected);
534
+ const table = ctx.expected.tables[tableName];
535
+ return ok([new AddColumnCall(tableName, columnSpecFromNode(column, table !== void 0 && isInlineAutoincrementPrimaryKeyNode(table, column)))]);
536
+ }
537
+ if (issue.reason === "not-expected") return ok([new DropColumnCall(tableName, blindCast(issue.actual).name)]);
538
+ const expected = blindCast(issue.expected);
539
+ return notOk(issueConflict(columnTypeChanged(expected, blindCast(issue.actual)) ? "typeMismatch" : "nullabilityConflict", issue.path.join("/"), issueLocation(tableName, expected.name)));
540
+ }
541
+ function mapIndexIssue(issue) {
542
+ const tableName = issue.path[1];
543
+ if (tableName === void 0) return notOk(issueConflict("unsupportedOperation", `Index issue has no table in its path: ${issue.path.join("/")}`));
544
+ if (issue.reason === "not-found") {
545
+ const index = blindCast(issue.expected);
546
+ return ok([new CreateIndexCall(tableName, index.name ?? defaultIndexName(tableName, index.columns), index.columns)]);
547
+ }
548
+ if (issue.reason === "not-expected") {
549
+ const index = blindCast(issue.actual);
550
+ return ok([new DropIndexCall(tableName, index.name ?? defaultIndexName(tableName, index.columns))]);
551
+ }
552
+ return notOk(issueConflict("indexIncompatible", issue.path.join("/"), issueLocation(tableName)));
553
+ }
554
+ function mapNodeIssueToCall(issue, ctx) {
555
+ const node = issueNode(issue);
556
+ if (node === void 0) return notOk(issueConflict("unsupportedOperation", `Issue carries neither an expected nor an actual node: ${issue.path.join("/")}`));
557
+ switch (node.nodeKind) {
558
+ case RelationalSchemaNodeKind.table: return mapTableIssue(issue);
559
+ case RelationalSchemaNodeKind.column: return mapColumnIssue(issue, ctx);
560
+ case RelationalSchemaNodeKind.index: return mapIndexIssue(issue);
561
+ case RelationalSchemaNodeKind.columnDefault:
562
+ case RelationalSchemaNodeKind.primaryKey:
563
+ case RelationalSchemaNodeKind.foreignKey:
564
+ case RelationalSchemaNodeKind.unique: return notOk(issueConflict(absorbedConflictKind(node.nodeKind), issue.path.join("/")));
565
+ case RelationalSchemaNodeKind.check: return notOk(issueConflict("unsupportedOperation", `SQLite does not support CHECK constraint DDL: ${issue.path.join("/")}`));
566
+ default: return notOk(issueConflict("unsupportedOperation", `Unhandled node kind: ${node.nodeKind}`));
567
+ }
568
+ }
569
+ function classifyCall(call) {
570
+ switch (call.factoryName) {
571
+ case "createTable": return "create-table";
572
+ case "addColumn": return "add-column";
573
+ case "createIndex": return "create-index";
574
+ case "dropColumn": return "drop-column";
575
+ case "dropIndex": return "drop-index";
576
+ case "dropTable": return "drop-table";
577
+ case "recreateTable": return null;
578
+ default: return null;
579
+ }
580
+ }
581
+ const DEFAULT_POLICY = { allowedOperationClasses: [
582
+ "additive",
583
+ "widening",
584
+ "destructive",
585
+ "data"
586
+ ] };
587
+ function planIssues(options) {
588
+ const policyProvided = options.policy !== void 0;
589
+ const policy = options.policy ?? DEFAULT_POLICY;
590
+ const frameworkComponents = options.frameworkComponents ?? [];
591
+ const context = {
592
+ expected: options.expected ?? emptySchemaIR(),
593
+ actual: options.actual ?? emptySchemaIR(),
594
+ policy,
595
+ frameworkComponents
596
+ };
597
+ const strategies = options.strategies ?? sqlitePlannerStrategies;
598
+ let remaining = options.issues;
599
+ const recipeCalls = [];
600
+ const bucketableCalls = [];
601
+ for (const strategy of strategies) {
602
+ const result = strategy(remaining, context);
603
+ if (result.kind === "match") {
604
+ remaining = result.issues;
605
+ if (result.recipe) recipeCalls.push(...result.calls);
606
+ else bucketableCalls.push(...result.calls);
607
+ }
608
+ }
609
+ const sorted = [...remaining].sort((a, b) => {
610
+ const kindDelta = nodeIssueOrder(a) - nodeIssueOrder(b);
611
+ if (kindDelta !== 0) return kindDelta;
612
+ const keyA = nodeIssueKey(a);
613
+ const keyB = nodeIssueKey(b);
614
+ return keyA < keyB ? -1 : keyA > keyB ? 1 : 0;
615
+ });
616
+ const defaultCalls = [];
617
+ const conflicts = [];
618
+ for (const issue of sorted) {
619
+ const result = mapNodeIssueToCall(issue, context);
620
+ if (result.ok) defaultCalls.push(...result.value);
621
+ else conflicts.push(result.failure);
622
+ }
623
+ const allowed = policy.allowedOperationClasses;
624
+ let gatedRecipe = recipeCalls;
625
+ let gatedBucketable = bucketableCalls;
626
+ let gatedDefault = defaultCalls;
627
+ if (policyProvided) {
628
+ const sink = (acc) => (call) => {
629
+ if (allowed.includes(call.operationClass)) {
630
+ acc.push(call);
631
+ return;
632
+ }
633
+ conflicts.push(conflictForDisallowedCall(call, allowed));
634
+ };
635
+ const gatedRecipeBucket = [];
636
+ const gatedBucketableBucket = [];
637
+ const gatedDefaultBucket = [];
638
+ recipeCalls.forEach(sink(gatedRecipeBucket));
639
+ bucketableCalls.forEach(sink(gatedBucketableBucket));
640
+ defaultCalls.forEach(sink(gatedDefaultBucket));
641
+ gatedRecipe = gatedRecipeBucket;
642
+ gatedBucketable = gatedBucketableBucket;
643
+ gatedDefault = gatedDefaultBucket;
644
+ }
645
+ if (conflicts.length > 0) return notOk(conflicts);
646
+ const combined = [...gatedDefault, ...gatedBucketable];
647
+ const byCategory = (cat) => combined.filter((c) => classifyCall(c) === cat);
648
+ return ok({ calls: [
649
+ ...byCategory("create-table"),
650
+ ...byCategory("add-column"),
651
+ ...byCategory("create-index"),
652
+ ...gatedRecipe,
653
+ ...byCategory("drop-column"),
654
+ ...byCategory("drop-index"),
655
+ ...byCategory("drop-table")
656
+ ] });
657
+ }
658
+ function emptySchemaIR() {
659
+ return new SqlSchemaIR({ tables: {} });
660
+ }
661
+ function conflictForDisallowedCall(call, allowed) {
662
+ const summary = `Operation "${call.label}" requires class "${call.operationClass}", but policy allows only: ${allowed.join(", ")}`;
663
+ const location = locationForCall(call);
664
+ return {
665
+ kind: conflictKindForCall(call),
666
+ summary,
667
+ why: "Use `migration new` to author a custom migration for this change.",
668
+ ...location ? { location } : {}
669
+ };
670
+ }
671
+ function conflictKindForCall(call) {
672
+ switch (call.factoryName) {
673
+ case "createIndex":
674
+ case "dropIndex": return "indexIncompatible";
675
+ default: return "missingButNonAdditive";
676
+ }
677
+ }
678
+ function locationForCall(call) {
679
+ const location = {};
680
+ if ("tableName" in call) location.table = call.tableName;
681
+ if ("columnName" in call) location.column = call.columnName;
682
+ if ("indexName" in call) location.index = call.indexName;
683
+ return Object.keys(location).length > 0 ? location : void 0;
684
+ }
685
+ //#endregion
686
+ //#region src/core/migrations/planner.ts
687
+ function createSqliteMigrationPlanner(lowerer) {
688
+ return new SqliteMigrationPlanner(lowerer);
689
+ }
690
+ /**
691
+ * SQLite migration planner — a thin wrapper over `planIssues`.
692
+ *
693
+ * `plan()` diffs the live schema against the target contract via the one
694
+ * differ (`buildSqlitePlanDiff`, producing node-typed `SchemaDiffIssue[]`)
695
+ * and delegates to `planIssues` with the registered strategies. Strategies
696
+ * absorb groups of related issues into composite recipes (e.g. recreating a
697
+ * table to apply type/nullability/default/constraint changes at once);
698
+ * anything not absorbed by a strategy flows through `mapNodeIssueToCall` in
699
+ * the issue planner as a one-off call.
700
+ *
701
+ * FK-backing indexes are already merged into the expected table node's
702
+ * `indexes` at derivation (`contractToSchemaIR`'s `convertTable`), so
703
+ * `mapNodeIssueToCall` handles them uniformly alongside user-declared
704
+ * indexes — no separate expansion step in the planner.
705
+ */
706
+ var SqliteMigrationPlanner = class {
707
+ #lowerer;
708
+ constructor(lowerer) {
709
+ this.#lowerer = lowerer;
710
+ }
711
+ plan(options) {
712
+ return this.planSql(options);
713
+ }
714
+ emptyMigration(context, spaceId) {
715
+ return new TypeScriptRenderableSqliteMigration([], {
716
+ from: context.fromHash,
717
+ to: context.toHash
718
+ }, spaceId, void 0, this.#lowerer);
719
+ }
720
+ planSql(options) {
721
+ const policyResult = this.ensureAdditivePolicy(options.policy);
722
+ if (policyResult) return policyResult;
723
+ const { expected, actual, issues } = this.collectSchemaIssues(options);
724
+ const codecHooks = extractCodecControlHooks(options.frameworkComponents);
725
+ const result = planIssues({
726
+ issues,
727
+ expected,
728
+ actual,
729
+ policy: options.policy,
730
+ frameworkComponents: options.frameworkComponents,
731
+ strategies: sqlitePlannerStrategies
732
+ });
733
+ if (!result.ok) return plannerFailure(result.failure);
734
+ const fieldEventOps = planFieldEventOperations({
735
+ priorContract: options.fromContract,
736
+ newContract: options.contract,
737
+ codecHooks
738
+ });
739
+ const calls = [...result.value.calls, ...fieldEventOps];
740
+ const destination = {
741
+ storageHash: options.contract.storage.storageHash,
742
+ ...options.contract.profileHash !== void 0 ? { profileHash: options.contract.profileHash } : {}
743
+ };
744
+ return {
745
+ kind: "success",
746
+ plan: new TypeScriptRenderableSqliteMigration(calls, {
747
+ from: options.fromContract?.storage.storageHash ?? null,
748
+ to: options.contract.storage.storageHash
749
+ }, options.spaceId, destination, this.#lowerer)
750
+ };
751
+ }
752
+ ensureAdditivePolicy(policy) {
753
+ if (!policy.allowedOperationClasses.includes("additive")) return plannerFailure([{
754
+ kind: "unsupportedOperation",
755
+ summary: "Migration planner requires additive operations be allowed",
756
+ why: "The planner requires the \"additive\" operation class to be allowed in the policy."
757
+ }]);
758
+ return null;
759
+ }
760
+ /**
761
+ * Diffs the target contract against the live schema via the one differ
762
+ * (the same tree-building `diffSqliteSchema` uses, plus the
763
+ * op-render stamper) and prepares the issue list `planIssues` consumes.
764
+ *
765
+ * Three passes, in order:
766
+ * 1. Subtree coalescing — the differ is total (a missing/extra table also
767
+ * emits an issue for every column/constraint under it); those nested
768
+ * issues are redundant once the table-level `CreateTable`/`DropTable`
769
+ * call already accounts for the whole subtree. Runs FIRST, over the
770
+ * complete diff: a sibling-owned extra table's column issues must
771
+ * collapse into its one table-level issue before the ownership pass,
772
+ * because a bare column node carries no table reference — if coalescing
773
+ * ran after ownership dropped the table-level issue, the orphaned column
774
+ * issues would survive and the planner would emit drops against a
775
+ * sibling space's table.
776
+ * 2. Ownership — a live extra is only this plan's to drop when no contract
777
+ * space owns it. The differ ran against THIS space's contract, so a
778
+ * table a sibling owns surfaces here as `not-expected`; the planner asks
779
+ * the ownership oracle (the passive aggregate) whether any space declares
780
+ * it and, if so, leaves it alone. A table no space owns stays a genuine
781
+ * extra. Ownership lives in the aggregate; the planner only asks. No
782
+ * oracle (single-space) keeps every extra.
783
+ * 3. Strict-mode extras gating — `not-expected` (extra table/column/
784
+ * constraint) issues are dropped entirely outside strict mode, mirroring
785
+ * the retired coordinate walk's `if (strict) { ...extra_* } }` guards:
786
+ * an additive-only plan must never even consider dropping an unclaimed
787
+ * object, not just refuse to emit the drop.
788
+ */
789
+ collectSchemaIssues(options) {
790
+ const allowed = options.policy.allowedOperationClasses;
791
+ const strict = allowed.includes("widening") || allowed.includes("destructive");
792
+ const { expected, actual, issues: rawIssues } = buildSqlitePlanDiff({
793
+ contract: options.contract,
794
+ actualSchema: options.schema,
795
+ frameworkComponents: options.frameworkComponents
796
+ });
797
+ const owned = retainUnownedExtras(coalesceSubtreeIssues(rawIssues), options.ownership);
798
+ return {
799
+ expected,
800
+ actual,
801
+ issues: strict ? owned : owned.filter((issue) => issue.reason !== "not-expected")
802
+ };
803
+ }
804
+ };
805
+ /**
806
+ * Drops a `not-expected` issue when it is a whole extra TABLE that some
807
+ * contract space owns, asking the ownership oracle per node.
808
+ *
809
+ * The consultation applies ONLY to table-level extras — a live table this
810
+ * space's contract lacks — identified by asking the issue's own node
811
+ * (`nodeKind === table`), never by counting path segments. SQLite is a
812
+ * single-namespace target, so every coordinate is qualified with the shared
813
+ * `UNBOUND_NAMESPACE_ID` sentinel (the same one the aggregate's declared
814
+ * entities carry for this target). `entityKind` is the literal `'table'`:
815
+ * this function only ever asks about a node already confirmed to be
816
+ * `RelationalSchemaNodeKind.table` (checked just above), and that's a
817
+ * diff-tree `nodeKind` spelling (`'sql-table'`) distinct from the storage
818
+ * `entries` vocabulary `elementCoordinates` walks (`'table'`) — the literal
819
+ * is that storage-entries spelling. `declaresEntity` answers over the whole
820
+ * composition (self included), so a positive answer on such a table means
821
+ * another space owns it (a table this space owned would be in its expected
822
+ * tree, never an extra): leave it. A negative answer means no space owns
823
+ * it — a genuine orphan to drop.
824
+ *
825
+ * A DEEPER extra (an extra column/constraint on a table this space DOES own —
826
+ * only the child drifted, so the table is in the expected tree) is this
827
+ * space's own drift and is always kept for dropping; asking the oracle there
828
+ * would wrongly suppress it, because the owned table answers `true`. No oracle
829
+ * ⇒ every extra is kept (single-space plan).
830
+ */
831
+ function retainUnownedExtras(issues, ownership) {
832
+ if (ownership === void 0) return issues;
833
+ return issues.filter((issue) => {
834
+ if (issue.reason !== "not-expected") return true;
835
+ const node = issueNode(issue);
836
+ if (node === void 0 || node.nodeKind !== RelationalSchemaNodeKind.table) return true;
837
+ const tableName = issue.path[1];
838
+ return tableName === void 0 || !ownership.declaresEntity({
839
+ namespaceId: UNBOUND_NAMESPACE_ID,
840
+ entityKind: "table",
841
+ entityName: tableName
842
+ });
843
+ });
844
+ }
845
+ //#endregion
846
+ export { verifySqliteDatabaseSchema as a, sqliteContractToSchema as i, createSqliteMigrationPlanner as n, diffSqliteSchema as r, SqliteMigrationPlanner as t };
847
+
848
+ //# sourceMappingURL=planner-DGhzXuGh.mjs.map