@uncutsql/core 0.8.0 → 0.9.0
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/README.md +8 -3
- package/dist/index.cjs +427 -91
- package/dist/index.d.cts +157 -18
- package/dist/index.d.ts +157 -18
- package/dist/index.js +425 -93
- package/package.json +4 -3
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Data, Effect, Option, Schema } from "effect";
|
|
1
|
+
import { Data, Effect, Option, Result, Schema } from "effect";
|
|
2
2
|
// src/model.ts
|
|
3
3
|
const tableKey = (table) => JSON.stringify([
|
|
4
4
|
table.catalog ?? null,
|
|
@@ -199,6 +199,35 @@ var SchemaDiffError = class extends Data.TaggedError("SchemaDiffError") {
|
|
|
199
199
|
return this.diagnostics.map((item) => `${item.side}: ${item.message}`).join("\n");
|
|
200
200
|
}
|
|
201
201
|
};
|
|
202
|
+
/**
|
|
203
|
+
* Every column a table change carries over: changed, renamed and unchanged ones. A table option
|
|
204
|
+
* can change how a column with an unchanged declaration stores values (SQLite `STRICT`), so the
|
|
205
|
+
* dialect classifies every pair, not only declaration changes (ADR 0042).
|
|
206
|
+
*/
|
|
207
|
+
const pairedColumns = (before, after, changes) => {
|
|
208
|
+
const pairs = [];
|
|
209
|
+
const touchedBefore = /* @__PURE__ */ new Set();
|
|
210
|
+
const touchedAfter = /* @__PURE__ */ new Set();
|
|
211
|
+
for (const change of changes) if (change._tag === "ColumnChanged" || change._tag === "ColumnRenamed") {
|
|
212
|
+
pairs.push({
|
|
213
|
+
after: change.after,
|
|
214
|
+
before: change.before,
|
|
215
|
+
renamed: change._tag === "ColumnRenamed"
|
|
216
|
+
});
|
|
217
|
+
touchedBefore.add(change.before.key);
|
|
218
|
+
touchedAfter.add(change.after.key);
|
|
219
|
+
} else if (change._tag === "ColumnAdded") touchedAfter.add(change.column.key);
|
|
220
|
+
else if (change._tag === "ColumnRemoved") touchedBefore.add(change.column.key);
|
|
221
|
+
for (const column of after.columns) {
|
|
222
|
+
const source = touchedAfter.has(column.key) ? void 0 : before.columns.find((item) => item.key === column.key && !touchedBefore.has(item.key));
|
|
223
|
+
if (source) pairs.push({
|
|
224
|
+
after: column,
|
|
225
|
+
before: source,
|
|
226
|
+
renamed: false
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
return pairs;
|
|
230
|
+
};
|
|
202
231
|
const validateDatabase = (database, side) => {
|
|
203
232
|
const diagnostics = [];
|
|
204
233
|
const tables = /* @__PURE__ */ new Set();
|
|
@@ -1025,6 +1054,7 @@ const diffDatabases = (before, after) => Effect.gen(function* () {
|
|
|
1025
1054
|
/** Low-level logical lowering of caller-approved intent. Resolve migration decisions first in user-facing workflows. */
|
|
1026
1055
|
const planDatabaseMigration = (diff) => ({
|
|
1027
1056
|
...diff.dropGuards ? { dropGuards: diff.dropGuards } : {},
|
|
1057
|
+
...diff.typeChanges ? { typeChanges: diff.typeChanges } : {},
|
|
1028
1058
|
procedures: diff.changes.map((change) => {
|
|
1029
1059
|
switch (change._tag) {
|
|
1030
1060
|
case "NamespaceAdded":
|
|
@@ -1850,6 +1880,7 @@ const nextMigration = (run, migrations, tipId) => run.baseline && tipId === 0 ?
|
|
|
1850
1880
|
var MigrationDecisionError = class extends Data.TaggedError("MigrationDecisionError") {};
|
|
1851
1881
|
const equal = (a, b) => schemaValueEqual(a, b);
|
|
1852
1882
|
const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1883
|
+
const isJson = Schema.is(Schema.Json);
|
|
1853
1884
|
const idFor = (table, column) => JSON.stringify([tableKey(table), column ?? null]);
|
|
1854
1885
|
const renamedColumnId = (source, target, column) => JSON.stringify([
|
|
1855
1886
|
tableKey(source),
|
|
@@ -1864,12 +1895,103 @@ const valueId = (source, target, value) => JSON.stringify([
|
|
|
1864
1895
|
tableKey(target),
|
|
1865
1896
|
value
|
|
1866
1897
|
]);
|
|
1867
|
-
const
|
|
1898
|
+
const qualifiedName = (identity) => [
|
|
1868
1899
|
identity.catalog,
|
|
1869
1900
|
identity.schema,
|
|
1870
1901
|
identity.name
|
|
1871
1902
|
].filter((part) => part !== void 0).join(".");
|
|
1872
1903
|
const quoted = (value) => `'${JSON.stringify(value).slice(1, -1)}'`;
|
|
1904
|
+
const isTypeChangeKind = (kind) => kind === "type_change_loss" || kind === "type_change_failure";
|
|
1905
|
+
const typeChangeId = (kind, change, support) => {
|
|
1906
|
+
const { source, target } = support.displayTypes(change);
|
|
1907
|
+
return JSON.stringify([
|
|
1908
|
+
kind,
|
|
1909
|
+
tableKey(change.before.table.identity),
|
|
1910
|
+
tableKey(change.after.table.identity),
|
|
1911
|
+
change.before.column.key,
|
|
1912
|
+
change.after.column.key,
|
|
1913
|
+
source,
|
|
1914
|
+
target
|
|
1915
|
+
]);
|
|
1916
|
+
};
|
|
1917
|
+
const typeChangePair = (document, id, kind, support, renames) => {
|
|
1918
|
+
if (!isTypeChangeKind(kind)) return;
|
|
1919
|
+
let parts;
|
|
1920
|
+
try {
|
|
1921
|
+
parts = JSON.parse(id);
|
|
1922
|
+
} catch {
|
|
1923
|
+
return;
|
|
1924
|
+
}
|
|
1925
|
+
if (!Array.isArray(parts) || parts.length !== 7 || parts[0] !== kind) return;
|
|
1926
|
+
const [, source, target, sourceColumn, targetColumn] = parts;
|
|
1927
|
+
const side = (schema, tableId, columnKey) => {
|
|
1928
|
+
const table = schema.tables.find((item) => tableKey(item.identity) === tableId);
|
|
1929
|
+
const column = table?.columns.find((item) => item.key === columnKey);
|
|
1930
|
+
return table && column ? {
|
|
1931
|
+
column,
|
|
1932
|
+
schema,
|
|
1933
|
+
table
|
|
1934
|
+
} : void 0;
|
|
1935
|
+
};
|
|
1936
|
+
const before = side(document.before, source, sourceColumn);
|
|
1937
|
+
const after = side(document.after, target, targetColumn);
|
|
1938
|
+
if (before && after && id === typeChangeId(kind, {
|
|
1939
|
+
after,
|
|
1940
|
+
before
|
|
1941
|
+
}, support)) return {
|
|
1942
|
+
after,
|
|
1943
|
+
before,
|
|
1944
|
+
...renames ? { enumRenames: renames } : {}
|
|
1945
|
+
};
|
|
1946
|
+
};
|
|
1947
|
+
const validateFallback = (document, decision, literal, typeChange, renames) => {
|
|
1948
|
+
const pair = typeChangePair(document, decision.id, decision.kind, typeChange, renames);
|
|
1949
|
+
return pair ? typeChange.validateFallback(pair, literal) : "The type-change decision does not identify a column pair in the snapshots.";
|
|
1950
|
+
};
|
|
1951
|
+
const typeChangeReviews = (diff, schemas, support, scope, renames) => {
|
|
1952
|
+
if (!support) return [];
|
|
1953
|
+
const reviews = [];
|
|
1954
|
+
for (const table of diff.changes) {
|
|
1955
|
+
if (!("changes" in table)) continue;
|
|
1956
|
+
for (const column of pairedColumns(table.before, table.after, table.changes)) {
|
|
1957
|
+
if (scope !== "all" && scope === "nested" !== (table._tag === "TableRenamed" || column.renamed)) continue;
|
|
1958
|
+
const change = {
|
|
1959
|
+
after: {
|
|
1960
|
+
column: column.after,
|
|
1961
|
+
schema: schemas.after,
|
|
1962
|
+
table: table.after
|
|
1963
|
+
},
|
|
1964
|
+
before: {
|
|
1965
|
+
column: column.before,
|
|
1966
|
+
schema: schemas.before,
|
|
1967
|
+
table: table.before
|
|
1968
|
+
},
|
|
1969
|
+
...renames ? { enumRenames: renames } : {}
|
|
1970
|
+
};
|
|
1971
|
+
const classification = support.classify(change);
|
|
1972
|
+
if (classification === void 0 || classification === "lossless") continue;
|
|
1973
|
+
const { source, target } = support.displayTypes(change);
|
|
1974
|
+
const label = `${qualifiedName(table.after.identity)}.${column.after.name}`;
|
|
1975
|
+
const question = (kind, text) => ({
|
|
1976
|
+
column: column.before.key,
|
|
1977
|
+
id: typeChangeId(kind, change, support),
|
|
1978
|
+
kind,
|
|
1979
|
+
question: text,
|
|
1980
|
+
resolution: { action: "pending" },
|
|
1981
|
+
table: table.before.identity
|
|
1982
|
+
});
|
|
1983
|
+
const questions = [];
|
|
1984
|
+
if (classification !== "may_lose") questions.push(question("type_change_failure", `How should the migration handle values that cannot convert when changing ${label} from ${source} to ${target}?`));
|
|
1985
|
+
if (classification !== "may_fail") questions.push(question("type_change_loss", `How should the migration handle values that would lose information when converting ${label} from ${source} to ${target}?`));
|
|
1986
|
+
reviews.push({
|
|
1987
|
+
change,
|
|
1988
|
+
classification,
|
|
1989
|
+
questions
|
|
1990
|
+
});
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
return reviews;
|
|
1994
|
+
};
|
|
1873
1995
|
const missingFrom = (values, other) => {
|
|
1874
1996
|
const present = new Set(other);
|
|
1875
1997
|
return values.filter((value) => !present.has(value));
|
|
@@ -1883,7 +2005,7 @@ const enumQuestions = (change, diff) => {
|
|
|
1883
2005
|
candidates,
|
|
1884
2006
|
enum: identity,
|
|
1885
2007
|
id: enumId(identity),
|
|
1886
|
-
question: `Drop type ${
|
|
2008
|
+
question: `Drop type ${qualifiedName(identity)}, or rename it to an added type?`,
|
|
1887
2009
|
resolution: { action: "pending" }
|
|
1888
2010
|
}] : [];
|
|
1889
2011
|
}
|
|
@@ -1893,7 +2015,7 @@ const enumQuestions = (change, diff) => {
|
|
|
1893
2015
|
candidates,
|
|
1894
2016
|
enum: before.identity,
|
|
1895
2017
|
id: valueId(before.identity, after.identity, value),
|
|
1896
|
-
question: `Rename value ${quoted(value)} of ${
|
|
2018
|
+
question: `Rename value ${quoted(value)} of ${qualifiedName(before.identity)} to an added value?`,
|
|
1897
2019
|
resolution: { action: "pending" },
|
|
1898
2020
|
value
|
|
1899
2021
|
})) : [];
|
|
@@ -1921,13 +2043,27 @@ const questions = (diff) => diff.changes.flatMap((change) => {
|
|
|
1921
2043
|
table: change.table
|
|
1922
2044
|
}));
|
|
1923
2045
|
});
|
|
1924
|
-
const
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
2046
|
+
const defersTypeChanges = (decisions) => decisions.some((item) => "enum" in item && item.candidates.length > 0);
|
|
2047
|
+
const rootReview = (diff, before, after, typeChange) => {
|
|
2048
|
+
const removals = questions(diff);
|
|
2049
|
+
const typeChanges = defersTypeChanges(removals) ? [] : typeChangeReviews(diff, {
|
|
2050
|
+
after,
|
|
2051
|
+
before
|
|
2052
|
+
}, typeChange, "root");
|
|
2053
|
+
return {
|
|
2054
|
+
document: {
|
|
2055
|
+
after,
|
|
2056
|
+
before,
|
|
2057
|
+
decisions: [...removals, ...typeChanges.flatMap((review) => review.questions)],
|
|
2058
|
+
version: 1
|
|
2059
|
+
},
|
|
2060
|
+
typeChanges
|
|
2061
|
+
};
|
|
2062
|
+
};
|
|
2063
|
+
function prepareMigrationDecisions(before, after, typeChange) {
|
|
2064
|
+
return Effect.map(diffDatabases(before, after), (diff) => rootReview(diff, before, after, typeChange).document);
|
|
2065
|
+
}
|
|
2066
|
+
const readAnswers = (pending, inputs, allowPending, typeChange, renames) => Effect.gen(function* () {
|
|
1931
2067
|
const fail = (message) => Effect.fail(new MigrationDecisionError({
|
|
1932
2068
|
message,
|
|
1933
2069
|
pending
|
|
@@ -1939,13 +2075,37 @@ const readAnswers = (pending, inputs, allowPending) => Effect.gen(function* () {
|
|
|
1939
2075
|
if (!record(input) || typeof input.id !== "string") return yield* fail("Each decision needs its original id.");
|
|
1940
2076
|
const question = expected.get(input.id);
|
|
1941
2077
|
if (!question || answers.has(input.id)) return yield* fail(`Unknown or duplicate decision: ${input.id}`);
|
|
1942
|
-
if (!("enum" in question ? input.table === void 0 && input.column === void 0 && equal(input.enum, question.enum) && input.value === question.value : input.enum === void 0 && input.value === void 0 && equal(input.table, question.table) && input.column === question.column)) return yield* fail(`Decision identity changed: ${input.id}`);
|
|
2078
|
+
if (!("enum" in question ? input.table === void 0 && input.column === void 0 && equal(input.enum, question.enum) && input.value === question.value : input.enum === void 0 && input.value === void 0 && equal(input.table, question.table) && input.column === question.column) || "kind" in question && input.kind !== question.kind) return yield* fail(`Decision identity changed: ${input.id}`);
|
|
1943
2079
|
const resolution = input.resolution;
|
|
1944
2080
|
if (allowPending && record(resolution) && resolution.action === "pending" && Object.keys(resolution).length === 1) {
|
|
1945
2081
|
answers.set(input.id, question);
|
|
1946
2082
|
continue;
|
|
1947
2083
|
}
|
|
1948
2084
|
if (!record(resolution) || resolution.action === "pending") return yield* fail(`Unresolved decision: ${question.question}`);
|
|
2085
|
+
if ("kind" in question) {
|
|
2086
|
+
const action = resolution.action;
|
|
2087
|
+
if (Object.keys(resolution).length === 1 && ((action === "accept_loss" || action === "guard") && question.kind === "type_change_loss" || action === "accept_failure" && question.kind === "type_change_failure")) {
|
|
2088
|
+
answers.set(input.id, {
|
|
2089
|
+
...question,
|
|
2090
|
+
resolution: { action }
|
|
2091
|
+
});
|
|
2092
|
+
continue;
|
|
2093
|
+
}
|
|
2094
|
+
const fallback = resolution.fallback;
|
|
2095
|
+
if (question.kind === "type_change_failure" && Object.keys(resolution).length === 1 && record(fallback) && Object.keys(fallback).length === 1 && isJson(fallback.literal)) {
|
|
2096
|
+
const literal = fallback.literal;
|
|
2097
|
+
if (!allowPending && typeChange) {
|
|
2098
|
+
const reason = validateFallback(pending, question, literal, typeChange, renames);
|
|
2099
|
+
if (reason !== void 0) return yield* fail(`Invalid fallback for ${question.question} ${quoted(reason)}`);
|
|
2100
|
+
}
|
|
2101
|
+
answers.set(input.id, {
|
|
2102
|
+
...question,
|
|
2103
|
+
resolution: { fallback: { literal } }
|
|
2104
|
+
});
|
|
2105
|
+
continue;
|
|
2106
|
+
}
|
|
2107
|
+
return yield* fail(`Invalid resolution for ${question.question}`);
|
|
2108
|
+
}
|
|
1949
2109
|
if ((resolution.action === "drop" || resolution.action === "drop_if_empty" && !("enum" in question)) && Object.keys(resolution).length === 1) answers.set(input.id, {
|
|
1950
2110
|
...question,
|
|
1951
2111
|
resolution: { action: resolution.action }
|
|
@@ -1969,7 +2129,7 @@ const readAnswers = (pending, inputs, allowPending) => Effect.gen(function* () {
|
|
|
1969
2129
|
});
|
|
1970
2130
|
} else return yield* fail(`Invalid resolution for ${question.question}`);
|
|
1971
2131
|
}
|
|
1972
|
-
if (answers.size !== expected.size) return yield* fail("Missing migration decisions: every removal requires an explicit resolution.");
|
|
2132
|
+
if (answers.size !== expected.size) return yield* fail(pending.decisions.some((item) => "kind" in item && !answers.has(item.id)) ? "Missing migration decisions: every type-change question requires an explicit resolution." : "Missing migration decisions: every removal requires an explicit resolution.");
|
|
1973
2133
|
return answers;
|
|
1974
2134
|
});
|
|
1975
2135
|
const expandRenames = (diff, answers) => {
|
|
@@ -2013,7 +2173,47 @@ const expandRenames = (diff, answers) => {
|
|
|
2013
2173
|
nested: questions({ changes: renames })
|
|
2014
2174
|
};
|
|
2015
2175
|
};
|
|
2176
|
+
const pairColumns = (diff, resolutionFor) => ({ changes: diff.changes.map((change) => {
|
|
2177
|
+
if (!("changes" in change)) return change;
|
|
2178
|
+
const renamedSources = /* @__PURE__ */ new Set();
|
|
2179
|
+
const renamedTargets = /* @__PURE__ */ new Set();
|
|
2180
|
+
const renames = [];
|
|
2181
|
+
for (const item of change.changes) {
|
|
2182
|
+
if (item._tag !== "ColumnRemoved") continue;
|
|
2183
|
+
const resolution = resolutionFor(columnId(change, item.column.key));
|
|
2184
|
+
if (!record(resolution) || resolution.action !== "rename") continue;
|
|
2185
|
+
const target = change.changes.find((candidate) => candidate._tag === "ColumnAdded" && candidate.column.key === resolution.target);
|
|
2186
|
+
if (target?._tag !== "ColumnAdded") continue;
|
|
2187
|
+
renamedSources.add(item.column.key);
|
|
2188
|
+
renamedTargets.add(target.column.key);
|
|
2189
|
+
const fields = [];
|
|
2190
|
+
if (!equal(item.column.dataType, target.column.dataType)) fields.push("dataType");
|
|
2191
|
+
if (!constraintsEqual(item.column.constraints, target.column.constraints)) fields.push("constraints");
|
|
2192
|
+
renames.push({
|
|
2193
|
+
_tag: "ColumnRenamed",
|
|
2194
|
+
after: target.column,
|
|
2195
|
+
before: item.column,
|
|
2196
|
+
fields
|
|
2197
|
+
});
|
|
2198
|
+
}
|
|
2199
|
+
return {
|
|
2200
|
+
...change,
|
|
2201
|
+
changes: [...renames, ...change.changes.filter((item) => !(item._tag === "ColumnAdded" && renamedTargets.has(item.column.key)) && !(item._tag === "ColumnRemoved" && renamedSources.has(item.column.key)))]
|
|
2202
|
+
};
|
|
2203
|
+
}) });
|
|
2204
|
+
const issuedForTypeChangePairing = (pending, input, deferred, typeChange) => {
|
|
2205
|
+
const pair = typeof input.id === "string" && typeChangePair(pending, input.id, input.kind, typeChange);
|
|
2206
|
+
if (!pair || !equal(input.table, pair.before.table.identity) || input.column !== pair.before.column.key || equal(pair.before.column.dataType, pair.after.column.dataType) && typeChange.classify(pair) === void 0) return false;
|
|
2207
|
+
const { after, before } = pair;
|
|
2208
|
+
const renamedTable = tableKey(before.table.identity) !== tableKey(after.table.identity);
|
|
2209
|
+
if (renamedTable && !pending.decisions.some((parent) => !("enum" in parent) && !("kind" in parent) && parent.column === void 0 && equal(parent.table, before.table.identity) && parent.candidates.some((name) => equal({
|
|
2210
|
+
...parent.table,
|
|
2211
|
+
name
|
|
2212
|
+
}, after.table.identity)))) return false;
|
|
2213
|
+
return before.column.key === after.column.key ? renamedTable || deferred : !before.table.columns.some((column) => column.key === after.column.key) && !after.table.columns.some((column) => column.key === before.column.key);
|
|
2214
|
+
};
|
|
2016
2215
|
const issuedForPairing = (pending, input) => pending.decisions.some((parent) => {
|
|
2216
|
+
if ("kind" in parent) return false;
|
|
2017
2217
|
if ("enum" in parent) {
|
|
2018
2218
|
const value = input.value;
|
|
2019
2219
|
return parent.value === void 0 && typeof value === "string" && equal(parent.enum, input.enum) && parent.candidates.some((name) => input.id === valueId(parent.enum, {
|
|
@@ -2027,29 +2227,55 @@ const issuedForPairing = (pending, input) => pending.decisions.some((parent) =>
|
|
|
2027
2227
|
name
|
|
2028
2228
|
}, column));
|
|
2029
2229
|
});
|
|
2030
|
-
const
|
|
2230
|
+
const readEnumAnswers = (document, questions, inputs) => {
|
|
2231
|
+
const enums = questions.filter((item) => "enum" in item);
|
|
2232
|
+
const expected = new Set(enums.map((item) => item.id));
|
|
2233
|
+
const supplied = inputs.filter((input) => record(input) && typeof input.id === "string" && expected.has(input.id));
|
|
2234
|
+
const ids = new Set(supplied.map((input) => input.id));
|
|
2235
|
+
return readAnswers({
|
|
2236
|
+
...document,
|
|
2237
|
+
decisions: enums
|
|
2238
|
+
}, [...supplied, ...enums.filter((item) => !ids.has(item.id))], true);
|
|
2239
|
+
};
|
|
2240
|
+
const enumsAnswered = (decisions) => !Array.from(decisions).some((item) => "enum" in item && item.resolution.action === "pending");
|
|
2241
|
+
const reviewAnswers = (pending, diff, inputs, merging, typeChange) => Effect.gen(function* () {
|
|
2031
2242
|
const rootIds = new Set(pending.decisions.map((item) => item.id));
|
|
2032
2243
|
const roots = inputs.filter((input) => record(input) && typeof input.id === "string" && rootIds.has(input.id));
|
|
2033
2244
|
const rootAnswers = yield* readAnswers(pending, roots, merging);
|
|
2034
2245
|
const expanded = expandRenames(diff, rootAnswers);
|
|
2246
|
+
const resolutions = new Map(inputs.flatMap((input) => record(input) && typeof input.id === "string" ? [[input.id, input.resolution]] : []));
|
|
2247
|
+
const paired = pairColumns(expanded.diff, (id) => resolutions.get(id));
|
|
2248
|
+
const deferred = defersTypeChanges(pending.decisions);
|
|
2249
|
+
let renames;
|
|
2250
|
+
let nestedTypeChanges = [];
|
|
2251
|
+
if (typeChange && deferred && enumsAnswered(rootAnswers.values())) {
|
|
2252
|
+
const labels = yield* Effect.result(readEnumAnswers(pending, expanded.nested, inputs));
|
|
2253
|
+
if (Result.isSuccess(labels) && enumsAnswered(labels.success.values())) {
|
|
2254
|
+
renames = acceptedEnumRenames(expanded.diff, new Map([...rootAnswers, ...labels.success]));
|
|
2255
|
+
nestedTypeChanges = typeChangeReviews(paired, pending, typeChange, "all", renames);
|
|
2256
|
+
}
|
|
2257
|
+
} else if (!deferred) nestedTypeChanges = typeChangeReviews(paired, pending, typeChange, "nested");
|
|
2258
|
+
const nested = [...expanded.nested, ...nestedTypeChanges.flatMap((item) => item.questions)];
|
|
2035
2259
|
const review = {
|
|
2036
2260
|
...pending,
|
|
2037
|
-
decisions: [...rootAnswers.values(), ...
|
|
2261
|
+
decisions: [...rootAnswers.values(), ...nested]
|
|
2038
2262
|
};
|
|
2039
2263
|
const expected = new Set(review.decisions.map((item) => item.id));
|
|
2040
|
-
const current = inputs.filter((input) => !merging || !record(input) || typeof input.id !== "string" || expected.has(input.id) || !issuedForPairing(pending, input));
|
|
2264
|
+
const current = inputs.filter((input) => !merging || !record(input) || typeof input.id !== "string" || expected.has(input.id) || !(issuedForPairing(pending, input) || typeChange && issuedForTypeChangePairing(pending, input, deferred, typeChange)));
|
|
2041
2265
|
const ids = new Set(current.flatMap((input) => record(input) ? [input.id] : []));
|
|
2042
|
-
const missing =
|
|
2266
|
+
const missing = nested.filter((item) => !ids.has(item.id));
|
|
2043
2267
|
if (!merging && missing.length) {
|
|
2044
|
-
const required = missing.some((item) => "enum" in item) ? "Enum rename requires value decisions" : "Table rename requires column decisions";
|
|
2268
|
+
const required = missing.some((item) => "enum" in item) ? "Enum rename requires value decisions" : missing.some((item) => !("kind" in item)) ? "Table rename requires column decisions" : "Rename requires type-change decisions";
|
|
2045
2269
|
return yield* Effect.fail(new MigrationDecisionError({
|
|
2046
2270
|
message: `${required}. Run --merge-decisions to review them.`,
|
|
2047
2271
|
pending: review
|
|
2048
2272
|
}));
|
|
2049
2273
|
}
|
|
2050
2274
|
return {
|
|
2051
|
-
answers: yield* readAnswers(review, [...current, ...missing], merging),
|
|
2052
|
-
diff: expanded.diff
|
|
2275
|
+
answers: yield* readAnswers(review, [...current, ...missing], merging, typeChange, renames),
|
|
2276
|
+
diff: expanded.diff,
|
|
2277
|
+
nestedTypeChanges,
|
|
2278
|
+
paired
|
|
2053
2279
|
};
|
|
2054
2280
|
});
|
|
2055
2281
|
/** The enum and value renames that the reviewer accepted. */
|
|
@@ -2061,63 +2287,113 @@ const enumRenames = (diff, answers) => {
|
|
|
2061
2287
|
const { after, before } = change;
|
|
2062
2288
|
const key = tableKey(before.identity);
|
|
2063
2289
|
if (change._tag === "EnumRenamed") enums.set(key, after.identity);
|
|
2064
|
-
|
|
2290
|
+
const labels = new Map(before.values.flatMap((value) => {
|
|
2065
2291
|
const choice = answers.get(valueId(before.identity, after.identity, value))?.resolution;
|
|
2066
2292
|
return choice?.action === "rename" ? [[value, choice.target]] : [];
|
|
2067
|
-
}))
|
|
2293
|
+
}));
|
|
2294
|
+
if (labels.size) values.set(key, labels);
|
|
2068
2295
|
}
|
|
2069
2296
|
return {
|
|
2070
2297
|
enums,
|
|
2071
2298
|
values
|
|
2072
2299
|
};
|
|
2073
2300
|
};
|
|
2074
|
-
|
|
2075
|
-
const
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2301
|
+
const acceptedEnumRenames = (diff, answers) => {
|
|
2302
|
+
const renames = enumRenames(diff, answers);
|
|
2303
|
+
return renames.enums.size || renames.values.size ? renames : void 0;
|
|
2304
|
+
};
|
|
2305
|
+
/** Rebuild the column pair and accepted enum renames to validate a proposed fallback. */
|
|
2306
|
+
const validateTypeChangeFallback = (document, decision, literal, typeChange) => {
|
|
2307
|
+
let renames;
|
|
2308
|
+
if (defersTypeChanges(document.decisions)) {
|
|
2309
|
+
const diff = { changes: diffEnums(document.before, document.after) };
|
|
2310
|
+
const answers = Effect.runSync(Effect.result(Effect.gen(function* () {
|
|
2311
|
+
const roots = yield* readEnumAnswers(document, questions(diff), document.decisions);
|
|
2312
|
+
const expanded = expandRenames(diff, roots);
|
|
2313
|
+
const labels = yield* readEnumAnswers(document, expanded.nested, document.decisions);
|
|
2314
|
+
return acceptedEnumRenames(expanded.diff, new Map([...roots, ...labels]));
|
|
2315
|
+
})));
|
|
2316
|
+
if (Result.isFailure(answers)) return answers.failure.message;
|
|
2317
|
+
renames = answers.success;
|
|
2318
|
+
}
|
|
2319
|
+
return validateFallback(document, decision, literal, typeChange, renames);
|
|
2320
|
+
};
|
|
2321
|
+
function mergeMigrationDecisions(fresh, previous, typeChange) {
|
|
2322
|
+
return Effect.gen(function* () {
|
|
2323
|
+
if (!record(previous) || previous.version !== 1 || !Array.isArray(previous.decisions)) return yield* Effect.fail(new MigrationDecisionError({
|
|
2324
|
+
message: "Expected a version 1 migration decision document.",
|
|
2325
|
+
pending: fresh
|
|
2326
|
+
}));
|
|
2327
|
+
const before = yield* decodeDatabaseSchema(previous.before);
|
|
2328
|
+
const after = yield* decodeDatabaseSchema(previous.after);
|
|
2329
|
+
const originalDiff = yield* diffDatabases(before, after);
|
|
2330
|
+
const original = rootReview(originalDiff, before, after, typeChange).document;
|
|
2331
|
+
const { answers } = yield* reviewAnswers(original, originalDiff, previous.decisions, true, typeChange);
|
|
2332
|
+
const carry = (question, renames) => {
|
|
2333
|
+
const answer = answers.get(question.id);
|
|
2334
|
+
if (!answer) return question;
|
|
2335
|
+
if ("kind" in question) {
|
|
2336
|
+
if (!("kind" in answer)) return question;
|
|
2337
|
+
const resolution = answer.resolution;
|
|
2338
|
+
if ("fallback" in resolution && typeChange && validateFallback(fresh, question, resolution.fallback.literal, typeChange, renames) !== void 0) return question;
|
|
2339
|
+
return {
|
|
2340
|
+
...question,
|
|
2341
|
+
resolution
|
|
2342
|
+
};
|
|
2343
|
+
}
|
|
2344
|
+
if ("kind" in answer) return question;
|
|
2345
|
+
const resolution = answer.resolution;
|
|
2346
|
+
if (resolution.action === "rename" && !question.candidates.includes(resolution.target)) return question;
|
|
2347
|
+
return {
|
|
2348
|
+
...question,
|
|
2349
|
+
resolution
|
|
2350
|
+
};
|
|
2351
|
+
};
|
|
2352
|
+
const freshDiff = yield* diffDatabases(fresh.before, fresh.after);
|
|
2353
|
+
const roots = rootReview(freshDiff, fresh.before, fresh.after, typeChange).document.decisions.map((question) => carry(question));
|
|
2354
|
+
const expanded = expandRenames(freshDiff, new Map(roots.map((item) => [item.id, item])));
|
|
2355
|
+
const decisions = [...roots, ...expanded.nested.map((question) => carry(question))];
|
|
2356
|
+
const deferred = defersTypeChanges(roots);
|
|
2357
|
+
if (typeChange && (!deferred || enumsAnswered(decisions))) {
|
|
2358
|
+
const carried = new Map(decisions.map((item) => [item.id, item]));
|
|
2359
|
+
const paired = pairColumns(expanded.diff, (id) => carried.get(id)?.resolution);
|
|
2360
|
+
const renames = deferred ? acceptedEnumRenames(expanded.diff, carried) : void 0;
|
|
2361
|
+
const reviews = typeChangeReviews(paired, fresh, typeChange, deferred ? "all" : "nested", renames);
|
|
2362
|
+
for (const review of reviews) decisions.push(...review.questions.map((question) => carry(question, renames)));
|
|
2363
|
+
}
|
|
2093
2364
|
return {
|
|
2094
|
-
...
|
|
2095
|
-
|
|
2365
|
+
...fresh,
|
|
2366
|
+
decisions
|
|
2096
2367
|
};
|
|
2097
|
-
};
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2368
|
+
});
|
|
2369
|
+
}
|
|
2370
|
+
const resolvedTypeChanges = (reviews, answers) => reviews.map(({ change: { before }, classification, questions }) => {
|
|
2371
|
+
let loss;
|
|
2372
|
+
let failure;
|
|
2373
|
+
for (const question of questions) {
|
|
2374
|
+
const resolution = answers.get(question.id)?.resolution;
|
|
2375
|
+
if (resolution?.action === "accept_loss" || resolution?.action === "guard") loss = resolution.action;
|
|
2376
|
+
else if (resolution?.action === "accept_failure") failure = { action: "accept_failure" };
|
|
2377
|
+
else if (resolution && "fallback" in resolution) failure = { fallback: resolution.fallback };
|
|
2378
|
+
}
|
|
2101
2379
|
return {
|
|
2102
|
-
|
|
2103
|
-
|
|
2380
|
+
classification,
|
|
2381
|
+
column: before.column.name,
|
|
2382
|
+
table: before.table.identity,
|
|
2383
|
+
...loss ? { loss } : {},
|
|
2384
|
+
...failure ? { failure } : {}
|
|
2104
2385
|
};
|
|
2105
2386
|
});
|
|
2106
2387
|
/** Validate untrusted JSON and resolve intent against fresh comparison results. */
|
|
2107
|
-
const resolveMigrationDecisions = (before, after, supplied) => Effect.gen(function* () {
|
|
2388
|
+
const resolveMigrationDecisions = (before, after, supplied, typeChange) => Effect.gen(function* () {
|
|
2108
2389
|
const diff = yield* diffDatabases(before, after);
|
|
2109
|
-
const pending =
|
|
2110
|
-
after,
|
|
2111
|
-
before,
|
|
2112
|
-
decisions: questions(diff),
|
|
2113
|
-
version: 1
|
|
2114
|
-
};
|
|
2390
|
+
const { document: pending, typeChanges: roots } = rootReview(diff, before, after, typeChange);
|
|
2115
2391
|
const fail = (message) => Effect.fail(new MigrationDecisionError({
|
|
2116
2392
|
message,
|
|
2117
2393
|
pending
|
|
2118
2394
|
}));
|
|
2119
2395
|
if (supplied === void 0) {
|
|
2120
|
-
if (pending.decisions.length) return yield* fail("Unresolved migration decisions. Prepare a decision file and resolve each removal before planning.");
|
|
2396
|
+
if (pending.decisions.length) return yield* fail(roots.length ? "Unresolved migration decisions. Prepare a decision file and resolve each question before planning." : "Unresolved migration decisions. Prepare a decision file and resolve each removal before planning.");
|
|
2121
2397
|
return {
|
|
2122
2398
|
decisions: pending,
|
|
2123
2399
|
diff
|
|
@@ -2125,42 +2401,19 @@ const resolveMigrationDecisions = (before, after, supplied) => Effect.gen(functi
|
|
|
2125
2401
|
}
|
|
2126
2402
|
if (!record(supplied) || supplied.version !== 1 || !Array.isArray(supplied.decisions)) return yield* fail("Expected a version 1 migration decision document.");
|
|
2127
2403
|
if (!equal(supplied.before, before) || !equal(supplied.after, after)) return yield* fail("Stale migration decisions: source or target schema changed. Prepare a new decision file.");
|
|
2128
|
-
const reviewed = yield* reviewAnswers(pending, diff, supplied.decisions, false);
|
|
2404
|
+
const reviewed = yield* reviewAnswers(pending, diff, supplied.decisions, false, typeChange);
|
|
2129
2405
|
const answers = reviewed.answers;
|
|
2406
|
+
const typeChanges = resolvedTypeChanges([...roots, ...reviewed.nestedTypeChanges], answers);
|
|
2130
2407
|
const dropGuards = [];
|
|
2131
|
-
const
|
|
2132
|
-
if (
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
const answer = answers.get(columnId(change, item.column.key));
|
|
2141
|
-
if (answer.resolution.action === "drop_if_empty") dropGuards.push({
|
|
2142
|
-
column: item.column.name,
|
|
2143
|
-
table: change.table
|
|
2144
|
-
});
|
|
2145
|
-
if (answer.resolution.action !== "rename") continue;
|
|
2146
|
-
const targetKey = answer.resolution.target;
|
|
2147
|
-
const afterColumn = change.after.columns.find((column) => column.key === targetKey);
|
|
2148
|
-
renamedTargets.add(afterColumn.key);
|
|
2149
|
-
const fields = [];
|
|
2150
|
-
if (!equal(item.column.dataType, afterColumn.dataType)) fields.push("dataType");
|
|
2151
|
-
if (!constraintsEqual(item.column.constraints, afterColumn.constraints)) fields.push("constraints");
|
|
2152
|
-
changes.push({
|
|
2153
|
-
_tag: "ColumnRenamed",
|
|
2154
|
-
after: afterColumn,
|
|
2155
|
-
before: item.column,
|
|
2156
|
-
fields
|
|
2157
|
-
});
|
|
2158
|
-
}
|
|
2159
|
-
return {
|
|
2160
|
-
...change,
|
|
2161
|
-
changes: [...changes, ...change.changes.filter((item) => !(item._tag === "ColumnAdded" && renamedTargets.has(item.column.key)) && !(item._tag === "ColumnRemoved" && answers.get(columnId(change, item.column.key))?.resolution.action === "rename"))]
|
|
2162
|
-
};
|
|
2163
|
-
});
|
|
2408
|
+
for (const change of reviewed.diff.changes) {
|
|
2409
|
+
if (change._tag === "TableRemoved" && answers.get(idFor(change.table))?.resolution.action === "drop_if_empty") dropGuards.push({ table: change.table });
|
|
2410
|
+
if (!("changes" in change)) continue;
|
|
2411
|
+
for (const item of change.changes) if (item._tag === "ColumnRemoved" && answers.get(columnId(change, item.column.key))?.resolution.action === "drop_if_empty") dropGuards.push({
|
|
2412
|
+
column: item.column.name,
|
|
2413
|
+
table: change.table
|
|
2414
|
+
});
|
|
2415
|
+
}
|
|
2416
|
+
const { changes } = reviewed.paired;
|
|
2164
2417
|
const renames = sequenceRenames(changes);
|
|
2165
2418
|
const kept = changes.filter((change) => !/^(Comment|Enum|Sequence|Trigger)/.test(change._tag));
|
|
2166
2419
|
const leading = (change) => /^(Namespace|Extension)/.test(change._tag);
|
|
@@ -2173,7 +2426,8 @@ const resolveMigrationDecisions = (before, after, supplied) => Effect.gen(functi
|
|
|
2173
2426
|
];
|
|
2174
2427
|
const resolved = {
|
|
2175
2428
|
changes: [...withRenames, ...diffComments(before, after, withRenames)],
|
|
2176
|
-
...dropGuards.length ? { dropGuards } : {}
|
|
2429
|
+
...dropGuards.length ? { dropGuards } : {},
|
|
2430
|
+
...typeChanges.length ? { typeChanges } : {}
|
|
2177
2431
|
};
|
|
2178
2432
|
return {
|
|
2179
2433
|
decisions: {
|
|
@@ -2309,6 +2563,17 @@ const mappingResult = Schema.Struct({
|
|
|
2309
2563
|
diagnostics,
|
|
2310
2564
|
schema: Schema.Unknown
|
|
2311
2565
|
});
|
|
2566
|
+
const stringList = Schema.Array(Schema.String);
|
|
2567
|
+
const mapperSubjectDescriptionSchema = Schema.Struct({
|
|
2568
|
+
definitions: Schema.optionalKey(stringList),
|
|
2569
|
+
language: Schema.NonEmptyString,
|
|
2570
|
+
notes: Schema.optionalKey(stringList),
|
|
2571
|
+
types: Schema.Array(Schema.Struct({
|
|
2572
|
+
label: Schema.NonEmptyString,
|
|
2573
|
+
text: Schema.String
|
|
2574
|
+
}))
|
|
2575
|
+
});
|
|
2576
|
+
const subjectDescription = Schema.UndefinedOr(mapperSubjectDescriptionSchema);
|
|
2312
2577
|
const wrapError = (cause, code, path, fallback) => {
|
|
2313
2578
|
if (cause instanceof CodegenError) return cause;
|
|
2314
2579
|
const details = Schema.decodeUnknownOption(taggedCodegenError)(cause);
|
|
@@ -2365,6 +2630,39 @@ const invoke = (callback, code, path) => Effect.flatMap(validate(() => {
|
|
|
2365
2630
|
});
|
|
2366
2631
|
return result;
|
|
2367
2632
|
}, "invalid-plugin", path), (effect) => Effect.mapError(effect, (cause) => wrapError(cause, code, path, `Plugin ${path}() failed`)));
|
|
2633
|
+
/** Optional capability: absent gives no describer; a present value must be a function. */
|
|
2634
|
+
const optionalDescribe = (plugin) => {
|
|
2635
|
+
if (!("describe" in plugin)) return;
|
|
2636
|
+
const callback = plugin.describe;
|
|
2637
|
+
if (typeof callback !== "function") throw new CodegenError({
|
|
2638
|
+
code: "invalid-plugin",
|
|
2639
|
+
message: "Plugin describe() must be a function",
|
|
2640
|
+
path: "describe"
|
|
2641
|
+
});
|
|
2642
|
+
return (schema, subject) => {
|
|
2643
|
+
let result;
|
|
2644
|
+
try {
|
|
2645
|
+
result = Reflect.apply(callback, plugin, [schema, subject]);
|
|
2646
|
+
} catch (cause) {
|
|
2647
|
+
throw new CodegenError({
|
|
2648
|
+
cause,
|
|
2649
|
+
code: "description-failed",
|
|
2650
|
+
message: cause instanceof Error ? cause.message : "Plugin describe() failed",
|
|
2651
|
+
path: "describe"
|
|
2652
|
+
});
|
|
2653
|
+
}
|
|
2654
|
+
try {
|
|
2655
|
+
return Schema.decodeUnknownSync(subjectDescription)(result);
|
|
2656
|
+
} catch (cause) {
|
|
2657
|
+
throw new CodegenError({
|
|
2658
|
+
cause,
|
|
2659
|
+
code: "invalid-description",
|
|
2660
|
+
message: "Plugin describe() returned an invalid subject description",
|
|
2661
|
+
path: "describe"
|
|
2662
|
+
});
|
|
2663
|
+
}
|
|
2664
|
+
};
|
|
2665
|
+
};
|
|
2368
2666
|
/** Validate the mapper value selected from a module by the consumer. */
|
|
2369
2667
|
const decodeMapperPlugin = (value) => validate(() => {
|
|
2370
2668
|
const plugin = readExport(value, "mapper");
|
|
@@ -2372,8 +2670,10 @@ const decodeMapperPlugin = (value) => validate(() => {
|
|
|
2372
2670
|
const decodeInput = method(plugin, "decodeInput");
|
|
2373
2671
|
const decodeOptions = method(plugin, "decodeOptions");
|
|
2374
2672
|
const map = method(plugin, "map");
|
|
2673
|
+
const describeSubject = optionalDescribe(plugin);
|
|
2375
2674
|
return {
|
|
2376
2675
|
descriptor,
|
|
2676
|
+
...describeSubject === void 0 ? {} : { describe: describeSubject },
|
|
2377
2677
|
map: (schema, options) => Effect.gen(function* () {
|
|
2378
2678
|
const input = yield* invoke(() => decodeInput(schema), "invalid-input", "decodeInput");
|
|
2379
2679
|
const settings = yield* invoke(() => decodeOptions(options), "invalid-options", "decodeOptions");
|
|
@@ -2400,4 +2700,36 @@ const decodeGeneratorPlugin = (value) => validate(() => {
|
|
|
2400
2700
|
})
|
|
2401
2701
|
};
|
|
2402
2702
|
}, "invalid-plugin", "generator");
|
|
2403
|
-
|
|
2703
|
+
// src/codegen-pipeline.ts
|
|
2704
|
+
/** Map every profile in order, retaining errors and diagnostics for the caller. */
|
|
2705
|
+
const mapProfiles = (schema, profiles) => Effect.forEach(profiles, ({ mapper, name, options }) => mapper.map(schema, options).pipe(Effect.match({
|
|
2706
|
+
onFailure: (error) => ({
|
|
2707
|
+
mapper,
|
|
2708
|
+
name,
|
|
2709
|
+
result: { error }
|
|
2710
|
+
}),
|
|
2711
|
+
onSuccess: (result) => ({
|
|
2712
|
+
mapper,
|
|
2713
|
+
name,
|
|
2714
|
+
result
|
|
2715
|
+
})
|
|
2716
|
+
})));
|
|
2717
|
+
var GenerationFailure = class extends Data.TaggedError("GenerationFailure") {};
|
|
2718
|
+
/** Check the entire batch's contracts before invoking any generator. */
|
|
2719
|
+
const generate = (mapped, generators) => Effect.gen(function* () {
|
|
2720
|
+
const output = mapped.mapper.descriptor.output;
|
|
2721
|
+
yield* Effect.forEach(generators, ({ generator, name }) => validateApplicationCompatibility(output, generator.descriptor.input).pipe(Effect.mapError((error) => new GenerationFailure({
|
|
2722
|
+
error,
|
|
2723
|
+
generator: name,
|
|
2724
|
+
stage: "compatibility"
|
|
2725
|
+
}))), { discard: true });
|
|
2726
|
+
return yield* Effect.forEach(generators, ({ generator, name, options }) => generator.generate(output, mapped.result.schema, options).pipe(Effect.mapError((error) => new GenerationFailure({
|
|
2727
|
+
error,
|
|
2728
|
+
generator: name,
|
|
2729
|
+
stage: "generation"
|
|
2730
|
+
})), Effect.map((result) => ({
|
|
2731
|
+
name,
|
|
2732
|
+
result
|
|
2733
|
+
}))));
|
|
2734
|
+
});
|
|
2735
|
+
export { CodegenError, MigrationDecisionError, SchemaDiffError, SchemaModelError, StatementEditError, artifactPathSchema, changedExternals, checkManagedScope, codegenDiagnosticSchema, commentObjects, compareTable, completionCandidates, constraintsEqual, continuesRun, declarationAt, decodeDatabaseSchema, decodeGenerationResult, decodeGeneratorPlugin, decodeMapperPlugin, definitions, diffComments, diffDatabases, diffEnums, diffFunctions, diffSequences, diffStructures, diffTriggers, enumObjects, extensionObjects, externalObjects, formatExtractOmissions, functionKey, functionLabel, generate, generatedFileHeader, hashMigrationPair, mapProfiles, mergeMigrationDecisions, migrationRun, nameSpan, namespaceKey, namespaceOf, nextMigration, pairedColumns, planDatabaseMigration, planDownMigration, prepareMigrationDecisions, referenceAt, referencesTo, relationIdentitySchema, renameSiteAt, renameSpans, resolveMigrationDecisions, schemaValueEqual, sequenceRenames, tableKey, triggerKey, validateApplicationCompatibility, validateDatabase, validateTypeChangeFallback };
|