feat(schema-diff): compare routines across same-structure databases
This commit is contained in:
1 parent
bd2ac50ac1
commit
1191118b5c
31 files changed
+2256
-281
No files matched your search
+31
-1
@@ -1,5 +1,15 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { customTypeCapabilities, databaseObjectCapabilities, normalizeSidebarObjectKind, sidebarObjectKindsForDatabase, supportsPackageMemberExpansion, supportsTypeObjectSource } from "@/lib/database/databaseObjectCapabilities";
|
||||
import {
|
||||
customTypeCapabilities,
|
||||
databaseObjectCapabilities,
|
||||
normalizeSidebarObjectKind,
|
||||
schemaDiffRoutineObjectTypes,
|
||||
schemaDiffRoutineObjectTypesIntersection,
|
||||
sidebarObjectKindsForDatabase,
|
||||
supportsPackageMemberExpansion,
|
||||
supportsSchemaDiffRoutines,
|
||||
supportsTypeObjectSource,
|
||||
} from "@/lib/database/databaseObjectCapabilities";
|
||||
import { buildObjectGroupPlaceholderNodes } from "@/lib/table/tableTree";
|
||||
|
||||
describe("databaseObjectCapabilities", () => {
|
||||
@@ -128,4 +138,24 @@ describe("databaseObjectCapabilities", () => {
|
||||
expect(customTypeCapabilities(dbType), String(dbType)).toEqual({ details: false, members: false, ddl: false });
|
||||
}
|
||||
});
|
||||
|
||||
it("opens schema diff routines only for same-dialect allowlisted databases", () => {
|
||||
for (const dbType of ["postgres", "opengauss", "mysql", "sqlserver", "gaussdb", "kingbase"] as const) {
|
||||
expect(supportsSchemaDiffRoutines(dbType), dbType).toBe(true);
|
||||
}
|
||||
for (const dbType of ["oracle", "dameng", "hive", "sqlite", "doris", "databend", "manticoresearch"] as const) {
|
||||
expect(supportsSchemaDiffRoutines(dbType), dbType).toBe(false);
|
||||
}
|
||||
// Fallback ROUTINE_OBJECTS must not open schema-diff routine compare.
|
||||
expect(supportsSchemaDiffRoutines("jdbc")).toBe(false);
|
||||
expect(supportsSchemaDiffRoutines(undefined)).toBe(false);
|
||||
expect(schemaDiffRoutineObjectTypes("mysql")).toEqual(["PROCEDURE", "FUNCTION"]);
|
||||
expect(schemaDiffRoutineObjectTypes("sqlserver")).toEqual(["PROCEDURE", "FUNCTION"]);
|
||||
expect(schemaDiffRoutineObjectTypes("oracle")).toEqual([]);
|
||||
expect(schemaDiffRoutineObjectTypesIntersection("mysql", "mysql")).toEqual(["PROCEDURE", "FUNCTION"]);
|
||||
expect(schemaDiffRoutineObjectTypesIntersection("mysql", "oracle")).toEqual([]);
|
||||
expect(schemaDiffRoutineObjectTypesIntersection("mysql", "sqlserver")).toEqual([]);
|
||||
expect(schemaDiffRoutineObjectTypesIntersection("postgres", "opengauss")).toEqual(["PROCEDURE", "FUNCTION"]);
|
||||
expect(sidebarObjectKindsForDatabase("sqlserver")).toEqual(["TABLE", "VIEW", "PROCEDURE", "FUNCTION"]);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createConcurrencyLimiter, loadSchemaDetails, mapWithConcurrency, schemaDiffMetadataConcurrency, schemaDiffMetadataLoadPlan, shouldFetchSchemaDiffDdl, type SchemaDiffMetadataApi, type SchemaDiffMetadataProgress } from "../../schema/schemaDiffMetadataLoad";
|
||||
import { getSchemaDiffNextProgressStep, shouldLoadSchemaDiffExtraObjects } from "../../schema/schemaDiffProgress";
|
||||
import { getSchemaDiffNextProgressStep, shouldLoadSchemaDiffExtraObjectPhase, shouldLoadSchemaDiffExtraObjects, shouldLoadSchemaDiffRoutines } from "../../schema/schemaDiffProgress";
|
||||
import { DEFAULT_MYSQL_OPTIONS, DEFAULT_POSTGRES_OPTIONS } from "../../../types/schemaDiff";
|
||||
import type { TableInfo } from "../../../types/database";
|
||||
|
||||
@@ -187,6 +187,16 @@ describe("schemaDiffMetadataLoad", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("treats supported same-dialect routine compare as an extra-object progress phase", () => {
|
||||
expect(shouldLoadSchemaDiffRoutines("mysql", "mysql", { functions: true })).toBe(true);
|
||||
expect(shouldLoadSchemaDiffRoutines("mysql", "oracle", { functions: true })).toBe(false);
|
||||
expect(shouldLoadSchemaDiffRoutines("mysql", "sqlite", { functions: true })).toBe(false);
|
||||
expect(shouldLoadSchemaDiffRoutines("mysql", "mysql", { functions: false })).toBe(false);
|
||||
expect(shouldLoadSchemaDiffExtraObjectPhase("mysql", "mysql", DEFAULT_MYSQL_OPTIONS)).toBe(true);
|
||||
expect(shouldLoadSchemaDiffExtraObjectPhase("mysql", "mysql", { ...DEFAULT_MYSQL_OPTIONS, functions: false })).toBe(false);
|
||||
expect(shouldLoadSchemaDiffExtraObjectPhase("postgres", "postgres", DEFAULT_POSTGRES_OPTIONS)).toBe(true);
|
||||
});
|
||||
|
||||
it("maps phases to the next step on the actual comparison path", () => {
|
||||
expect(getSchemaDiffNextProgressStep("loading-table-lists", false)).toBe("nextSourceDetails");
|
||||
expect(getSchemaDiffNextProgressStep("loading-source-details", false)).toBe("nextTargetDetails");
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
countSchemaDiffActionableObjects,
|
||||
filterSchemaDiffFunctions,
|
||||
isSchemaDiffUnrestrictedRoutineLoadTooLarge,
|
||||
partitionSchemaDiffObjectsByResultTab,
|
||||
SCHEMA_DIFF_UNRESTRICTED_ROUTINE_LIMIT,
|
||||
schemaDiffRoutineKey,
|
||||
schemaDiffRoutineKeyFromFunction,
|
||||
summarizeSchemaDiffRoutineTextDiff,
|
||||
} from "@/lib/schema/schemaDiffRoutine";
|
||||
import type { SchemaDiffObject } from "@/lib/schema/schemaDiff";
|
||||
import type { FunctionInfo } from "@/types/database";
|
||||
|
||||
function fn(name: string, args = "", definition = "body"): FunctionInfo {
|
||||
return { name, function_type: "FUNCTION", data_type: "void", definition, arguments: args };
|
||||
}
|
||||
|
||||
function obj(partial: Partial<SchemaDiffObject> & Pick<SchemaDiffObject, "id" | "objectKind" | "operationType" | "name">): SchemaDiffObject {
|
||||
return {
|
||||
selected: true,
|
||||
...partial,
|
||||
};
|
||||
}
|
||||
|
||||
describe("schemaDiffRoutine", () => {
|
||||
it("builds stable routine keys for overloaded functions", () => {
|
||||
expect(schemaDiffRoutineKey("add")).toBe("add");
|
||||
expect(schemaDiffRoutineKey("add", "integer")).toBe("add(integer)");
|
||||
expect(schemaDiffRoutineKeyFromFunction(fn("add", "integer, text"))).toBe("add(integer, text)");
|
||||
});
|
||||
|
||||
it("blocks unrestricted compare when routine count exceeds the soft limit", () => {
|
||||
expect(SCHEMA_DIFF_UNRESTRICTED_ROUTINE_LIMIT).toBe(200);
|
||||
expect(isSchemaDiffUnrestrictedRoutineLoadTooLarge(200, undefined)).toBe(false);
|
||||
expect(isSchemaDiffUnrestrictedRoutineLoadTooLarge(201, undefined)).toBe(true);
|
||||
expect(isSchemaDiffUnrestrictedRoutineLoadTooLarge(500, ["a"])).toBe(false);
|
||||
});
|
||||
|
||||
it("filters selected source routines and same-name mapped targets", () => {
|
||||
const source = [fn("a"), fn("b", "int"), fn("c")];
|
||||
const target = [fn("a"), fn("b", "int"), fn("c"), fn("orphan")];
|
||||
const filtered = filterSchemaDiffFunctions(source, target, ["a", "b(int)"], [{ sourceRoutine: "b(int)", targetRoutine: "b(int)" }]);
|
||||
expect(filtered.sourceFunctions.map((item) => schemaDiffRoutineKeyFromFunction(item))).toEqual(["a", "b(int)"]);
|
||||
expect(filtered.targetFunctions.map((item) => schemaDiffRoutineKeyFromFunction(item))).toEqual(["a", "b(int)"]);
|
||||
});
|
||||
|
||||
it("ignores non-identity rename mappings until backend rematch exists", () => {
|
||||
const source = [fn("a"), fn("b", "int"), fn("c")];
|
||||
const target = [fn("a"), fn("b_new", "int"), fn("c"), fn("orphan")];
|
||||
const filtered = filterSchemaDiffFunctions(source, target, ["a", "b(int)"], [{ sourceRoutine: "b(int)", targetRoutine: "b_new(int)" }]);
|
||||
expect(filtered.sourceFunctions.map((item) => schemaDiffRoutineKeyFromFunction(item))).toEqual(["a", "b(int)"]);
|
||||
// Without same-name target for b(int), only auto-matched "a" is kept on the target side.
|
||||
expect(filtered.targetFunctions.map((item) => schemaDiffRoutineKeyFromFunction(item))).toEqual(["a"]);
|
||||
});
|
||||
|
||||
it("keeps all functions when selection is unrestricted", () => {
|
||||
const source = [fn("a")];
|
||||
const target = [fn("a"), fn("b")];
|
||||
expect(filterSchemaDiffFunctions(source, target, undefined)).toEqual({ sourceFunctions: source, targetFunctions: target });
|
||||
});
|
||||
|
||||
it("partitions result objects into table and routine tabs", () => {
|
||||
const objects = [obj({ id: "t1", objectKind: "table", operationType: "modify", name: "t1" }), obj({ id: "f1", objectKind: "function", operationType: "create", name: "f1" }), obj({ id: "v1", objectKind: "view", operationType: "none", name: "v1" })];
|
||||
const { tableObjects, routineObjects } = partitionSchemaDiffObjectsByResultTab(objects);
|
||||
expect(tableObjects.map((item) => item.id)).toEqual(["t1", "v1"]);
|
||||
expect(routineObjects.map((item) => item.id)).toEqual(["f1"]);
|
||||
expect(countSchemaDiffActionableObjects(tableObjects)).toBe(1);
|
||||
expect(countSchemaDiffActionableObjects(routineObjects)).toBe(1);
|
||||
});
|
||||
|
||||
it("summarizes routine DDL line diffs for create, delete, and modify", () => {
|
||||
expect(summarizeSchemaDiffRoutineTextDiff(undefined, undefined)).toEqual({ added: 0, removed: 0, modified: 0 });
|
||||
expect(summarizeSchemaDiffRoutineTextDiff("a\nb\nc", "")).toEqual({ added: 3, removed: 0, modified: 0 });
|
||||
expect(summarizeSchemaDiffRoutineTextDiff("", "x\ny")).toEqual({ added: 0, removed: 2, modified: 0 });
|
||||
|
||||
const modified = summarizeSchemaDiffRoutineTextDiff("line1\nold\nline3", "line1\nnew\nline3\nextra");
|
||||
expect(modified.modified).toBeGreaterThanOrEqual(1);
|
||||
expect(modified.added).toBeGreaterThanOrEqual(1);
|
||||
expect(modified.removed).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -92,6 +92,8 @@ describe("schema diff table mappings", () => {
|
||||
expect(normalizeSchemaDiffCompareOptions({}).tableMappings).toEqual([]);
|
||||
expect(normalizeSchemaDiffCompareOptions({}).ignoreTableNameCase).toBe(false);
|
||||
expect(normalizeSchemaDiffCompareOptions({}).ignoreColumnNameCase).toBe(false);
|
||||
expect(normalizeSchemaDiffCompareOptions({ tables: false, views: true }, "mysql").views).toBe(false);
|
||||
expect(normalizeSchemaDiffCompareOptions({ tables: true, views: true }, "mysql").views).toBe(true);
|
||||
});
|
||||
|
||||
it("swaps each mapping direction", () => {
|
||||
|
||||
@@ -55,6 +55,10 @@ const DATABASE_TYPE_OBJECTS = new Map<DatabaseType, SidebarObjectKind[]>([
|
||||
["oceanbase-oracle", OCEANBASE_ORACLE_OBJECTS],
|
||||
["xugu", XUGU_OBJECTS],
|
||||
["mysql", MYSQL_OBJECTS],
|
||||
// Explicit entry so schema-diff routine gating can opt in without relying on the
|
||||
// unknown-type ROUTINE_OBJECTS fallback. Keep the same object set the fallback
|
||||
// already used (no TRIGGER/SEQUENCE expansion in this change).
|
||||
["sqlserver", ROUTINE_OBJECTS],
|
||||
// table and view
|
||||
["sqlite", TABLE_VIEW_OBJECTS],
|
||||
["rqlite", TABLE_VIEW_OBJECTS],
|
||||
@@ -119,6 +123,49 @@ export function databaseObjectCapabilities(dbType?: DatabaseType): DatabaseObjec
|
||||
};
|
||||
}
|
||||
|
||||
const SCHEMA_DIFF_ROUTINE_KINDS = ["PROCEDURE", "FUNCTION"] as const;
|
||||
|
||||
/** Same-dialect families with verified list_objects + get_object_source (or PG catalog) paths. */
|
||||
const SCHEMA_DIFF_ROUTINE_FAMILY = new Map<DatabaseType, "postgres" | "mysql" | "sqlserver">([
|
||||
["postgres", "postgres"],
|
||||
["opengauss", "postgres"],
|
||||
["gaussdb", "postgres"],
|
||||
["kwdb", "postgres"],
|
||||
["kingbase", "postgres"],
|
||||
["highgo", "postgres"],
|
||||
["uxdb", "postgres"],
|
||||
["vastbase", "postgres"],
|
||||
["redshift", "postgres"],
|
||||
["mysql", "mysql"],
|
||||
["sqlserver", "sqlserver"],
|
||||
]);
|
||||
|
||||
/**
|
||||
* Schema Diff routine compare is limited to an allowlist of same-dialect families.
|
||||
* Sidebar may list routines for more engines (oracle/hive/…); those stay out of
|
||||
* schema-diff until a verified compare path lands. Cross-family pairs never match.
|
||||
*/
|
||||
export function supportsSchemaDiffRoutines(dbType?: DatabaseType): boolean {
|
||||
if (!dbType || !SCHEMA_DIFF_ROUTINE_FAMILY.has(dbType)) return false;
|
||||
const { sidebarObjects, sourceReadable } = databaseObjectCapabilities(dbType);
|
||||
return SCHEMA_DIFF_ROUTINE_KINDS.some((kind) => sidebarObjects.includes(kind) && sourceReadable.includes(kind));
|
||||
}
|
||||
|
||||
export function schemaDiffRoutineObjectTypes(dbType?: DatabaseType): Array<"PROCEDURE" | "FUNCTION"> {
|
||||
if (!supportsSchemaDiffRoutines(dbType)) return [];
|
||||
const { sidebarObjects, sourceReadable } = databaseObjectCapabilities(dbType);
|
||||
return SCHEMA_DIFF_ROUTINE_KINDS.filter((kind) => sidebarObjects.includes(kind) && sourceReadable.includes(kind));
|
||||
}
|
||||
|
||||
export function schemaDiffRoutineObjectTypesIntersection(sourceDbType?: DatabaseType, targetDbType?: DatabaseType): Array<"PROCEDURE" | "FUNCTION"> {
|
||||
if (!sourceDbType || !targetDbType) return [];
|
||||
const sourceFamily = SCHEMA_DIFF_ROUTINE_FAMILY.get(sourceDbType);
|
||||
const targetFamily = SCHEMA_DIFF_ROUTINE_FAMILY.get(targetDbType);
|
||||
if (!sourceFamily || sourceFamily !== targetFamily) return [];
|
||||
const sourceTypes = new Set(schemaDiffRoutineObjectTypes(sourceDbType));
|
||||
return schemaDiffRoutineObjectTypes(targetDbType).filter((kind) => sourceTypes.has(kind));
|
||||
}
|
||||
|
||||
export function sidebarObjectKindsForDatabase(dbType?: DatabaseType): SidebarObjectKind[] {
|
||||
if (!dbType) return [...TABLE_VIEW_OBJECTS];
|
||||
return DATABASE_TYPE_OBJECTS.get(dbType) ?? [...ROUTINE_OBJECTS];
|
||||
|
||||
@@ -384,6 +384,8 @@ export interface SchemaDiffObject {
|
||||
parentName?: string;
|
||||
/** Function arguments signature (for PostgreSQL overloaded functions) */
|
||||
arguments?: string;
|
||||
/** PROCEDURE vs FUNCTION when objectKind is function (for getObjectSource). */
|
||||
routineType?: "PROCEDURE" | "FUNCTION";
|
||||
renameMetadata?: {
|
||||
confirmed: boolean;
|
||||
sourceName?: string;
|
||||
@@ -718,12 +720,15 @@ export function convertToSchemaDiffObjects(tableDiffs: TableDiff[], functionDiff
|
||||
|
||||
for (const diff of functionDiffs) {
|
||||
const args = diff.source?.arguments || diff.target?.arguments || "";
|
||||
const functionType = (diff.source?.function_type || diff.target?.function_type || "").toUpperCase();
|
||||
const routineType: "PROCEDURE" | "FUNCTION" = functionType.includes("PROC") ? "PROCEDURE" : "FUNCTION";
|
||||
objects.push({
|
||||
id: `func-${diff.name}-${args}`,
|
||||
operationType: getOperationType(diff.type),
|
||||
objectKind: "function",
|
||||
name: diff.name,
|
||||
arguments: args,
|
||||
routineType,
|
||||
sourceName: diff.type === "added" ? undefined : diff.name,
|
||||
targetName: diff.type === "removed" ? undefined : diff.name,
|
||||
selected: true,
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import type { SchemaDiffCompareOptions } from "@/types/schemaDiff";
|
||||
import type { DatabaseType } from "@/types/database";
|
||||
import { schemaDiffRoutineObjectTypesIntersection } from "@/lib/database/databaseObjectCapabilities";
|
||||
|
||||
export type SchemaDiffProgressPhase = "loading-table-lists" | "loading-source-details" | "loading-target-details" | "loading-extra-objects" | "comparing" | "generating" | "complete";
|
||||
|
||||
@@ -9,10 +11,22 @@ export function isSchemaDiffPostgresLike(dbType: string | null | undefined): boo
|
||||
return normalizedDbType === "postgres" || normalizedDbType === "opengauss";
|
||||
}
|
||||
|
||||
/** Extra objects that remain Postgres-catalog specific (sequences/rules/owners + PG function fast path). Routine compare for other DBs is gated separately via supportsSchemaDiffRoutines. */
|
||||
export function shouldLoadSchemaDiffExtraObjects(dbType: string | null | undefined, options: Pick<SchemaDiffCompareOptions, "functions" | "sequences" | "rules" | "owners">): boolean {
|
||||
return isSchemaDiffPostgresLike(dbType) && (options.functions || options.sequences || options.rules || options.owners);
|
||||
}
|
||||
|
||||
/** True when session will load routines via listFunctions for a supported source/target pair. */
|
||||
export function shouldLoadSchemaDiffRoutines(sourceDbType: string | null | undefined, targetDbType: string | null | undefined, options: Pick<SchemaDiffCompareOptions, "functions">): boolean {
|
||||
if (!options.functions) return false;
|
||||
return schemaDiffRoutineObjectTypesIntersection(sourceDbType as DatabaseType | undefined, targetDbType as DatabaseType | undefined).length > 0;
|
||||
}
|
||||
|
||||
/** Unified extra-object progress phase used by session + dialog next-step hints. */
|
||||
export function shouldLoadSchemaDiffExtraObjectPhase(sourceDbType: string | null | undefined, targetDbType: string | null | undefined, options: Pick<SchemaDiffCompareOptions, "functions" | "sequences" | "rules" | "owners">): boolean {
|
||||
return shouldLoadSchemaDiffExtraObjects(targetDbType, options) || shouldLoadSchemaDiffRoutines(sourceDbType, targetDbType, options);
|
||||
}
|
||||
|
||||
export function getSchemaDiffNextProgressStep(phase: SchemaDiffProgressPhase | undefined, hasExtraObjectPhase: boolean): SchemaDiffNextProgressStep | null {
|
||||
switch (phase) {
|
||||
case "loading-table-lists":
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
import type { FunctionInfo } from "@/types/database";
|
||||
import type { SchemaDiffRoutineMapping } from "@/types/schemaDiff";
|
||||
import type { DiffObjectKind, SchemaDiffObject } from "@/lib/schema/schemaDiff";
|
||||
import { buildTextDiff } from "@/lib/common/textDiff";
|
||||
import {
|
||||
areSchemaDiffTableMappingsEqual,
|
||||
availableSchemaDiffTargetTables,
|
||||
buildSchemaDiffTableMatches,
|
||||
pruneSchemaDiffTableMappings,
|
||||
reconcileSchemaDiffTableMappings,
|
||||
swapSchemaDiffTableMappings,
|
||||
updateSchemaDiffTableMapping,
|
||||
type SchemaDiffTableMatch,
|
||||
type SchemaDiffTableMappingUpdate,
|
||||
} from "@/lib/schema/schemaDiffTableMapping";
|
||||
|
||||
export interface SchemaDiffRoutineTextDiffStats {
|
||||
added: number;
|
||||
removed: number;
|
||||
modified: number;
|
||||
}
|
||||
|
||||
/** Unrestricted routine compare loads every definition; require explicit selection above this count. */
|
||||
export const SCHEMA_DIFF_UNRESTRICTED_ROUTINE_LIMIT = 200;
|
||||
|
||||
export function isSchemaDiffUnrestrictedRoutineLoadTooLarge(routineCount: number, selectedRoutines: string[] | undefined): boolean {
|
||||
return selectedRoutines === undefined && routineCount > SCHEMA_DIFF_UNRESTRICTED_ROUTINE_LIMIT;
|
||||
}
|
||||
|
||||
function countNonEmptyLines(text: string): number {
|
||||
if (!text) return 0;
|
||||
const normalized = text.replace(/\r\n?/g, "\n");
|
||||
if (!normalized) return 0;
|
||||
const lines = normalized.split("\n");
|
||||
if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
|
||||
return lines.length;
|
||||
}
|
||||
|
||||
/** Line-level add/remove/modify counts for routine DDL side-by-side comparison. */
|
||||
export function summarizeSchemaDiffRoutineTextDiff(sourceDdl?: string | null, targetDdl?: string | null): SchemaDiffRoutineTextDiffStats {
|
||||
const source = sourceDdl ?? "";
|
||||
const target = targetDdl ?? "";
|
||||
if (!source && !target) return { added: 0, removed: 0, modified: 0 };
|
||||
// Source-only (create on target): count as additions. Target-only (drop on target): removals.
|
||||
if (source && !target) return { added: countNonEmptyLines(source), removed: 0, modified: 0 };
|
||||
if (!source && target) return { added: 0, removed: countNonEmptyLines(target), modified: 0 };
|
||||
|
||||
let added = 0;
|
||||
let removed = 0;
|
||||
let modified = 0;
|
||||
for (const row of buildTextDiff(source, target)) {
|
||||
if (row.kind === "added") added += 1;
|
||||
else if (row.kind === "removed") removed += 1;
|
||||
else if (row.kind === "modified") modified += 1;
|
||||
}
|
||||
return { added, removed, modified };
|
||||
}
|
||||
|
||||
export type SchemaDiffRoutineMatch = SchemaDiffTableMatch & {
|
||||
sourceRoutine: string;
|
||||
targetRoutine?: string;
|
||||
};
|
||||
|
||||
const ROUTINE_OBJECT_KINDS = new Set<DiffObjectKind>(["function"]);
|
||||
|
||||
/** Stable routine identity for overloaded functions: `name` or `name(args)`. */
|
||||
export function schemaDiffRoutineKey(name: string, args = ""): string {
|
||||
const trimmedArgs = args.trim();
|
||||
return trimmedArgs ? `${name}(${trimmedArgs})` : name;
|
||||
}
|
||||
|
||||
export function schemaDiffRoutineKeyFromFunction(fn: Pick<FunctionInfo, "name" | "arguments">): string {
|
||||
return schemaDiffRoutineKey(fn.name, fn.arguments);
|
||||
}
|
||||
|
||||
export function isSchemaDiffRoutineObjectKind(kind: DiffObjectKind): boolean {
|
||||
return ROUTINE_OBJECT_KINDS.has(kind);
|
||||
}
|
||||
|
||||
export function isSchemaDiffRoutineObject(object: Pick<SchemaDiffObject, "objectKind">): boolean {
|
||||
return isSchemaDiffRoutineObjectKind(object.objectKind);
|
||||
}
|
||||
|
||||
export function partitionSchemaDiffObjectsByResultTab(objects: SchemaDiffObject[]): { tableObjects: SchemaDiffObject[]; routineObjects: SchemaDiffObject[] } {
|
||||
const tableObjects: SchemaDiffObject[] = [];
|
||||
const routineObjects: SchemaDiffObject[] = [];
|
||||
for (const object of objects) {
|
||||
if (isSchemaDiffRoutineObject(object)) routineObjects.push(object);
|
||||
else tableObjects.push(object);
|
||||
}
|
||||
return { tableObjects, routineObjects };
|
||||
}
|
||||
|
||||
/** Count objects that are not "none" (used for tab badges). */
|
||||
export function countSchemaDiffActionableObjects(objects: SchemaDiffObject[]): number {
|
||||
return objects.filter((object) => object.operationType !== "none").length;
|
||||
}
|
||||
|
||||
function toTableMappings(mappings: readonly SchemaDiffRoutineMapping[]) {
|
||||
return mappings.map((mapping) => ({ sourceTable: mapping.sourceRoutine, targetTable: mapping.targetRoutine }));
|
||||
}
|
||||
|
||||
function fromTableMappings(mappings: { sourceTable: string; targetTable: string }[]): SchemaDiffRoutineMapping[] {
|
||||
return mappings.map((mapping) => ({ sourceRoutine: mapping.sourceTable, targetRoutine: mapping.targetTable }));
|
||||
}
|
||||
|
||||
export function pruneSchemaDiffRoutineMappings(selectedRoutines: readonly string[], mappings: readonly SchemaDiffRoutineMapping[]): SchemaDiffRoutineMapping[] {
|
||||
return fromTableMappings(pruneSchemaDiffTableMappings(selectedRoutines, toTableMappings(mappings)));
|
||||
}
|
||||
|
||||
export function reconcileSchemaDiffRoutineMappings(selectedRoutines: readonly string[], targetRoutines: readonly string[], mappings: readonly SchemaDiffRoutineMapping[], ignoreNameCase = false): SchemaDiffRoutineMapping[] {
|
||||
return fromTableMappings(reconcileSchemaDiffTableMappings(selectedRoutines, targetRoutines, toTableMappings(mappings), ignoreNameCase));
|
||||
}
|
||||
|
||||
export function buildSchemaDiffRoutineMatches(selectedRoutines: readonly string[], targetRoutines: readonly string[], mappings: readonly SchemaDiffRoutineMapping[], ignoreNameCase = false): SchemaDiffRoutineMatch[] {
|
||||
return buildSchemaDiffTableMatches(selectedRoutines, targetRoutines, toTableMappings(mappings), ignoreNameCase).map((match) => ({
|
||||
...match,
|
||||
sourceRoutine: match.sourceTable,
|
||||
targetRoutine: match.targetTable,
|
||||
}));
|
||||
}
|
||||
|
||||
export function updateSchemaDiffRoutineMapping(mappings: readonly SchemaDiffRoutineMapping[], sourceRoutine: string, targetRoutine: string, ignoreNameCase = false): SchemaDiffTableMappingUpdate & { routineMappings: SchemaDiffRoutineMapping[] } {
|
||||
const update = updateSchemaDiffTableMapping(toTableMappings(mappings), sourceRoutine, targetRoutine, ignoreNameCase);
|
||||
return {
|
||||
...update,
|
||||
routineMappings: fromTableMappings(update.mappings),
|
||||
};
|
||||
}
|
||||
|
||||
export function availableSchemaDiffTargetRoutines(sourceRoutine: string, targetRoutines: readonly string[], mappings: readonly SchemaDiffRoutineMapping[], ignoreNameCase = false): string[] {
|
||||
return availableSchemaDiffTargetTables(sourceRoutine, targetRoutines, toTableMappings(mappings), ignoreNameCase);
|
||||
}
|
||||
|
||||
export function swapSchemaDiffRoutineMappings(mappings: readonly SchemaDiffRoutineMapping[]): SchemaDiffRoutineMapping[] {
|
||||
return fromTableMappings(swapSchemaDiffTableMappings(toTableMappings(mappings)));
|
||||
}
|
||||
|
||||
export function areSchemaDiffRoutineMappingsEqual(left: readonly SchemaDiffRoutineMapping[], right: readonly SchemaDiffRoutineMapping[]): boolean {
|
||||
return areSchemaDiffTableMappingsEqual(toTableMappings(left), toTableMappings(right));
|
||||
}
|
||||
|
||||
export function reconcileSchemaDiffSelectedRoutines(selectedRoutines: string[], availableRoutines: string[]): string[] {
|
||||
const available = new Set(availableRoutines);
|
||||
return selectedRoutines.filter((routine) => available.has(routine));
|
||||
}
|
||||
|
||||
/** Same-name (identity) mappings only — rename rematch is not wired through prepareSchemaDiff yet. */
|
||||
export function isSchemaDiffRoutineIdentityMapping(mapping: SchemaDiffRoutineMapping, ignoreNameCase = false): boolean {
|
||||
if (ignoreNameCase) {
|
||||
return mapping.sourceRoutine.toLocaleLowerCase() === mapping.targetRoutine.toLocaleLowerCase();
|
||||
}
|
||||
return mapping.sourceRoutine === mapping.targetRoutine;
|
||||
}
|
||||
|
||||
export function identitySchemaDiffRoutineMappings(mappings: readonly SchemaDiffRoutineMapping[], ignoreNameCase = false): SchemaDiffRoutineMapping[] {
|
||||
return mappings.filter((mapping) => isSchemaDiffRoutineIdentityMapping(mapping, ignoreNameCase));
|
||||
}
|
||||
|
||||
export interface FilteredSchemaDiffFunctions {
|
||||
sourceFunctions: FunctionInfo[];
|
||||
targetFunctions: FunctionInfo[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply visual routine selection + same-name mappings before prepareSchemaDiff.
|
||||
* When `selectedRoutines` is undefined, both sides keep all listed functions.
|
||||
* Non-identity (rename) mappings are ignored until backend rematch lands.
|
||||
*/
|
||||
export function filterSchemaDiffFunctions(sourceFunctions: FunctionInfo[], targetFunctions: FunctionInfo[], selectedRoutines: string[] | undefined, routineMappings: SchemaDiffRoutineMapping[] = []): FilteredSchemaDiffFunctions {
|
||||
if (selectedRoutines === undefined) {
|
||||
return { sourceFunctions, targetFunctions };
|
||||
}
|
||||
|
||||
const selectedSet = new Set(selectedRoutines);
|
||||
const filteredSource = sourceFunctions.filter((fn) => selectedSet.has(schemaDiffRoutineKeyFromFunction(fn)));
|
||||
const targetByKey = new Map(targetFunctions.map((fn) => [schemaDiffRoutineKeyFromFunction(fn), fn]));
|
||||
const targetKeys = [...targetByKey.keys()];
|
||||
const mappings = reconcileSchemaDiffRoutineMappings(
|
||||
filteredSource.map((fn) => schemaDiffRoutineKeyFromFunction(fn)),
|
||||
targetKeys,
|
||||
identitySchemaDiffRoutineMappings(routineMappings),
|
||||
);
|
||||
const selectedTargetKeys = new Set(mappings.map((mapping) => mapping.targetRoutine));
|
||||
|
||||
return {
|
||||
sourceFunctions: filteredSource,
|
||||
targetFunctions: targetFunctions.filter((fn) => selectedTargetKeys.has(schemaDiffRoutineKeyFromFunction(fn))),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user