From 2a6b3c6f5ca57e4dd3eac11b0b3602983d431a76 Mon Sep 17 00:00:00 2001 From: Yash Date: Sat, 28 Nov 2026 19:24:19 +0530 Subject: [PATCH 01/14] feat(bridge): implement canonical schema AST, normalizer, and deterministic diff engine (M1) --- bridge/__tests__/gitServiceRef.test.ts | 79 ++ bridge/__tests__/schemaDiffEngine.test.ts | 307 +++++++ .../schemaSnapshotNormalizer.test.ts | 264 ++++++ bridge/src/handlers/migrationHandlers.ts | 132 +++ bridge/src/handlers/projectHandlers.ts | 55 +- bridge/src/jsonRpcHandler.ts | 1 + bridge/src/services/gitService.ts | 41 +- bridge/src/services/liveSchemaIntrospector.ts | 70 ++ bridge/src/services/schemaDiffEngine.ts | 823 ++++++++++++++++++ .../src/services/schemaSnapshotNormalizer.ts | 484 ++++++++++ bridge/src/types/index.ts | 1 + bridge/src/types/schemaDiff.ts | 160 ++++ 12 files changed, 2413 insertions(+), 4 deletions(-) create mode 100644 bridge/__tests__/gitServiceRef.test.ts create mode 100644 bridge/__tests__/schemaDiffEngine.test.ts create mode 100644 bridge/__tests__/schemaSnapshotNormalizer.test.ts create mode 100644 bridge/src/services/liveSchemaIntrospector.ts create mode 100644 bridge/src/services/schemaDiffEngine.ts create mode 100644 bridge/src/services/schemaSnapshotNormalizer.ts create mode 100644 bridge/src/types/schemaDiff.ts diff --git a/bridge/__tests__/gitServiceRef.test.ts b/bridge/__tests__/gitServiceRef.test.ts new file mode 100644 index 00000000..682feff7 --- /dev/null +++ b/bridge/__tests__/gitServiceRef.test.ts @@ -0,0 +1,79 @@ +import { afterAll, beforeAll, describe, expect, test } from "@jest/globals"; +import { GitService } from "../src/services/gitService"; +import fs from "fs/promises"; +import fsSync from "fs"; +import path from "path"; +import os from "os"; +import { execFile } from "child_process"; +import { promisify } from "util"; + +const execFileAsync = promisify(execFile); + +const TEST_ROOT = path.join(os.tmpdir(), "git-service-ref-test-" + Date.now()); +let repoDir: string; +let git: GitService; + +async function rawGit(cwd: string, ...args: string[]): Promise { + const { stdout } = await execFileAsync("git", args, { cwd, windowsHide: true }); + return stdout.trimEnd(); +} + +describe("GitService.getFileAtRef", () => { + beforeAll(async () => { + git = new GitService(); + repoDir = path.join(TEST_ROOT, "repo"); + await fs.mkdir(path.join(repoDir, "schema"), { recursive: true }); + await rawGit(repoDir, "init", "-b", "main"); + await rawGit(repoDir, "config", "user.email", "test@relwave.dev"); + await rawGit(repoDir, "config", "user.name", "Test User"); + + await fs.writeFile( + path.join(repoDir, "schema", "schema.json"), + JSON.stringify({ version: 2, rev: 1 }), + "utf-8", + ); + await rawGit(repoDir, "add", "schema/schema.json"); + await rawGit(repoDir, "commit", "-m", "v1"); + + await fs.writeFile( + path.join(repoDir, "schema", "schema.json"), + JSON.stringify({ version: 2, rev: 2 }), + "utf-8", + ); + await rawGit(repoDir, "add", "schema/schema.json"); + await rawGit(repoDir, "commit", "-m", "v2"); + }); + + afterAll(async () => { + if (fsSync.existsSync(TEST_ROOT)) { + await fs.rm(TEST_ROOT, { recursive: true, force: true }); + } + }); + + test("reads file contents at HEAD and HEAD~1", async () => { + const headContent = await git.getFileAtRef(repoDir, "schema/schema.json", "HEAD"); + expect(headContent).not.toBeNull(); + expect(JSON.parse(headContent!).rev).toBe(2); + + const prevContent = await git.getFileAtRef(repoDir, "schema\\schema.json", "HEAD~1"); + expect(prevContent).not.toBeNull(); + expect(JSON.parse(prevContent!).rev).toBe(1); + }); + + test("returns null when file or ref does not exist", async () => { + expect(await git.getFileAtRef(repoDir, "schema/missing.json", "HEAD")).toBeNull(); + expect(await git.getFileAtRef(repoDir, "schema/schema.json", "nonexistent-branch")).toBeNull(); + }); + + test("rejects unsafe refs and paths", async () => { + await expect(git.getFileAtRef(repoDir, "schema/schema.json", "-evil")).rejects.toThrow(); + await expect(git.getFileAtRef(repoDir, "schema/schema.json", "HEAD main")).rejects.toThrow(); + await expect(git.getFileAtRef(repoDir, "schema/schema.json", "HEAD..main")).rejects.toThrow(); + await expect(git.getFileAtRef(repoDir, "schema/schema.json", "HEAD\n")).rejects.toThrow(); + + await expect(git.getFileAtRef(repoDir, "../secret.txt", "HEAD")).rejects.toThrow(); + await expect(git.getFileAtRef(repoDir, "/etc/passwd", "HEAD")).rejects.toThrow(); + await expect(git.getFileAtRef(repoDir, "C:\\Windows\\win.ini", "HEAD")).rejects.toThrow(); + await expect(git.getFileAtRef(repoDir, "schema/a\0b.json", "HEAD")).rejects.toThrow(); + }); +}); diff --git a/bridge/__tests__/schemaDiffEngine.test.ts b/bridge/__tests__/schemaDiffEngine.test.ts new file mode 100644 index 00000000..b1ece479 --- /dev/null +++ b/bridge/__tests__/schemaDiffEngine.test.ts @@ -0,0 +1,307 @@ +import { describe, expect, test } from "@jest/globals"; +import { diffSchemas } from "../src/services/schemaDiffEngine"; +import type { CanonicalSchemaAST } from "../src/types/schemaDiff"; + +function makePgAst(tables: CanonicalSchemaAST["schemas"][0]["tables"]): CanonicalSchemaAST { + return { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables, + enums: [], + views: [], + }, + ], + }; +} + +describe("schemaDiffEngine", () => { + test("returns hasChanges=false for identical schemas", () => { + const ast = makePgAst([ + { + name: "users", + type: "BASE TABLE", + columns: [ + { + name: "id", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: true, + ordinalPosition: 1, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ]); + + const res = diffSchemas(ast, ast, { sourceLabel: "snap", targetLabel: "live" }); + expect(res.hasChanges).toBe(false); + expect(res.summary).toEqual({ total: 0, safe: 0, warning: 0, destructive: 0 }); + expect(res.items).toEqual([]); + }); + + test("classifies additions, warnings, and destructive changes accurately", () => { + const source = makePgAst([ + { + name: "users", + type: "BASE TABLE", + columns: [ + { + name: "id", + type: "bigint", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + { + name: "bio", + type: "text", + nullable: true, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 2, + }, + { + name: "legacy", + type: "integer", + nullable: true, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 3, + }, + ], + indexes: [{ name: "idx_bio", columns: ["bio"], unique: false }], + foreignKeys: [], + checks: [], + }, + ]); + + const target = makePgAst([ + { + name: "users", + type: "BASE TABLE", + columns: [ + { + name: "id", + type: "integer", // narrowed bigint -> integer => destructive + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + { + name: "bio", + type: "text", + nullable: false, // nullable -> NOT NULL without default => destructive + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 2, + }, + { + name: "created_at", + type: "timestamp with time zone", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: "now()", + isUnique: false, + isSerial: false, + ordinalPosition: 3, + }, + ], + indexes: [], // idx_bio dropped => warning + foreignKeys: [], + checks: [], + }, + ]); + + const res = diffSchemas(source, target); + expect(res.hasChanges).toBe(true); + expect(res.summary).toEqual({ total: 5, safe: 1, warning: 1, destructive: 3 }); + + const byType = new Map(res.items.map((i) => [`${i.type}:${i.objectName || ""}`, i])); + expect(byType.get("COLUMN_MODIFIED:id")?.severity).toBe("destructive"); + expect(byType.get("COLUMN_MODIFIED:bio")?.severity).toBe("destructive"); + expect(byType.get("COLUMN_DROPPED:legacy")?.severity).toBe("destructive"); + expect(byType.get("COLUMN_ADDED:created_at")?.severity).toBe("safe"); + expect(byType.get("INDEX_DROPPED:idx_bio")?.severity).toBe("warning"); + }); + + test("detects table and column rename candidates", () => { + const source = makePgAst([ + { + name: "old_users", + type: "BASE TABLE", + columns: [ + { + name: "id", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: true, + ordinalPosition: 1, + }, + { + name: "full_name", + type: "varchar(100)", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 2, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + { + name: "items", + type: "BASE TABLE", + columns: [ + { + name: "title", + type: "varchar(200)", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ]); + + const target = makePgAst([ + { + name: "users", + type: "BASE TABLE", + columns: source.schemas[0].tables[0].columns, + indexes: [], + foreignKeys: [], + checks: [], + }, + { + name: "items", + type: "BASE TABLE", + columns: [ + { + name: "label", + type: "varchar(200)", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ]); + + const res = diffSchemas(source, target); + const droppedTable = res.items.find((i) => i.type === "TABLE_DROPPED"); + const addedTable = res.items.find((i) => i.type === "TABLE_ADDED"); + expect(droppedTable?.renameCandidate).toBe("users"); + expect(addedTable?.renameCandidate).toBe("old_users"); + + const droppedCol = res.items.find((i) => i.type === "COLUMN_DROPPED"); + const addedCol = res.items.find((i) => i.type === "COLUMN_ADDED"); + expect(droppedCol?.renameCandidate).toBe("label"); + expect(addedCol?.renameCandidate).toBe("title"); + }); + + test("diffs MongoDB collections, indexes, and validators", () => { + const source: CanonicalSchemaAST = { + dialect: "mongodb", + schemas: [], + collections: [ + { + name: "orders", + type: "collection", + indexes: [ + { name: "_id_", key: { _id: 1 }, unique: false, sparse: false }, + { name: "user_1", key: { userId: 1 }, unique: false, sparse: false }, + ], + validator: { $jsonSchema: { bsonType: "object" } }, + }, + { + name: "temp_logs", + type: "collection", + indexes: [{ name: "_id_", key: { _id: 1 }, unique: false, sparse: false }], + validator: null, + }, + ], + }; + + const target: CanonicalSchemaAST = { + dialect: "mongodb", + schemas: [], + collections: [ + { + name: "orders", + type: "collection", + indexes: [ + { name: "_id_", key: { _id: 1 }, unique: false, sparse: false }, + { name: "user_1", key: { userId: 1 }, unique: true, sparse: false }, + { name: "status_1", key: { status: 1 }, unique: false, sparse: true }, + ], + validator: { $jsonSchema: { bsonType: "object", required: ["userId"] } }, + }, + { + name: "invoices", + type: "collection", + indexes: [{ name: "_id_", key: { _id: 1 }, unique: false, sparse: false }], + validator: null, + }, + ], + }; + + const res = diffSchemas(source, target); + expect(res.hasChanges).toBe(true); + expect(res.items.map((i) => i.type).sort()).toEqual([ + "COLLECTION_ADDED", + "COLLECTION_DROPPED", + "MONGO_INDEX_ADDED", + "MONGO_INDEX_MODIFIED", + "VALIDATOR_MODIFIED", + ]); + }); +}); diff --git a/bridge/__tests__/schemaSnapshotNormalizer.test.ts b/bridge/__tests__/schemaSnapshotNormalizer.test.ts new file mode 100644 index 00000000..d4e9bd38 --- /dev/null +++ b/bridge/__tests__/schemaSnapshotNormalizer.test.ts @@ -0,0 +1,264 @@ +import { describe, expect, test } from "@jest/globals"; +import { + canonicalizeType, + INTERNAL_MIGRATION_TABLES, + normalizeExpression, + normalizeLiveSqlSchemas, + normalizeMongoIntrospection, + normalizeSchemaFile, +} from "../src/services/schemaSnapshotNormalizer"; +import type { SchemaFile } from "../src/services/projectStore"; + +describe("schemaSnapshotNormalizer", () => { + test("canonicalizes PostgreSQL and MySQL type aliases", () => { + expect(canonicalizeType("int4", "postgresql")).toBe("integer"); + expect(canonicalizeType("INT8", "postgresql")).toBe("bigint"); + expect(canonicalizeType("bool", "postgresql")).toBe("boolean"); + expect(canonicalizeType("timestamptz", "postgresql")).toBe("timestamp with time zone"); + expect(canonicalizeType("character varying(120)", "postgresql")).toBe("varchar(120)"); + + expect(canonicalizeType("int(11)", "mysql")).toBe("int"); + expect(canonicalizeType("bigint(20) unsigned", "mysql")).toBe("bigint unsigned"); + expect(canonicalizeType("tinyint(4)", "mariadb")).toBe("tinyint"); + }); + + test("normalizes whitespace and identifier quoting in expressions", () => { + expect(normalizeExpression(' ( "age" > 0 ) ')).toBe("(age > 0)"); + expect(normalizeExpression("`status` IN ('active', 'pending')")).toBe( + "status IN ('active', 'pending')", + ); + expect(normalizeExpression(" ")).toBeNull(); + expect(normalizeExpression(null)).toBeNull(); + }); + + test("excludes all internal migration tables and sorts deterministically", () => { + const schemaFile: SchemaFile = { + version: 2, + projectId: "proj-1", + databaseId: "db-1", + dialect: "postgresql", + cachedAt: "2026-01-01T00:00:00Z", + relwaveVersion: "1.3.5", + schemaHash: "abc", + schemas: [ + { + name: "z_schema", + tables: [], + enums: [], + views: [], + }, + { + name: "public", + tables: [ + ...Array.from(INTERNAL_MIGRATION_TABLES).map((name) => ({ + name, + type: "BASE TABLE", + columns: [], + indexes: [], + foreignKeys: [], + checks: [], + })), + { + name: "users", + type: "BASE TABLE", + columns: [ + { + name: "email", + type: "character varying(255)", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: true, + isSerial: false, + ordinalPosition: 2, + }, + { + name: "id", + type: "int4", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: true, + ordinalPosition: 1, + }, + ], + indexes: [ + { name: "idx_z", columns: ["email"], unique: true }, + { name: "idx_a", columns: ["id"], unique: true }, + ], + foreignKeys: [], + checks: [], + }, + { + name: "accounts", + type: "BASE TABLE", + columns: [], + indexes: [], + foreignKeys: [], + checks: [], + }, + ], + enums: [ + { name: "role_enum", values: ["admin", "user"] }, + { name: "alert_enum", values: ["low", "high"] }, + ], + views: [ + { name: "v_users", definition: 'SELECT "id" FROM "users"' }, + { name: "v_accounts", definition: "SELECT 1" }, + ], + }, + ], + }; + + const ast = normalizeSchemaFile(schemaFile); + expect(ast.dialect).toBe("postgresql"); + expect(ast.schemas.map((s) => s.name)).toEqual(["public", "z_schema"]); + + const pub = ast.schemas[0]; + expect(pub.tables.map((t) => t.name)).toEqual(["accounts", "users"]); + expect(pub.enums.map((e) => e.name)).toEqual(["alert_enum", "role_enum"]); + expect(pub.views.map((v) => v.name)).toEqual(["v_accounts", "v_users"]); + expect(pub.views[1].definition).toBe("SELECT id FROM users"); + + const users = pub.tables[1]; + expect(users.columns.map((c) => c.name)).toEqual(["email", "id"]); + expect(users.columns[0].type).toBe("varchar(255)"); + expect(users.columns[1].type).toBe("integer"); + expect(users.indexes.map((i) => i.name)).toEqual(["idx_a", "idx_z"]); + }); + + test("normalizes live SQL introspection with flat index/FK rows", () => { + const live = { + schemas: [ + { + name: "public", + tables: [ + { + name: "orders", + type: "BASE TABLE", + columns: [ + { + name: "id", + type: "int8", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: true, + ordinalPosition: 1, + }, + { + name: "user_id", + type: "int8", + nullable: false, + isPrimaryKey: false, + isForeignKey: true, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 2, + }, + ], + indexes: [ + { + table_name: "orders", + index_name: "idx_orders_composite", + column_name: "id", + is_unique: false, + is_primary: false, + index_type: "BTREE", + ordinal_position: 2, + }, + { + table_name: "orders", + index_name: "idx_orders_composite", + column_name: "user_id", + is_unique: false, + is_primary: false, + index_type: "BTREE", + ordinal_position: 1, + }, + ], + foreignKeys: [ + { + constraint_name: "fk_orders_user", + source_schema: "public", + source_table: "orders", + source_column: "user_id", + target_schema: "public", + target_table: "users", + target_column: "id", + update_rule: "no action", + delete_rule: "cascade", + ordinal_position: 1, + }, + ], + checkConstraints: [ + { + constraint_name: "chk_positive", + definition: '( "id" > 0 )', + }, + ], + }, + { + name: "_relwave_migrations", + type: "BASE TABLE", + columns: [], + indexes: [], + foreignKeys: [], + checkConstraints: [], + }, + ], + enumTypes: [{ enum_name: "status", enum_value: "open" }], + }, + ], + }; + + const ast = normalizeLiveSqlSchemas(live, "postgres"); + expect(ast.dialect).toBe("postgresql"); + const orders = ast.schemas[0].tables[0]; + expect(ast.schemas[0].tables).toHaveLength(1); + expect(orders.indexes[0].columns).toEqual(["user_id", "id"]); + expect(orders.foreignKeys[0]).toEqual({ + name: "fk_orders_user", + columns: ["user_id"], + referencedSchema: "public", + referencedTable: "users", + referencedColumns: ["id"], + onDelete: "CASCADE", + onUpdate: "NO ACTION", + }); + expect(orders.checks[0]).toEqual({ + name: "chk_positive", + expression: "(id > 0)", + }); + expect(ast.schemas[0].enums[0]).toEqual({ + name: "status", + values: ["open"], + }); + }); + + test("normalizes MongoDB introspection and filters system/internal collections", () => { + const ast = normalizeMongoIntrospection([ + { + name: "users", + type: "collection", + indexes: [ + { name: "email_1", key: { email: 1 }, unique: true }, + { name: "_id_", key: { _id: 1 }, unique: false }, + ], + validator: { $jsonSchema: { bsonType: "object" } }, + }, + { name: "system.views", type: "view" }, + { name: "_relwave_migrations", type: "collection" }, + ]); + + expect(ast.dialect).toBe("mongodb"); + expect(ast.collections).toHaveLength(1); + expect(ast.collections![0].indexes.map((i) => i.name)).toEqual(["_id_", "email_1"]); + }); +}); diff --git a/bridge/src/handlers/migrationHandlers.ts b/bridge/src/handlers/migrationHandlers.ts index ba04cc0a..152427f2 100644 --- a/bridge/src/handlers/migrationHandlers.ts +++ b/bridge/src/handlers/migrationHandlers.ts @@ -8,6 +8,10 @@ import fs from "fs"; import { projectStoreInstance } from "../services/projectStore"; import { mongoMigrationEngine } from "../services/mongoMigrationEngine"; import { selectDb, MongoApiError } from "../connectors/mongo"; +import { gitServiceInstance } from "../services/gitService"; +import { normalizeSchemaFile } from "../services/schemaSnapshotNormalizer"; +import { diffSchemas } from "../services/schemaDiffEngine"; +import { introspectLiveCanonicalAST } from "../services/liveSchemaIntrospector"; export class MigrationHandlers { constructor( @@ -829,4 +833,132 @@ export class MigrationHandlers { this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); } } + + /** + * Compare two schema sources (live-vs-snapshot, live-vs-ref, ref-vs-ref) + * and return a structured SchemaDiffResult. + */ + async handleDiffSchema(params: any, id: number | string) { + try { + const { projectId, mode = "live-vs-snapshot", sourceRef, targetRef } = params || {}; + if (!projectId) { + return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing projectId" }); + } + + const project = await projectStoreInstance.getProject(projectId); + if (!project) { + return this.rpc.sendError(id, { code: "NOT_FOUND", message: "Project not found" }); + } + + const schemaRelPath = "schema/schema.json"; + + if (mode === "live-vs-snapshot") { + if (!project.databaseId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Project has no database ID", + }); + } + const savedSchema = await projectStoreInstance.getSchema(projectId); + if (!savedSchema) { + return this.rpc.sendError(id, { + code: "NOT_FOUND", + message: "No saved schema snapshot found for project", + }); + } + + const snapshotAST = normalizeSchemaFile(savedSchema); + const liveAST = await introspectLiveCanonicalAST( + this.dbService, + this.queryExecutor, + project.databaseId, + ); + const result = diffSchemas(snapshotAST, liveAST, { + sourceLabel: "snapshot", + targetLabel: "live", + }); + return this.rpc.sendResponse(id, { ok: true, data: result }); + } + + if (mode === "live-vs-ref") { + if (!project.databaseId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Project has no database ID", + }); + } + if (!targetRef) { + return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing targetRef" }); + } + + const projectDir = await projectStoreInstance.resolveProjectDir(projectId); + const rawRefJson = await gitServiceInstance.getFileAtRef( + projectDir, + schemaRelPath, + targetRef, + ); + if (rawRefJson === null) { + return this.rpc.sendError(id, { + code: "NOT_FOUND", + message: `Schema snapshot not found at ref ${targetRef}`, + }); + } + + const refAST = normalizeSchemaFile(JSON.parse(rawRefJson)); + const liveAST = await introspectLiveCanonicalAST( + this.dbService, + this.queryExecutor, + project.databaseId, + ); + const result = diffSchemas(liveAST, refAST, { + sourceLabel: "live", + targetLabel: targetRef, + }); + return this.rpc.sendResponse(id, { ok: true, data: result }); + } + + if (mode === "ref-vs-ref") { + if (!sourceRef || !targetRef) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing sourceRef or targetRef", + }); + } + + const projectDir = await projectStoreInstance.resolveProjectDir(projectId); + const [rawSourceJson, rawTargetJson] = await Promise.all([ + gitServiceInstance.getFileAtRef(projectDir, schemaRelPath, sourceRef), + gitServiceInstance.getFileAtRef(projectDir, schemaRelPath, targetRef), + ]); + + if (rawSourceJson === null) { + return this.rpc.sendError(id, { + code: "NOT_FOUND", + message: `Schema snapshot not found at ref ${sourceRef}`, + }); + } + if (rawTargetJson === null) { + return this.rpc.sendError(id, { + code: "NOT_FOUND", + message: `Schema snapshot not found at ref ${targetRef}`, + }); + } + + const sourceAST = normalizeSchemaFile(JSON.parse(rawSourceJson)); + const targetAST = normalizeSchemaFile(JSON.parse(rawTargetJson)); + const result = diffSchemas(sourceAST, targetAST, { + sourceLabel: sourceRef, + targetLabel: targetRef, + }); + return this.rpc.sendResponse(id, { ok: true, data: result }); + } + + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: `Unsupported diff mode: ${mode}`, + }); + } catch (e: any) { + this.sendMigrationError(id, e, "migration.diffSchema failed"); + } + } } diff --git a/bridge/src/handlers/projectHandlers.ts b/bridge/src/handlers/projectHandlers.ts index 91a7ce80..dd5433e5 100644 --- a/bridge/src/handlers/projectHandlers.ts +++ b/bridge/src/handlers/projectHandlers.ts @@ -5,6 +5,9 @@ import { DatabaseService } from "../services/databaseService"; import { QueryExecutor } from "../services/queryExecutor"; import { gitServiceInstance } from "../services/gitService"; import { getConnector } from "../services/connectorRegistry"; +import { normalizeSchemaFile } from "../services/schemaSnapshotNormalizer"; +import { diffSchemas } from "../services/schemaDiffEngine"; +import { introspectLiveCanonicalAST } from "../services/liveSchemaIntrospector"; import path from "path"; /** @@ -579,8 +582,56 @@ export class ProjectHandlers { if (!projectId) return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing projectId" }); - // Stub implementation for now - this.rpc.sendResponse(id, { ok: true, data: { driftDetected: false, differences: [] } }); + const project = await projectStoreInstance.getProject(projectId); + if (!project) { + return this.rpc.sendError(id, { code: "NOT_FOUND", message: "Project not found" }); + } + + const savedSchema = await projectStoreInstance.getSchema(projectId); + if ( + !savedSchema || + (!savedSchema.schemaHash && + (!savedSchema.schemas || savedSchema.schemas.length === 0) && + !(savedSchema as any).collections?.length) + ) { + return this.rpc.sendResponse(id, { + ok: true, + data: { + driftDetected: false, + differences: [], + summary: { total: 0, safe: 0, warning: 0, destructive: 0 }, + }, + }); + } + + if (!project.databaseId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Project has no database ID", + }); + } + + const snapshotAST = normalizeSchemaFile(savedSchema); + const liveAST = await introspectLiveCanonicalAST( + this.dbService, + this.queryExecutor, + project.databaseId, + ); + const result = diffSchemas(snapshotAST, liveAST, { + sourceLabel: "snapshot", + targetLabel: "live", + }); + + this.rpc.sendResponse(id, { + ok: true, + data: { + driftDetected: result.hasChanges, + differences: result.items, + summary: result.summary, + sourceLabel: result.sourceLabel, + targetLabel: result.targetLabel, + }, + }); } catch (e: any) { this.logger?.error({ e }, "project.getDrift failed"); this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); diff --git a/bridge/src/jsonRpcHandler.ts b/bridge/src/jsonRpcHandler.ts index 468de2dc..bb821d7d 100644 --- a/bridge/src/jsonRpcHandler.ts +++ b/bridge/src/jsonRpcHandler.ts @@ -198,6 +198,7 @@ export function registerDbHandlers(rpc: Rpc, logger: Logger, sessions: SessionMa ); rpcRegister(rpc, "migration.delete", (p, id) => migrationHandlers.handleDeleteMigration(p, id)); rpcRegister(rpc, "migration.getSQL", (p, id) => migrationHandlers.handleGetMigrationSQL(p, id)); + rpcRegister(rpc, "migration.diffSchema", (p, id) => migrationHandlers.handleDiffSchema(p, id)); // ========================================== // STATISTICS HANDLERS diff --git a/bridge/src/services/gitService.ts b/bridge/src/services/gitService.ts index 715d4397..6a5c96fb 100644 --- a/bridge/src/services/gitService.ts +++ b/bridge/src/services/gitService.ts @@ -517,11 +517,48 @@ export class GitService { /** * Read a file's content at a given git ref (HEAD, branch, commit hash). * Returns null if the file doesn't exist at that ref. + * Validates ref and relative filePath against unsafe characters or path traversal. */ async getFileAtRef(dir: string, filePath: string, ref = "HEAD"): Promise { + const hasControlChars = (value: string): boolean => { + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i); + if (code <= 0x1f || code === 0x7f) return true; + } + return false; + }; + + if (!ref || typeof ref !== "string") { + throw new GitError("INVALID_REF", "Git ref must be a non-empty string"); + } + if (ref.startsWith("-") || /\s/.test(ref) || ref.includes("..") || hasControlChars(ref)) { + throw new GitError("INVALID_REF", `Unsafe or invalid git ref: ${ref}`); + } + + if (!filePath || typeof filePath !== "string") { + throw new GitError("INVALID_PATH", "Relative path must be a non-empty string"); + } + if ( + hasControlChars(filePath) || + path.isAbsolute(filePath) || + filePath.startsWith("/") || + filePath.startsWith("\\") || + /^[a-zA-Z]:/.test(filePath) + ) { + throw new GitError("INVALID_PATH", `Unsafe or non-relative path: ${filePath}`); + } + + const posixPath = filePath.replace(/\\/g, "/").replace(/^\.\//, ""); + if (!posixPath || posixPath.split("/").includes("..")) { + throw new GitError("INVALID_PATH", `Path traversal is not allowed: ${filePath}`); + } + try { - return await this.git(dir, "show", `${ref}:${filePath}`); - } catch { + return await this.git(dir, "show", `${ref}:${posixPath}`); + } catch (err: any) { + if (err?.message === "Git is not installed or not on PATH") { + throw err; + } return null; // file doesn't exist at this ref } } diff --git a/bridge/src/services/liveSchemaIntrospector.ts b/bridge/src/services/liveSchemaIntrospector.ts new file mode 100644 index 00000000..87bc14ce --- /dev/null +++ b/bridge/src/services/liveSchemaIntrospector.ts @@ -0,0 +1,70 @@ +/** + * Live Schema Introspector + * + * Shared helper that introspects a live SQL or MongoDB connection + * and normalizes it into a CanonicalSchemaAST. + */ + +import { DBType } from "../types"; +import type { CanonicalSchemaAST } from "../types/schemaDiff"; +import type { DatabaseService } from "./databaseService"; +import type { QueryExecutor } from "./queryExecutor"; +import { mongoConnector, selectDb } from "../connectors/mongo"; +import { + normalizeLiveSqlSchemas, + normalizeMongoIntrospection, + type MongoIntrospectionInput, +} from "./schemaSnapshotNormalizer"; + +/** + * Introspect a live database connection and return its CanonicalSchemaAST. + */ +export async function introspectLiveCanonicalAST( + dbService: DatabaseService, + queryExecutor: QueryExecutor, + databaseId: string, +): Promise { + const { conn, dbType } = await dbService.getDatabaseConnection(databaseId); + + if (dbType === DBType.MONGODB) { + const db = selectDb(conn as any); + const rawInfos = await db.listCollections({}, { nameOnly: false }).toArray(); + const collections: MongoIntrospectionInput[] = []; + + for (const info of rawInfos) { + const name = info.name; + if (!name || name.startsWith("system.")) continue; + const type = info.type === "view" ? "view" : "collection"; + let indexes: MongoIntrospectionInput["indexes"] = []; + if (type === "collection") { + try { + const idxRes = await mongoConnector.listIndexes(conn as any, { collection: name }); + indexes = idxRes.indexes.map((idx) => ({ + name: idx.name, + key: idx.key, + unique: idx.unique, + sparse: idx.sparse, + expireAfterSeconds: idx.expireAfterSeconds, + partialFilterExpression: idx.partialFilterExpression ?? null, + })); + } catch { + indexes = []; + } + } + const opts = (info as any).options || {}; + collections.push({ + name, + type, + indexes, + validator: opts.validator ?? null, + validationLevel: opts.validationLevel ?? null, + validationAction: opts.validationAction ?? null, + }); + } + + return normalizeMongoIntrospection(collections); + } + + const dbSchema = (await queryExecutor.listSchemas(conn, dbType)) as any; + return normalizeLiveSqlSchemas(dbSchema, dbType); +} diff --git a/bridge/src/services/schemaDiffEngine.ts b/bridge/src/services/schemaDiffEngine.ts new file mode 100644 index 00000000..faf49064 --- /dev/null +++ b/bridge/src/services/schemaDiffEngine.ts @@ -0,0 +1,823 @@ +/** + * Schema Diff Engine + * + * Pure AST comparison engine that diffs two CanonicalSchemaAST trees + * (SQL or MongoDB) and produces classified, deterministic SchemaDiffResult items. + */ + +import type { + CanonicalCollection, + CanonicalColumn, + CanonicalSchemaAST, + CanonicalTable, + DiffSeverity, + SchemaDiffItem, + SchemaDiffResult, + SchemaDiffSummary, +} from "../types/schemaDiff"; + +export interface DiffSchemasOptions { + sourceLabel?: string; + targetLabel?: string; + detectRenames?: boolean; +} + +/** Deterministic JSON serialization with sorted object keys. */ +function stableStringify(value: unknown): string { + if (value === null || value === undefined) return String(value); + if (typeof value !== "object") return JSON.stringify(value); + if (Array.isArray(value)) { + return `[${value.map((v) => stableStringify(v)).join(",")}]`; + } + const obj = value as Record; + const keys = Object.keys(obj).sort(); + return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(",")}}`; +} + +function deepEqual(a: unknown, b: unknown): boolean { + return stableStringify(a) === stableStringify(b); +} + +const INT_RANKS: Record = { + tinyint: 1, + smallint: 2, + mediumint: 3, + int: 4, + integer: 4, + bigint: 5, +}; + +const FLOAT_RANKS: Record = { + real: 1, + float: 1, + double: 2, + "double precision": 2, +}; + +function parseSizedType(typeStr: string): { base: string; params: number[] } | null { + const match = typeStr.match(/^([a-z\s]+)\((\d+(?:\s*,\s*\d+)*)\)$/); + if (!match) return null; + const base = match[1].trim(); + const params = match[2].split(",").map((p) => parseInt(p.trim(), 10)); + return { base, params }; +} + +/** + * Determine whether changing a column type from `fromType` to `toType` + * narrows its value range or length (potentially truncating data). + */ +export function isTypeNarrowing(fromType: string, toType: string): boolean { + const from = fromType.trim().toLowerCase(); + const to = toType.trim().toLowerCase(); + if (from === to) return false; + + if (INT_RANKS[from] !== undefined && INT_RANKS[to] !== undefined) { + return INT_RANKS[to] < INT_RANKS[from]; + } + + if (FLOAT_RANKS[from] !== undefined && FLOAT_RANKS[to] !== undefined) { + return FLOAT_RANKS[to] < FLOAT_RANKS[from]; + } + + // Unbounded text -> bounded varchar/char + if (from === "text" && /^(varchar|char)\(\d+\)$/.test(to)) { + return true; + } + + const parsedFrom = parseSizedType(from); + const parsedTo = parseSizedType(to); + if (parsedFrom && parsedTo && parsedFrom.base === parsedTo.base) { + if (parsedFrom.params.length === 1 && parsedTo.params.length === 1) { + return parsedTo.params[0] < parsedFrom.params[0]; + } + if (parsedFrom.params.length >= 2 && parsedTo.params.length >= 2) { + return parsedTo.params[0] < parsedFrom.params[0] || parsedTo.params[1] < parsedFrom.params[1]; + } + } + + return false; +} + +function classifyColumnModification(before: CanonicalColumn, after: CanonicalColumn): DiffSeverity { + if (isTypeNarrowing(before.type, after.type)) { + return "destructive"; + } + // Making a nullable column NOT NULL without a default value can fail on existing NULL rows + if (before.nullable && !after.nullable && !after.defaultValue) { + return "destructive"; + } + return "warning"; +} + +function describeColumnChanges(before: CanonicalColumn, after: CanonicalColumn): string { + const changes: string[] = []; + if (before.type !== after.type) changes.push(`type ${before.type} -> ${after.type}`); + if (before.nullable !== after.nullable) { + changes.push(after.nullable ? "NULLABLE" : "NOT NULL"); + } + if (before.defaultValue !== after.defaultValue) { + changes.push(`default ${before.defaultValue ?? "none"} -> ${after.defaultValue ?? "none"}`); + } + if (before.isPrimaryKey !== after.isPrimaryKey) { + changes.push(after.isPrimaryKey ? "added PK" : "removed PK"); + } + if (before.isUnique !== after.isUnique) { + changes.push(after.isUnique ? "added UNIQUE" : "removed UNIQUE"); + } + if ((before.comment ?? null) !== (after.comment ?? null)) { + changes.push("comment changed"); + } + return changes.join(", "); +} + +function buildItemId( + type: SchemaDiffItem["type"], + schema: string | undefined, + tableOrCollection: string, + objectName?: string, +): string { + return [type, schema || "", tableOrCollection, objectName || ""].join(":"); +} + +function tableSignature(table: CanonicalTable): Set { + return new Set(table.columns.map((c) => `${c.name}:${c.type}`)); +} + +function jaccardSimilarity(a: Set, b: Set): number { + if (a.size === 0 && b.size === 0) return 1; + if (a.size === 0 || b.size === 0) return 0; + let intersection = 0; + for (const item of a) { + if (b.has(item)) intersection++; + } + const union = a.size + b.size - intersection; + return union === 0 ? 0 : intersection / union; +} + +function detectTableRenames( + items: SchemaDiffItem[], + sourceTablesBySchema: Map>, + targetTablesBySchema: Map>, +): void { + const dropped = items.filter((i) => i.type === "TABLE_DROPPED"); + const added = items.filter((i) => i.type === "TABLE_ADDED"); + const matchedAdded = new Set(); + + for (const dropItem of dropped) { + const schema = dropItem.schema || ""; + const srcTable = sourceTablesBySchema.get(schema)?.get(dropItem.tableOrCollection); + if (!srcTable || srcTable.columns.length === 0) continue; + + const srcSig = tableSignature(srcTable); + let bestMatch: SchemaDiffItem | null = null; + let bestScore = 0; + + for (const addItem of added) { + if ((addItem.schema || "") !== schema) continue; + if (matchedAdded.has(addItem.id)) continue; + + const tgtTable = targetTablesBySchema.get(schema)?.get(addItem.tableOrCollection); + if (!tgtTable || tgtTable.columns.length === 0) continue; + + const score = jaccardSimilarity(srcSig, tableSignature(tgtTable)); + if (score >= 0.6 && score > bestScore) { + bestScore = score; + bestMatch = addItem; + } + } + + if (bestMatch) { + matchedAdded.add(bestMatch.id); + dropItem.renameCandidate = bestMatch.tableOrCollection; + bestMatch.renameCandidate = dropItem.tableOrCollection; + } + } +} + +function detectColumnRenames(items: SchemaDiffItem[]): void { + const dropped = items.filter((i) => i.type === "COLUMN_DROPPED"); + const added = items.filter((i) => i.type === "COLUMN_ADDED"); + const matchedAdded = new Set(); + + for (const dropItem of dropped) { + const beforeCol = dropItem.before as CanonicalColumn | undefined; + if (!beforeCol) continue; + + for (const addItem of added) { + if (matchedAdded.has(addItem.id)) continue; + if ( + (addItem.schema || "") !== (dropItem.schema || "") || + addItem.tableOrCollection !== dropItem.tableOrCollection + ) { + continue; + } + const afterCol = addItem.after as CanonicalColumn | undefined; + if (!afterCol) continue; + + if (beforeCol.type === afterCol.type && beforeCol.nullable === afterCol.nullable) { + matchedAdded.add(addItem.id); + dropItem.renameCandidate = afterCol.name; + addItem.renameCandidate = beforeCol.name; + break; + } + } + } +} + +function diffTableObjects( + schemaName: string, + srcTable: CanonicalTable, + tgtTable: CanonicalTable, + items: SchemaDiffItem[], +): void { + if ( + srcTable.type !== tgtTable.type || + (srcTable.comment ?? null) !== (tgtTable.comment ?? null) + ) { + items.push({ + id: buildItemId("TABLE_MODIFIED", schemaName, srcTable.name), + type: "TABLE_MODIFIED", + severity: "warning", + schema: schemaName, + tableOrCollection: srcTable.name, + before: { type: srcTable.type, comment: srcTable.comment ?? null }, + after: { type: tgtTable.type, comment: tgtTable.comment ?? null }, + details: `Table ${schemaName}.${srcTable.name} metadata modified`, + }); + } + + // Columns + const srcCols = new Map(srcTable.columns.map((c) => [c.name, c])); + const tgtCols = new Map(tgtTable.columns.map((c) => [c.name, c])); + + for (const [colName, srcCol] of srcCols) { + const tgtCol = tgtCols.get(colName); + if (!tgtCol) { + items.push({ + id: buildItemId("COLUMN_DROPPED", schemaName, srcTable.name, colName), + type: "COLUMN_DROPPED", + severity: "destructive", + schema: schemaName, + tableOrCollection: srcTable.name, + objectName: colName, + before: srcCol, + details: `Column ${colName} (${srcCol.type}) dropped from ${schemaName}.${srcTable.name}`, + }); + } else if (!deepEqual(srcCol, tgtCol)) { + // Ignore pure ordinalPosition shifts when everything semantic is identical + const semBefore = { ...srcCol, ordinalPosition: 0 }; + const semAfter = { ...tgtCol, ordinalPosition: 0 }; + if (!deepEqual(semBefore, semAfter)) { + items.push({ + id: buildItemId("COLUMN_MODIFIED", schemaName, srcTable.name, colName), + type: "COLUMN_MODIFIED", + severity: classifyColumnModification(srcCol, tgtCol), + schema: schemaName, + tableOrCollection: srcTable.name, + objectName: colName, + before: srcCol, + after: tgtCol, + details: `Column ${colName} modified: ${describeColumnChanges(srcCol, tgtCol)}`, + }); + } + } + } + + for (const [colName, tgtCol] of tgtCols) { + if (!srcCols.has(colName)) { + items.push({ + id: buildItemId("COLUMN_ADDED", schemaName, srcTable.name, colName), + type: "COLUMN_ADDED", + severity: "safe", + schema: schemaName, + tableOrCollection: srcTable.name, + objectName: colName, + after: tgtCol, + details: `Column ${colName} (${tgtCol.type}) added to ${schemaName}.${srcTable.name}`, + }); + } + } + + // Indexes + const srcIdx = new Map(srcTable.indexes.map((i) => [i.name, i])); + const tgtIdx = new Map(tgtTable.indexes.map((i) => [i.name, i])); + + for (const [idxName, before] of srcIdx) { + const after = tgtIdx.get(idxName); + if (!after) { + items.push({ + id: buildItemId("INDEX_DROPPED", schemaName, srcTable.name, idxName), + type: "INDEX_DROPPED", + severity: "warning", + schema: schemaName, + tableOrCollection: srcTable.name, + objectName: idxName, + before, + details: `Index ${idxName} dropped from ${schemaName}.${srcTable.name}`, + }); + } else if (!deepEqual(before, after)) { + items.push({ + id: buildItemId("INDEX_MODIFIED", schemaName, srcTable.name, idxName), + type: "INDEX_MODIFIED", + severity: "warning", + schema: schemaName, + tableOrCollection: srcTable.name, + objectName: idxName, + before, + after, + details: `Index ${idxName} modified on ${schemaName}.${srcTable.name}`, + }); + } + } + for (const [idxName, after] of tgtIdx) { + if (!srcIdx.has(idxName)) { + items.push({ + id: buildItemId("INDEX_ADDED", schemaName, srcTable.name, idxName), + type: "INDEX_ADDED", + severity: "safe", + schema: schemaName, + tableOrCollection: srcTable.name, + objectName: idxName, + after, + details: `Index ${idxName} added on ${schemaName}.${srcTable.name}`, + }); + } + } + + // Foreign keys + const srcFks = new Map(srcTable.foreignKeys.map((fk) => [fk.name, fk])); + const tgtFks = new Map(tgtTable.foreignKeys.map((fk) => [fk.name, fk])); + + for (const [fkName, before] of srcFks) { + const after = tgtFks.get(fkName); + if (!after) { + items.push({ + id: buildItemId("FK_DROPPED", schemaName, srcTable.name, fkName), + type: "FK_DROPPED", + severity: "warning", + schema: schemaName, + tableOrCollection: srcTable.name, + objectName: fkName, + before, + details: `Foreign key ${fkName} dropped from ${schemaName}.${srcTable.name}`, + }); + } else if (!deepEqual(before, after)) { + items.push({ + id: buildItemId("FK_MODIFIED", schemaName, srcTable.name, fkName), + type: "FK_MODIFIED", + severity: "warning", + schema: schemaName, + tableOrCollection: srcTable.name, + objectName: fkName, + before, + after, + details: `Foreign key ${fkName} modified on ${schemaName}.${srcTable.name}`, + }); + } + } + for (const [fkName, after] of tgtFks) { + if (!srcFks.has(fkName)) { + items.push({ + id: buildItemId("FK_ADDED", schemaName, srcTable.name, fkName), + type: "FK_ADDED", + severity: "safe", + schema: schemaName, + tableOrCollection: srcTable.name, + objectName: fkName, + after, + details: `Foreign key ${fkName} added on ${schemaName}.${srcTable.name}`, + }); + } + } + + // Check constraints + const srcChecks = new Map(srcTable.checks.map((c) => [c.name, c])); + const tgtChecks = new Map(tgtTable.checks.map((c) => [c.name, c])); + + for (const [chkName, before] of srcChecks) { + const after = tgtChecks.get(chkName); + if (!after) { + items.push({ + id: buildItemId("CHECK_DROPPED", schemaName, srcTable.name, chkName), + type: "CHECK_DROPPED", + severity: "warning", + schema: schemaName, + tableOrCollection: srcTable.name, + objectName: chkName, + before, + details: `Check constraint ${chkName} dropped from ${schemaName}.${srcTable.name}`, + }); + } else if (!deepEqual(before, after)) { + items.push({ + id: buildItemId("CHECK_MODIFIED", schemaName, srcTable.name, chkName), + type: "CHECK_MODIFIED", + severity: "warning", + schema: schemaName, + tableOrCollection: srcTable.name, + objectName: chkName, + before, + after, + details: `Check constraint ${chkName} modified on ${schemaName}.${srcTable.name}`, + }); + } + } + for (const [chkName, after] of tgtChecks) { + if (!srcChecks.has(chkName)) { + items.push({ + id: buildItemId("CHECK_ADDED", schemaName, srcTable.name, chkName), + type: "CHECK_ADDED", + severity: "safe", + schema: schemaName, + tableOrCollection: srcTable.name, + objectName: chkName, + after, + details: `Check constraint ${chkName} added on ${schemaName}.${srcTable.name}`, + }); + } + } +} + +function diffSqlSchemas( + source: CanonicalSchemaAST, + target: CanonicalSchemaAST, + detectRenames: boolean, +): SchemaDiffItem[] { + const items: SchemaDiffItem[] = []; + const srcSchemas = new Map(source.schemas.map((s) => [s.name, s])); + const tgtSchemas = new Map(target.schemas.map((s) => [s.name, s])); + + const srcTablesBySchema = new Map>(); + const tgtTablesBySchema = new Map>(); + + for (const [schemaName, srcSchema] of srcSchemas) { + const tgtSchema = tgtSchemas.get(schemaName); + if (!tgtSchema) { + items.push({ + id: buildItemId("SCHEMA_DROPPED", schemaName, schemaName), + type: "SCHEMA_DROPPED", + severity: "destructive", + schema: schemaName, + tableOrCollection: schemaName, + before: srcSchema, + details: `Schema ${schemaName} dropped`, + }); + continue; + } + + const srcTables = new Map(srcSchema.tables.map((t) => [t.name, t])); + const tgtTables = new Map(tgtSchema.tables.map((t) => [t.name, t])); + srcTablesBySchema.set(schemaName, srcTables); + tgtTablesBySchema.set(schemaName, tgtTables); + + for (const [tableName, srcTable] of srcTables) { + const tgtTable = tgtTables.get(tableName); + if (!tgtTable) { + items.push({ + id: buildItemId("TABLE_DROPPED", schemaName, tableName), + type: "TABLE_DROPPED", + severity: "destructive", + schema: schemaName, + tableOrCollection: tableName, + before: srcTable, + details: `Table ${schemaName}.${tableName} dropped`, + }); + } else { + diffTableObjects(schemaName, srcTable, tgtTable, items); + } + } + + for (const [tableName, tgtTable] of tgtTables) { + if (!srcTables.has(tableName)) { + items.push({ + id: buildItemId("TABLE_ADDED", schemaName, tableName), + type: "TABLE_ADDED", + severity: "safe", + schema: schemaName, + tableOrCollection: tableName, + after: tgtTable, + details: `Table ${schemaName}.${tableName} added`, + }); + } + } + + // Enums + const srcEnums = new Map(srcSchema.enums.map((e) => [e.name, e])); + const tgtEnums = new Map(tgtSchema.enums.map((e) => [e.name, e])); + + for (const [enumName, before] of srcEnums) { + const after = tgtEnums.get(enumName); + if (!after) { + items.push({ + id: buildItemId("ENUM_DROPPED", schemaName, enumName, enumName), + type: "ENUM_DROPPED", + severity: "warning", + schema: schemaName, + tableOrCollection: enumName, + objectName: enumName, + before, + details: `Enum ${schemaName}.${enumName} dropped`, + }); + } else if (!deepEqual(before, after)) { + items.push({ + id: buildItemId("ENUM_MODIFIED", schemaName, enumName, enumName), + type: "ENUM_MODIFIED", + severity: "warning", + schema: schemaName, + tableOrCollection: enumName, + objectName: enumName, + before, + after, + details: `Enum ${schemaName}.${enumName} values modified`, + }); + } + } + for (const [enumName, after] of tgtEnums) { + if (!srcEnums.has(enumName)) { + items.push({ + id: buildItemId("ENUM_ADDED", schemaName, enumName, enumName), + type: "ENUM_ADDED", + severity: "safe", + schema: schemaName, + tableOrCollection: enumName, + objectName: enumName, + after, + details: `Enum ${schemaName}.${enumName} added`, + }); + } + } + + // Views + const srcViews = new Map(srcSchema.views.map((v) => [v.name, v])); + const tgtViews = new Map(tgtSchema.views.map((v) => [v.name, v])); + + for (const [viewName, before] of srcViews) { + const after = tgtViews.get(viewName); + if (!after) { + items.push({ + id: buildItemId("VIEW_DROPPED", schemaName, viewName, viewName), + type: "VIEW_DROPPED", + severity: "warning", + schema: schemaName, + tableOrCollection: viewName, + objectName: viewName, + before, + details: `View ${schemaName}.${viewName} dropped`, + }); + } else if (!deepEqual(before, after)) { + items.push({ + id: buildItemId("VIEW_MODIFIED", schemaName, viewName, viewName), + type: "VIEW_MODIFIED", + severity: "warning", + schema: schemaName, + tableOrCollection: viewName, + objectName: viewName, + before, + after, + details: `View ${schemaName}.${viewName} definition modified`, + }); + } + } + for (const [viewName, after] of tgtViews) { + if (!srcViews.has(viewName)) { + items.push({ + id: buildItemId("VIEW_ADDED", schemaName, viewName, viewName), + type: "VIEW_ADDED", + severity: "safe", + schema: schemaName, + tableOrCollection: viewName, + objectName: viewName, + after, + details: `View ${schemaName}.${viewName} added`, + }); + } + } + } + + for (const [schemaName, tgtSchema] of tgtSchemas) { + if (!srcSchemas.has(schemaName)) { + items.push({ + id: buildItemId("SCHEMA_ADDED", schemaName, schemaName), + type: "SCHEMA_ADDED", + severity: "safe", + schema: schemaName, + tableOrCollection: schemaName, + after: tgtSchema, + details: `Schema ${schemaName} added`, + }); + } + } + + if (detectRenames) { + detectTableRenames(items, srcTablesBySchema, tgtTablesBySchema); + detectColumnRenames(items); + } + + return items; +} + +function diffMongoCollections( + source: CanonicalSchemaAST, + target: CanonicalSchemaAST, + detectRenames: boolean, +): SchemaDiffItem[] { + const items: SchemaDiffItem[] = []; + const srcColls = new Map((source.collections || []).map((c) => [c.name, c])); + const tgtColls = new Map((target.collections || []).map((c) => [c.name, c])); + + for (const [collName, srcColl] of srcColls) { + const tgtColl = tgtColls.get(collName); + if (!tgtColl) { + items.push({ + id: buildItemId("COLLECTION_DROPPED", undefined, collName), + type: "COLLECTION_DROPPED", + severity: "destructive", + tableOrCollection: collName, + before: srcColl, + details: `Collection ${collName} dropped`, + }); + continue; + } + + // MongoDB indexes + const srcIdx = new Map(srcColl.indexes.map((i) => [i.name, i])); + const tgtIdx = new Map(tgtColl.indexes.map((i) => [i.name, i])); + + for (const [idxName, before] of srcIdx) { + const after = tgtIdx.get(idxName); + if (!after) { + items.push({ + id: buildItemId("MONGO_INDEX_DROPPED", undefined, collName, idxName), + type: "MONGO_INDEX_DROPPED", + severity: "warning", + tableOrCollection: collName, + objectName: idxName, + before, + details: `Index ${idxName} dropped from collection ${collName}`, + }); + } else if (!deepEqual(before, after)) { + items.push({ + id: buildItemId("MONGO_INDEX_MODIFIED", undefined, collName, idxName), + type: "MONGO_INDEX_MODIFIED", + severity: "warning", + tableOrCollection: collName, + objectName: idxName, + before, + after, + details: `Index ${idxName} modified on collection ${collName}`, + }); + } + } + for (const [idxName, after] of tgtIdx) { + if (!srcIdx.has(idxName)) { + items.push({ + id: buildItemId("MONGO_INDEX_ADDED", undefined, collName, idxName), + type: "MONGO_INDEX_ADDED", + severity: "safe", + tableOrCollection: collName, + objectName: idxName, + after, + details: `Index ${idxName} added on collection ${collName}`, + }); + } + } + + // Validators + const beforeVal = { + validator: srcColl.validator ?? null, + validationLevel: srcColl.validationLevel ?? null, + validationAction: srcColl.validationAction ?? null, + }; + const afterVal = { + validator: tgtColl.validator ?? null, + validationLevel: tgtColl.validationLevel ?? null, + validationAction: tgtColl.validationAction ?? null, + }; + + if (!beforeVal.validator && afterVal.validator) { + items.push({ + id: buildItemId("VALIDATOR_ADDED", undefined, collName, "validator"), + type: "VALIDATOR_ADDED", + severity: "safe", + tableOrCollection: collName, + objectName: "validator", + after: afterVal, + details: `Schema validator added to collection ${collName}`, + }); + } else if (beforeVal.validator && !afterVal.validator) { + items.push({ + id: buildItemId("VALIDATOR_DROPPED", undefined, collName, "validator"), + type: "VALIDATOR_DROPPED", + severity: "warning", + tableOrCollection: collName, + objectName: "validator", + before: beforeVal, + details: `Schema validator dropped from collection ${collName}`, + }); + } else if (!deepEqual(beforeVal, afterVal)) { + items.push({ + id: buildItemId("VALIDATOR_MODIFIED", undefined, collName, "validator"), + type: "VALIDATOR_MODIFIED", + severity: "warning", + tableOrCollection: collName, + objectName: "validator", + before: beforeVal, + after: afterVal, + details: `Schema validator modified on collection ${collName}`, + }); + } + } + + for (const [collName, tgtColl] of tgtColls) { + if (!srcColls.has(collName)) { + items.push({ + id: buildItemId("COLLECTION_ADDED", undefined, collName), + type: "COLLECTION_ADDED", + severity: "safe", + tableOrCollection: collName, + after: tgtColl, + details: `Collection ${collName} added`, + }); + } + } + + if (detectRenames) { + detectMongoCollectionRenames(items, srcColls, tgtColls); + } + + return items; +} + +function detectMongoCollectionRenames( + items: SchemaDiffItem[], + srcColls: Map, + tgtColls: Map, +): void { + const dropped = items.filter((i) => i.type === "COLLECTION_DROPPED"); + const added = items.filter((i) => i.type === "COLLECTION_ADDED"); + const matchedAdded = new Set(); + + for (const dropItem of dropped) { + const srcColl = srcColls.get(dropItem.tableOrCollection); + if (!srcColl) continue; + const srcKeys = new Set( + srcColl.indexes.filter((i) => i.name !== "_id_").map((i) => stableStringify(i.key)), + ); + if (srcKeys.size === 0) continue; + + for (const addItem of added) { + if (matchedAdded.has(addItem.id)) continue; + const tgtColl = tgtColls.get(addItem.tableOrCollection); + if (!tgtColl) continue; + const tgtKeys = new Set( + tgtColl.indexes.filter((i) => i.name !== "_id_").map((i) => stableStringify(i.key)), + ); + if (tgtKeys.size > 0 && jaccardSimilarity(srcKeys, tgtKeys) >= 0.6) { + matchedAdded.add(addItem.id); + dropItem.renameCandidate = addItem.tableOrCollection; + addItem.renameCandidate = dropItem.tableOrCollection; + break; + } + } + } +} + +/** + * Diff two CanonicalSchemaAST trees (`source` -> `target`) and return + * a structured, severity-classified SchemaDiffResult. + */ +export function diffSchemas( + source: CanonicalSchemaAST, + target: CanonicalSchemaAST, + options: DiffSchemasOptions = {}, +): SchemaDiffResult { + const { sourceLabel = "source", targetLabel = "target", detectRenames = true } = options; + + const isMongo = + source.dialect === "mongodb" || + target.dialect === "mongodb" || + Boolean(source.collections?.length || target.collections?.length); + + const items = isMongo + ? diffMongoCollections(source, target, detectRenames) + : diffSqlSchemas(source, target, detectRenames); + + const summary: SchemaDiffSummary = { + total: items.length, + safe: 0, + warning: 0, + destructive: 0, + }; + + for (const item of items) { + summary[item.severity]++; + } + + return { + hasChanges: items.length > 0, + sourceLabel, + targetLabel, + dialect: target.dialect || source.dialect, + summary, + items, + }; +} diff --git a/bridge/src/services/schemaSnapshotNormalizer.ts b/bridge/src/services/schemaSnapshotNormalizer.ts new file mode 100644 index 00000000..c300ef63 --- /dev/null +++ b/bridge/src/services/schemaSnapshotNormalizer.ts @@ -0,0 +1,484 @@ +/** + * Schema Snapshot Normalizer + * + * Normalizes saved SchemaFile / SchemaSnapshot[] snapshots, live SQL + * introspection results (from QueryExecutor.listSchemas), and MongoDB + * collection/index/validator metadata into a deterministic CanonicalSchemaAST. + */ + +import type { + CanonicalCheck, + CanonicalCollection, + CanonicalColumn, + CanonicalDialect, + CanonicalEnum, + CanonicalForeignKey, + CanonicalIndex, + CanonicalMongoIndex, + CanonicalSchema, + CanonicalSchemaAST, + CanonicalTable, + CanonicalView, +} from "../types/schemaDiff"; +import type { SchemaFile, SchemaSnapshot } from "./projectStore"; + +/** Internal migration tracking tables excluded from schema diffs. */ +export const INTERNAL_MIGRATION_TABLES: ReadonlySet = new Set([ + "schema_migrations", + "__relwave_migrations", + "relwave_migrations", + "_relwave_migrations", + "_relwave_migration_events", + "_relwave_migrations_lock", +]); + +/** Compare two strings deterministically without locale variance. */ +function compareNames(a: string, b: string): number { + if (a < b) return -1; + if (a > b) return 1; + return 0; +} + +/** + * Map a raw engine/dialect string to a CanonicalDialect. + */ +export function normalizeDialect(rawDialect?: string | null): CanonicalDialect { + const value = (rawDialect || "").trim().toLowerCase(); + switch (value) { + case "postgres": + case "postgresql": + case "pg": + return "postgresql"; + case "mysql": + return "mysql"; + case "mariadb": + return "mariadb"; + case "sqlite": + case "sqlite3": + return "sqlite"; + case "duckdb": + return "duckdb"; + case "clickhouse": + return "clickhouse"; + case "mongo": + case "mongodb": + return "mongodb"; + default: + return "postgresql"; + } +} + +/** + * Canonicalize a SQL column type string for a given dialect. + * Collapses whitespace, lowercases, and normalizes dialect-specific aliases + * (e.g. Postgres `int4` -> `integer`, MySQL `int(11)` -> `int`). + */ +export function canonicalizeType( + rawType: string | null | undefined, + dialect: CanonicalDialect, +): string { + if (!rawType) return "unknown"; + + let normalized = rawType + .trim() + .toLowerCase() + .replace(/\s+/g, " ") + .replace(/\s*\(\s*/g, "(") + .replace(/\s*\)/g, ")") + .replace(/\)(?=[a-z])/g, ") ") + .replace(/\s*,\s*/g, ", "); + + if (dialect === "postgresql" || dialect === "duckdb") { + normalized = normalized + .replace(/^character varying(\(.*\))?$/, "varchar$1") + .replace(/^character(\(.*\))?$/, "char$1") + .replace(/^decimal(\(.*\))?$/, "numeric$1"); + + const pgAliases: Record = { + int4: "integer", + int: "integer", + int8: "bigint", + int2: "smallint", + bool: "boolean", + float4: "real", + float8: dialect === "duckdb" ? "double" : "double precision", + timestamptz: "timestamp with time zone", + timetz: "time with time zone", + serial4: "serial", + serial8: "bigserial", + serial2: "smallserial", + }; + if (pgAliases[normalized]) { + return pgAliases[normalized]; + } + return normalized; + } + + if (dialect === "mysql" || dialect === "mariadb") { + // Strip integer display widths like int(11), bigint(20), tinyint(4) + normalized = normalized.replace( + /^(tinyint|smallint|mediumint|int|integer|bigint)\(\d+\)(\s+unsigned)?$/, + (_m, base, unsigned) => { + const canonicalBase = base === "integer" ? "int" : base; + return `${canonicalBase}${unsigned || ""}`; + }, + ); + if (normalized === "integer") return "int"; + if (normalized === "integer unsigned") return "int unsigned"; + if (normalized === "bool") return "boolean"; + return normalized; + } + + if (dialect === "sqlite") { + if (normalized === "int") return "integer"; + if (normalized === "bool") return "boolean"; + return normalized; + } + + return normalized; +} + +/** + * Normalize SQL expressions (defaults, check constraints, index predicates, view definitions). + * Collapses whitespace, normalizes spacing around parentheses, and unquotes simple identifiers. + */ +export function normalizeExpression(expr: string | null | undefined): string | null { + if (expr === null || expr === undefined) return null; + const trimmed = String(expr).trim(); + if (!trimmed) return null; + + return trimmed + .replace(/\s+/g, " ") + .replace(/\(\s+/g, "(") + .replace(/\s+\)/g, ")") + .replace(/["`]([a-zA-Z_][a-zA-Z0-9_]*)["`]/g, "$1") + .trim(); +} + +function isInternalTable(name: string): boolean { + return INTERNAL_MIGRATION_TABLES.has(name.toLowerCase()); +} + +function normalizeRule(rule?: string | null): string { + return (rule || "NO ACTION").trim().toUpperCase(); +} + +function normalizeColumns( + rawColumns: any[] | undefined, + dialect: CanonicalDialect, +): CanonicalColumn[] { + const cols: CanonicalColumn[] = (rawColumns || []).map((c: any, idx: number) => ({ + name: String(c.name), + type: canonicalizeType(c.type, dialect), + nullable: c.nullable !== undefined ? Boolean(c.nullable) : !c.not_nullable, + isPrimaryKey: Boolean(c.isPrimaryKey ?? c.is_primary_key), + isForeignKey: Boolean(c.isForeignKey ?? c.is_foreign_key), + defaultValue: normalizeExpression(c.defaultValue ?? c.default_value ?? null), + isUnique: Boolean(c.isUnique ?? c.is_unique), + isSerial: Boolean(c.isSerial ?? c.is_serial), + ordinalPosition: Number(c.ordinalPosition ?? c.ordinal_position ?? idx + 1), + comment: c.comment ?? null, + })); + + cols.sort((a, b) => compareNames(a.name, b.name)); + return cols; +} + +function normalizeIndexes(rawIndexes: any[] | undefined): CanonicalIndex[] { + if (!rawIndexes || rawIndexes.length === 0) return []; + + // Already grouped (IndexSnapshot[] / CanonicalIndex[]) + if (Array.isArray(rawIndexes[0]?.columns)) { + const result: CanonicalIndex[] = rawIndexes.map((idx: any) => ({ + name: String(idx.name), + columns: [...idx.columns].map(String), + unique: Boolean(idx.unique), + partial: normalizeExpression(idx.partial ?? null), + ...(idx.indexType ? { indexType: String(idx.indexType).toLowerCase() } : {}), + })); + result.sort((a, b) => compareNames(a.name, b.name)); + return result; + } + + // Flat rows (IndexInfo[] from live connector introspection) + const grouped = new Map< + string, + { + name: string; + cols: Array<{ name: string; pos: number }>; + unique: boolean; + partial: string | null; + indexType?: string; + } + >(); + + for (const row of rawIndexes) { + const name = String(row.index_name || row.name); + if (!grouped.has(name)) { + grouped.set(name, { + name, + cols: [], + unique: Boolean(row.is_unique ?? row.unique), + partial: normalizeExpression(row.predicate ?? row.partial ?? null), + indexType: row.index_type ? String(row.index_type).toLowerCase() : undefined, + }); + } + const entry = grouped.get(name)!; + const colName = row.column_name ?? row.column; + if (colName) { + entry.cols.push({ + name: String(colName), + pos: Number(row.seq_in_index ?? row.ordinal_position ?? entry.cols.length + 1), + }); + } + } + + const result: CanonicalIndex[] = Array.from(grouped.values()).map((g) => { + g.cols.sort((a, b) => a.pos - b.pos); + return { + name: g.name, + columns: g.cols.map((c) => c.name), + unique: g.unique, + partial: g.partial, + ...(g.indexType ? { indexType: g.indexType } : {}), + }; + }); + + result.sort((a, b) => compareNames(a.name, b.name)); + return result; +} + +function normalizeForeignKeys(rawFks: any[] | undefined): CanonicalForeignKey[] { + if (!rawFks || rawFks.length === 0) return []; + + // Already grouped (ForeignKeySnapshot[] / CanonicalForeignKey[]) + if (Array.isArray(rawFks[0]?.columns)) { + const result: CanonicalForeignKey[] = rawFks.map((fk: any) => ({ + name: String(fk.name), + columns: [...fk.columns].map(String), + referencedSchema: String(fk.referencedSchema || ""), + referencedTable: String(fk.referencedTable), + referencedColumns: [...(fk.referencedColumns || [])].map(String), + onDelete: normalizeRule(fk.onDelete), + onUpdate: normalizeRule(fk.onUpdate), + })); + result.sort((a, b) => compareNames(a.name, b.name)); + return result; + } + + // Flat rows (ForeignKeyInfo[] from live connector introspection) + const grouped = new Map< + string, + { + name: string; + pairs: Array<{ sourceCol: string; targetCol: string; pos: number }>; + referencedSchema: string; + referencedTable: string; + onDelete: string; + onUpdate: string; + } + >(); + + for (const row of rawFks) { + const name = String(row.constraint_name || row.name); + if (!grouped.has(name)) { + grouped.set(name, { + name, + pairs: [], + referencedSchema: String(row.target_schema || row.referencedSchema || ""), + referencedTable: String(row.target_table || row.referencedTable || ""), + onDelete: normalizeRule(row.delete_rule ?? row.onDelete), + onUpdate: normalizeRule(row.update_rule ?? row.onUpdate), + }); + } + const entry = grouped.get(name)!; + if (row.source_column) { + entry.pairs.push({ + sourceCol: String(row.source_column), + targetCol: String(row.target_column || ""), + pos: Number(row.ordinal_position ?? entry.pairs.length + 1), + }); + } + } + + const result: CanonicalForeignKey[] = Array.from(grouped.values()).map((g) => { + g.pairs.sort((a, b) => a.pos - b.pos); + return { + name: g.name, + columns: g.pairs.map((p) => p.sourceCol), + referencedSchema: g.referencedSchema, + referencedTable: g.referencedTable, + referencedColumns: g.pairs.map((p) => p.targetCol), + onDelete: g.onDelete, + onUpdate: g.onUpdate, + }; + }); + + result.sort((a, b) => compareNames(a.name, b.name)); + return result; +} + +function normalizeChecks(rawChecks: any[] | undefined): CanonicalCheck[] { + const checks: CanonicalCheck[] = (rawChecks || []).map((c: any) => ({ + name: String(c.name ?? c.constraint_name), + expression: normalizeExpression(c.expression ?? c.definition ?? c.check_clause ?? "") || "", + })); + checks.sort((a, b) => compareNames(a.name, b.name)); + return checks; +} + +function normalizeEnums(rawEnums: any[] | undefined): CanonicalEnum[] { + if (!rawEnums || rawEnums.length === 0) return []; + + // Already grouped ({ name, values }) + if (Array.isArray(rawEnums[0]?.values)) { + const result: CanonicalEnum[] = rawEnums.map((e: any) => ({ + name: String(e.name), + values: [...e.values].map(String), + })); + result.sort((a, b) => compareNames(a.name, b.name)); + return result; + } + + // Flat rows ({ enum_name, enum_value }) + const grouped = new Map(); + for (const row of rawEnums) { + const name = String(row.enum_name || row.name); + if (!grouped.has(name)) grouped.set(name, []); + if (row.enum_value !== undefined) { + grouped.get(name)!.push(String(row.enum_value)); + } + } + + const result: CanonicalEnum[] = Array.from(grouped.entries()).map(([name, values]) => ({ + name, + values, + })); + result.sort((a, b) => compareNames(a.name, b.name)); + return result; +} + +function normalizeViews(rawViews: any[] | undefined): CanonicalView[] { + const views: CanonicalView[] = (rawViews || []).map((v: any) => ({ + name: String(v.name), + definition: normalizeExpression(v.definition) || "", + })); + views.sort((a, b) => compareNames(a.name, b.name)); + return views; +} + +function normalizeSqlSchemaArray(rawSchemas: any[], dialect: CanonicalDialect): CanonicalSchema[] { + const schemas: CanonicalSchema[] = (rawSchemas || []).map((s: any) => { + const tables: CanonicalTable[] = (s.tables || []) + .filter((t: any) => t?.name && !isInternalTable(String(t.name))) + .map((t: any) => ({ + name: String(t.name), + type: String(t.type || "BASE TABLE").toUpperCase(), + columns: normalizeColumns(t.columns, dialect), + indexes: normalizeIndexes(t.indexes), + foreignKeys: normalizeForeignKeys(t.foreignKeys), + checks: normalizeChecks(t.checks ?? t.checkConstraints), + comment: t.comment ?? null, + })); + tables.sort((a, b) => compareNames(a.name, b.name)); + + const enums = normalizeEnums(s.enums ?? s.enumTypes); + const views = normalizeViews(s.views); + + return { + name: String(s.name), + tables, + enums, + views, + }; + }); + + schemas.sort((a, b) => compareNames(a.name, b.name)); + return schemas; +} + +/** + * Normalize a saved SchemaFile (or SchemaSnapshot[]) into a CanonicalSchemaAST. + */ +export function normalizeSchemaFile( + input: + | SchemaFile + | { dialect?: string; schemas?: SchemaSnapshot[]; collections?: MongoIntrospectionInput[] }, +): CanonicalSchemaAST { + const dialect = normalizeDialect((input as any)?.dialect); + if (dialect === "mongodb") { + const rawCollections = (input as any)?.collections || []; + return normalizeMongoIntrospection(rawCollections); + } + const schemas = normalizeSqlSchemaArray((input as any)?.schemas || [], dialect); + return { dialect, schemas }; +} + +/** + * Normalize a live SQL introspection result (from `QueryExecutor.listSchemas`) + * into a CanonicalSchemaAST. + */ +export function normalizeLiveSqlSchemas( + liveResult: { schemas?: any[] } | any[], + dialect: string | CanonicalDialect, +): CanonicalSchemaAST { + const canonicalDialect = normalizeDialect(dialect); + const rawSchemas = Array.isArray(liveResult) ? liveResult : liveResult?.schemas || []; + const schemas = normalizeSqlSchemaArray(rawSchemas, canonicalDialect); + return { dialect: canonicalDialect, schemas }; +} + +export interface MongoIntrospectionInput { + name: string; + type?: "collection" | "view"; + indexes?: Array<{ + name: string; + key: Record; + unique?: boolean; + sparse?: boolean; + expireAfterSeconds?: number; + partialFilterExpression?: Record | null; + }>; + validator?: Record | null; + validationLevel?: string | null; + validationAction?: string | null; +} + +/** + * Normalize MongoDB collections, indexes, and validators into a CanonicalSchemaAST. + */ +export function normalizeMongoIntrospection( + rawCollections: MongoIntrospectionInput[], +): CanonicalSchemaAST { + const collections: CanonicalCollection[] = (rawCollections || []) + .filter((c) => c?.name && !isInternalTable(c.name) && !c.name.startsWith("system.")) + .map((c) => { + const indexes: CanonicalMongoIndex[] = (c.indexes || []).map((idx) => ({ + name: String(idx.name), + key: idx.key || {}, + unique: Boolean(idx.unique), + sparse: Boolean(idx.sparse), + ...(idx.expireAfterSeconds !== undefined + ? { expireAfterSeconds: idx.expireAfterSeconds } + : {}), + partialFilterExpression: idx.partialFilterExpression ?? null, + })); + indexes.sort((a, b) => compareNames(a.name, b.name)); + + return { + name: String(c.name), + type: c.type === "view" ? "view" : "collection", + indexes, + validator: c.validator ?? null, + validationLevel: c.validationLevel ?? null, + validationAction: c.validationAction ?? null, + }; + }); + + collections.sort((a, b) => compareNames(a.name, b.name)); + return { + dialect: "mongodb", + schemas: [], + collections, + }; +} diff --git a/bridge/src/types/index.ts b/bridge/src/types/index.ts index cc95126d..c0ef4a24 100644 --- a/bridge/src/types/index.ts +++ b/bridge/src/types/index.ts @@ -20,6 +20,7 @@ export * from "./mongo"; export * from "./mongoMigration"; export * from "./mongoBulk"; export * from "./ai"; +export * from "./schemaDiff"; export { SSHConfig } from "./common"; export enum DBType { diff --git a/bridge/src/types/schemaDiff.ts b/bridge/src/types/schemaDiff.ts new file mode 100644 index 00000000..046ad4fe --- /dev/null +++ b/bridge/src/types/schemaDiff.ts @@ -0,0 +1,160 @@ +/** + * Canonical Schema AST & Schema Diff Types + * + * Engine-agnostic AST representation for SQL and MongoDB schemas, + * along with structured diff result types. + */ + +export type CanonicalDialect = + "postgresql" | "mysql" | "mariadb" | "sqlite" | "duckdb" | "clickhouse" | "mongodb"; + +export interface CanonicalColumn { + name: string; + type: string; + nullable: boolean; + isPrimaryKey: boolean; + isForeignKey: boolean; + defaultValue: string | null; + isUnique: boolean; + isSerial: boolean; + ordinalPosition: number; + comment?: string | null; +} + +export interface CanonicalIndex { + name: string; + columns: string[]; + unique: boolean; + partial?: string | null; + indexType?: string; +} + +export interface CanonicalForeignKey { + name: string; + columns: string[]; + referencedSchema: string; + referencedTable: string; + referencedColumns: string[]; + onDelete: string; + onUpdate: string; +} + +export interface CanonicalCheck { + name: string; + expression: string; +} + +export interface CanonicalTable { + name: string; + type: string; + columns: CanonicalColumn[]; + indexes: CanonicalIndex[]; + foreignKeys: CanonicalForeignKey[]; + checks: CanonicalCheck[]; + comment?: string | null; +} + +export interface CanonicalEnum { + name: string; + values: string[]; +} + +export interface CanonicalView { + name: string; + definition: string; +} + +export interface CanonicalSchema { + name: string; + tables: CanonicalTable[]; + enums: CanonicalEnum[]; + views: CanonicalView[]; +} + +export interface CanonicalMongoIndex { + name: string; + key: Record; + unique: boolean; + sparse: boolean; + expireAfterSeconds?: number; + partialFilterExpression?: Record | null; +} + +export interface CanonicalCollection { + name: string; + type: "collection" | "view"; + indexes: CanonicalMongoIndex[]; + validator?: Record | null; + validationLevel?: string | null; + validationAction?: string | null; +} + +export interface CanonicalSchemaAST { + dialect: CanonicalDialect; + schemas: CanonicalSchema[]; + collections?: CanonicalCollection[]; +} + +export type DiffSeverity = "safe" | "warning" | "destructive"; + +export type DiffOperationType = + | "SCHEMA_ADDED" + | "SCHEMA_DROPPED" + | "TABLE_ADDED" + | "TABLE_DROPPED" + | "TABLE_MODIFIED" + | "COLUMN_ADDED" + | "COLUMN_DROPPED" + | "COLUMN_MODIFIED" + | "INDEX_ADDED" + | "INDEX_DROPPED" + | "INDEX_MODIFIED" + | "FK_ADDED" + | "FK_DROPPED" + | "FK_MODIFIED" + | "CHECK_ADDED" + | "CHECK_DROPPED" + | "CHECK_MODIFIED" + | "ENUM_ADDED" + | "ENUM_DROPPED" + | "ENUM_MODIFIED" + | "VIEW_ADDED" + | "VIEW_DROPPED" + | "VIEW_MODIFIED" + | "COLLECTION_ADDED" + | "COLLECTION_DROPPED" + | "MONGO_INDEX_ADDED" + | "MONGO_INDEX_DROPPED" + | "MONGO_INDEX_MODIFIED" + | "VALIDATOR_ADDED" + | "VALIDATOR_DROPPED" + | "VALIDATOR_MODIFIED"; + +export interface SchemaDiffItem { + id: string; + type: DiffOperationType; + severity: DiffSeverity; + schema?: string; + tableOrCollection: string; + objectName?: string; + before?: unknown; + after?: unknown; + details: string; + renameCandidate?: string; +} + +export interface SchemaDiffSummary { + total: number; + safe: number; + warning: number; + destructive: number; +} + +export interface SchemaDiffResult { + hasChanges: boolean; + sourceLabel: string; + targetLabel: string; + dialect: CanonicalDialect; + summary: SchemaDiffSummary; + items: SchemaDiffItem[]; +} From 83a9412c0eea8b70559fd5f8a97af57980326c21 Mon Sep 17 00:00:00 2001 From: Yash Date: Sat, 28 Nov 2026 19:45:54 +0530 Subject: [PATCH 02/14] feat(migrations): implement dialect-aware migration generator and diff inspector UI (M2) --- bridge/__tests__/migrationGenerator.test.ts | 447 ++++++++ bridge/src/handlers/migrationHandlers.ts | 311 ++++-- bridge/src/jsonRpcHandler.ts | 3 + bridge/src/services/migrationGenerator.ts | 995 ++++++++++++++++++ src/__tests__/schemaDiffMigration.test.ts | 188 ++++ .../database/components/MigrationsPanel.tsx | 67 +- .../components/SchemaDiffMigrationDialog.tsx | 573 ++++++++++ .../database/hooks/useSchemaDiffMigration.ts | 367 +++++++ .../git/components/GitStatusPanel.tsx | 28 + .../migrations/MongoMigrationsPanel.tsx | 37 + src/services/bridge/migration.ts | 91 ++ 11 files changed, 2988 insertions(+), 119 deletions(-) create mode 100644 bridge/__tests__/migrationGenerator.test.ts create mode 100644 bridge/src/services/migrationGenerator.ts create mode 100644 src/__tests__/schemaDiffMigration.test.ts create mode 100644 src/features/database/components/SchemaDiffMigrationDialog.tsx create mode 100644 src/features/database/hooks/useSchemaDiffMigration.ts diff --git a/bridge/__tests__/migrationGenerator.test.ts b/bridge/__tests__/migrationGenerator.test.ts new file mode 100644 index 00000000..c84c15af --- /dev/null +++ b/bridge/__tests__/migrationGenerator.test.ts @@ -0,0 +1,447 @@ +import { describe, expect, test } from "@jest/globals"; +import { diffSchemas } from "../src/services/schemaDiffEngine"; +import { + generateMigrationFromDiff, + slugifyMigrationName, +} from "../src/services/migrationGenerator"; +import { MANIFEST_FILENAME_REGEX, validateManifest } from "../src/services/mongoMigrationEngine"; +import type { CanonicalColumn, CanonicalSchemaAST, CanonicalTable } from "../src/types/schemaDiff"; + +function col( + name: string, + type: string, + overrides: Partial = {}, +): CanonicalColumn { + return { + name, + type, + nullable: true, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + ...overrides, + }; +} + +function tbl( + name: string, + columns: CanonicalColumn[], + overrides: Partial = {}, +): CanonicalTable { + return { + name, + type: "BASE TABLE", + columns, + indexes: [], + foreignKeys: [], + checks: [], + ...overrides, + }; +} + +describe("migrationGenerator", () => { + test("slugifyMigrationName sanitizes unsafe characters and falls back to schema_diff", () => { + expect(slugifyMigrationName(undefined)).toBe("schema_diff"); + expect(slugifyMigrationName(" ")).toBe("schema_diff"); + expect(slugifyMigrationName("Add Users & Orders!")).toBe("Add_Users_Orders"); + expect(slugifyMigrationName("add-user_idx")).toBe("add-user_idx"); + }); + + test("PostgreSQL: generates -- +up/-- +down with enums, tables, indexes, FKs, checks, views, and concurrentIndexes", () => { + const source: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + tbl("users", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("legacy_col", "text"), + ]), + ], + enums: [{ name: "role_type", values: ["user"] }], + views: [], + }, + ], + }; + + const target: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + tbl( + "users", + [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("email", "varchar(255)", { nullable: false, defaultValue: "''" }), + ], + { + indexes: [{ name: "idx_users_email", columns: ["email"], unique: true }], + checks: [{ name: "chk_email_nonempty", expression: "email <> ''" }], + }, + ), + tbl( + "orders", + [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("user_id", "integer", { nullable: false }), + ], + { + foreignKeys: [ + { + name: "fk_orders_user", + columns: ["user_id"], + referencedSchema: "public", + referencedTable: "users", + referencedColumns: ["id"], + onDelete: "CASCADE", + onUpdate: "NO ACTION", + }, + ], + }, + ), + ], + enums: [ + { name: "role_type", values: ["user", "admin"] }, + { name: "order_status", values: ["pending", "paid"] }, + ], + views: [{ name: "active_users", definition: "SELECT id, email FROM public.users" }], + }, + ], + }; + + const diff = diffSchemas(source, target, { detectRenames: false }); + const res = generateMigrationFromDiff(diff, source, target, { + name: "add orders & email", + version: "20261128120000", + concurrentIndexes: true, + }); + + expect(res.format).toBe("sql"); + expect(res.filename).toBe("20261128120000_add_orders_email.sql"); + expect(res.hasDestructive).toBe(true); + expect(res.warnings.length).toBeGreaterThan(0); + expect(res.content).toContain("-- +up"); + expect(res.content).toContain("-- +down"); + expect(res.upSql).toContain("-- WARNING: Destructive operation:"); + expect(res.upSql).toContain('ALTER TABLE "public"."users" DROP COLUMN "legacy_col";'); + expect(res.upSql).toContain( + "CREATE TYPE \"public\".\"order_status\" AS ENUM ('pending', 'paid');", + ); + expect(res.upSql).toContain( + 'ALTER TYPE "public"."role_type" ADD VALUE IF NOT EXISTS \'admin\';', + ); + expect(res.upSql).toContain( + 'CREATE UNIQUE INDEX CONCURRENTLY "idx_users_email" ON "public"."users" ("email");', + ); + expect(res.upSql).not.toMatch(/\bBEGIN;/); + expect(res.upSql).toContain('CREATE TABLE "public"."orders"'); + expect(res.upSql).toContain( + 'CREATE VIEW "public"."active_users" AS SELECT id, email FROM public.users;', + ); + }); + + test("MySQL: uses backticks, MODIFY COLUMN, DROP FOREIGN KEY, and RENAME TABLE on accepted rename", () => { + const source: CanonicalSchemaAST = { + dialect: "mysql", + schemas: [ + { + name: "app", + tables: [ + tbl("accounts", [ + col("id", "int", { nullable: false, isPrimaryKey: true }), + col("username", "varchar(50)", { nullable: false }), + col("bio", "varchar(100)", { nullable: true }), + ]), + ], + enums: [], + views: [], + }, + ], + }; + + const target: CanonicalSchemaAST = { + dialect: "mysql", + schemas: [ + { + name: "app", + tables: [ + tbl("members", [ + col("id", "int", { nullable: false, isPrimaryKey: true }), + col("username", "varchar(50)", { nullable: false }), + col("bio", "varchar(100)", { nullable: true }), + ]), + ], + enums: [], + views: [], + }, + ], + }; + + const diff = diffSchemas(source, target, { detectRenames: true }); + const dropTableItem = diff.items.find((i) => i.type === "TABLE_DROPPED")!; + expect(dropTableItem.renameCandidate).toBe("members"); + + const res = generateMigrationFromDiff(diff, source, target, { + version: "20261128120001", + acceptRenameIds: [dropTableItem.id], + }); + + expect(res.hasDestructive).toBe(false); + expect(res.upSql).toContain("RENAME TABLE `app`.`accounts` TO `app`.`members`;"); + expect(res.upSql).not.toContain("DROP TABLE"); + expect(res.downSql).toContain("RENAME TABLE `app`.`members` TO `app`.`accounts`;"); + }); + + test("SQLite: emits 12-step table-rebuild pattern for COLUMN_MODIFIED, COLUMN_DROPPED, FK_ADDED, CHECK_ADDED", () => { + const source: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [ + tbl("items", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("price", "integer", { nullable: true }), + col("old_flag", "integer", { nullable: true }), + ]), + ], + enums: [], + views: [], + }, + ], + }; + + const target: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [ + tbl( + "items", + [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("price", "real", { nullable: false, defaultValue: "0" }), + ], + { + checks: [{ name: "chk_price", expression: "price >= 0" }], + }, + ), + ], + enums: [], + views: [], + }, + ], + }; + + const diff = diffSchemas(source, target, { detectRenames: false }); + const res = generateMigrationFromDiff(diff, source, target, { version: "20261128120002" }); + + expect(res.hasDestructive).toBe(true); + expect(res.upSql).toContain("PRAGMA foreign_keys=OFF;"); + expect(res.upSql).toContain("BEGIN;"); + expect(res.upSql).toContain('CREATE TABLE "__relwave_new_items"'); + expect(res.upSql).toContain( + 'INSERT INTO "__relwave_new_items" ("id", "price") SELECT "id", "price" FROM "items";', + ); + expect(res.upSql).toContain('DROP TABLE "items";'); + expect(res.upSql).toContain('ALTER TABLE "__relwave_new_items" RENAME TO "items";'); + expect(res.upSql).toContain("PRAGMA foreign_key_check;"); + expect(res.upSql).toContain("COMMIT;"); + expect(res.upSql).toContain("PRAGMA foreign_keys=ON;"); + }); + + test("DuckDB & ClickHouse: generates dialect-appropriate DDL", () => { + const duckSource: CanonicalSchemaAST = { + dialect: "duckdb", + schemas: [ + { + name: "main", + tables: [tbl("metrics", [col("id", "integer"), col("val", "integer")])], + enums: [], + views: [], + }, + ], + }; + const duckTarget: CanonicalSchemaAST = { + dialect: "duckdb", + schemas: [ + { + name: "main", + tables: [tbl("metrics", [col("id", "integer"), col("val", "bigint")])], + enums: [], + views: [], + }, + ], + }; + + const duckDiff = diffSchemas(duckSource, duckTarget); + const duckRes = generateMigrationFromDiff(duckDiff, duckSource, duckTarget, { + version: "20261128120003", + }); + expect(duckRes.upSql).toContain('ALTER TABLE "main"."metrics" ALTER COLUMN "val" TYPE bigint;'); + + const chSource: CanonicalSchemaAST = { + dialect: "clickhouse", + schemas: [{ name: "analytics", tables: [], enums: [], views: [] }], + }; + const chTarget: CanonicalSchemaAST = { + dialect: "clickhouse", + schemas: [ + { + name: "analytics", + tables: [ + tbl("events", [ + col("id", "UInt64", { nullable: false, isPrimaryKey: true }), + col("name", "String", { nullable: false }), + ]), + ], + enums: [], + views: [], + }, + ], + }; + + const chDiff = diffSchemas(chSource, chTarget); + const chRes = generateMigrationFromDiff(chDiff, chSource, chTarget, { + version: "20261128120004", + }); + expect(chRes.upSql).toContain("CREATE TABLE `analytics`.`events`"); + expect(chRes.upSql).toContain("ENGINE = MergeTree() ORDER BY (`id`);"); + }); + + test("acceptRenameIds: renames column instead of DROP + ADD", () => { + const source: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + tbl("users", [col("id", "integer"), col("full_name", "text", { nullable: false })]), + ], + enums: [], + views: [], + }, + ], + }; + const target: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + tbl("users", [col("id", "integer"), col("display_name", "text", { nullable: false })]), + ], + enums: [], + views: [], + }, + ], + }; + + const diff = diffSchemas(source, target, { detectRenames: true }); + const dropCol = diff.items.find((i) => i.type === "COLUMN_DROPPED")!; + expect(dropCol.renameCandidate).toBe("display_name"); + + const res = generateMigrationFromDiff(diff, source, target, { + version: "20261128120005", + acceptRenameIds: [dropCol.id], + }); + + expect(res.hasDestructive).toBe(false); + expect(res.upSql).toContain( + 'ALTER TABLE "public"."users" RENAME COLUMN "full_name" TO "display_name";', + ); + expect(res.upSql).not.toContain("DROP COLUMN"); + expect(res.downSql).toContain( + 'ALTER TABLE "public"."users" RENAME COLUMN "display_name" TO "full_name";', + ); + }); + + test("MongoDB: generates valid .mql.json manifest with warnings for dropCollection, dropIndex, dropValidator", () => { + const source: CanonicalSchemaAST = { + dialect: "mongodb", + schemas: [], + collections: [ + { + name: "legacy_logs", + type: "collection", + indexes: [{ name: "_id_", key: { _id: 1 }, unique: true, sparse: false }], + }, + { + name: "users", + type: "collection", + indexes: [ + { name: "_id_", key: { _id: 1 }, unique: true, sparse: false }, + { name: "old_idx", key: { oldField: 1 }, unique: false, sparse: false }, + ], + validator: { $jsonSchema: { bsonType: "object" } }, + }, + ], + }; + + const target: CanonicalSchemaAST = { + dialect: "mongodb", + schemas: [], + collections: [ + { + name: "users", + type: "collection", + indexes: [ + { name: "_id_", key: { _id: 1 }, unique: true, sparse: false }, + { name: "email_1", key: { email: 1 }, unique: true, sparse: false }, + ], + validator: null, + }, + { + name: "sessions", + type: "collection", + indexes: [ + { name: "_id_", key: { _id: 1 }, unique: true, sparse: false }, + { name: "token_1", key: { token: 1 }, unique: true, sparse: false }, + ], + }, + ], + }; + + const diff = diffSchemas(source, target, { detectRenames: false }); + const res = generateMigrationFromDiff(diff, source, target, { + name: "mongo sync", + version: "20261128120006", + }); + + expect(res.format).toBe("mql"); + expect(res.filename).toMatch(MANIFEST_FILENAME_REGEX); + expect(res.filename).toBe("20261128120006_mongo_sync.mql.json"); + expect(res.hasDestructive).toBe(true); + expect(res.warnings.some((w) => w.includes("legacy_logs"))).toBe(true); + expect(res.warnings.some((w) => w.includes("old_idx"))).toBe(true); + expect(res.warnings.some((w) => w.includes("validator"))).toBe(true); + + expect(res.manifest).toBeDefined(); + expect(res.manifest!.allowIrreversible).toBe(true); + expect( + res.manifest!.up.some((s) => s.type === "dropCollection" && s.collection === "legacy_logs"), + ).toBe(true); + expect( + res.manifest!.up.some((s) => s.type === "createCollection" && s.collection === "sessions"), + ).toBe(true); + expect(res.manifest!.up.some((s) => s.type === "createIndex" && s.collection === "users")).toBe( + true, + ); + expect(res.manifest!.up.some((s) => s.type === "dropIndex" && s.collection === "users")).toBe( + true, + ); + expect( + res.manifest!.up.some((s) => s.type === "setValidator" && s.collection === "users"), + ).toBe(true); + + const validation = validateManifest(res.manifest); + expect(validation.valid).toBe(true); + }); +}); diff --git a/bridge/src/handlers/migrationHandlers.ts b/bridge/src/handlers/migrationHandlers.ts index 152427f2..151c9756 100644 --- a/bridge/src/handlers/migrationHandlers.ts +++ b/bridge/src/handlers/migrationHandlers.ts @@ -6,12 +6,27 @@ import { Logger } from "pino"; import path from "path"; import fs from "fs"; import { projectStoreInstance } from "../services/projectStore"; -import { mongoMigrationEngine } from "../services/mongoMigrationEngine"; +import { + mongoMigrationEngine, + resolveMongoMigrationsDir, + validateSafeFilePath, +} from "../services/mongoMigrationEngine"; import { selectDb, MongoApiError } from "../connectors/mongo"; import { gitServiceInstance } from "../services/gitService"; import { normalizeSchemaFile } from "../services/schemaSnapshotNormalizer"; import { diffSchemas } from "../services/schemaDiffEngine"; import { introspectLiveCanonicalAST } from "../services/liveSchemaIntrospector"; +import { generateMigrationFromDiff } from "../services/migrationGenerator"; +import type { CanonicalSchemaAST, SchemaDiffResult } from "../types/schemaDiff"; + +class RpcInputError extends Error { + constructor( + public readonly code: string, + message: string, + ) { + super(message); + } +} export class MigrationHandlers { constructor( @@ -23,7 +38,7 @@ export class MigrationHandlers { private sendMigrationError(id: number | string, e: any, contextMsg: string): void { this.logger?.error({ e }, contextMsg); - if (e instanceof MongoApiError) { + if (e instanceof MongoApiError || e instanceof RpcInputError) { this.rpc.sendError(id, { code: e.code, message: e.message }); } else { this.rpc.sendError(id, { @@ -835,130 +850,216 @@ export class MigrationHandlers { } /** - * Compare two schema sources (live-vs-snapshot, live-vs-ref, ref-vs-ref) - * and return a structured SchemaDiffResult. + * Resolves source & target CanonicalSchemaASTs and computes their SchemaDiffResult + * for `live-vs-snapshot`, `live-vs-ref`, or `ref-vs-ref` modes. */ - async handleDiffSchema(params: any, id: number | string) { - try { - const { projectId, mode = "live-vs-snapshot", sourceRef, targetRef } = params || {}; - if (!projectId) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing projectId" }); + private async resolveSchemaDiff(params: { + projectId?: string; + mode?: string; + sourceRef?: string; + targetRef?: string; + }): Promise<{ + project: any; + sourceAST: CanonicalSchemaAST; + targetAST: CanonicalSchemaAST; + diff: SchemaDiffResult; + }> { + const { projectId, mode = "live-vs-snapshot", sourceRef, targetRef } = params; + if (!projectId) { + throw new RpcInputError("BAD_REQUEST", "Missing projectId"); + } + + const project = await projectStoreInstance.getProject(projectId); + if (!project) { + throw new RpcInputError("NOT_FOUND", "Project not found"); + } + + const schemaRelPath = "schema/schema.json"; + + if (mode === "live-vs-snapshot") { + if (!project.databaseId) { + throw new RpcInputError("BAD_REQUEST", "Project has no database ID"); + } + const savedSchema = await projectStoreInstance.getSchema(projectId); + if (!savedSchema) { + throw new RpcInputError("NOT_FOUND", "No saved schema snapshot found for project"); } - const project = await projectStoreInstance.getProject(projectId); - if (!project) { - return this.rpc.sendError(id, { code: "NOT_FOUND", message: "Project not found" }); + const sourceAST = normalizeSchemaFile(savedSchema); + const targetAST = await introspectLiveCanonicalAST( + this.dbService, + this.queryExecutor, + project.databaseId, + ); + const diff = diffSchemas(sourceAST, targetAST, { + sourceLabel: "snapshot", + targetLabel: "live", + }); + return { project, sourceAST, targetAST, diff }; + } + + if (mode === "live-vs-ref") { + if (!project.databaseId) { + throw new RpcInputError("BAD_REQUEST", "Project has no database ID"); + } + if (!targetRef) { + throw new RpcInputError("BAD_REQUEST", "Missing targetRef"); } - const schemaRelPath = "schema/schema.json"; + const projectDir = await projectStoreInstance.resolveProjectDir(projectId); + const rawRefJson = await gitServiceInstance.getFileAtRef( + projectDir, + schemaRelPath, + targetRef, + ); + if (rawRefJson === null) { + throw new RpcInputError("NOT_FOUND", `Schema snapshot not found at ref ${targetRef}`); + } - if (mode === "live-vs-snapshot") { - if (!project.databaseId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Project has no database ID", - }); - } - const savedSchema = await projectStoreInstance.getSchema(projectId); - if (!savedSchema) { - return this.rpc.sendError(id, { - code: "NOT_FOUND", - message: "No saved schema snapshot found for project", - }); - } + const sourceAST = await introspectLiveCanonicalAST( + this.dbService, + this.queryExecutor, + project.databaseId, + ); + const targetAST = normalizeSchemaFile(JSON.parse(rawRefJson)); + const diff = diffSchemas(sourceAST, targetAST, { + sourceLabel: "live", + targetLabel: targetRef, + }); + return { project, sourceAST, targetAST, diff }; + } - const snapshotAST = normalizeSchemaFile(savedSchema); - const liveAST = await introspectLiveCanonicalAST( - this.dbService, - this.queryExecutor, - project.databaseId, - ); - const result = diffSchemas(snapshotAST, liveAST, { - sourceLabel: "snapshot", - targetLabel: "live", - }); - return this.rpc.sendResponse(id, { ok: true, data: result }); + if (mode === "ref-vs-ref") { + if (!sourceRef || !targetRef) { + throw new RpcInputError("BAD_REQUEST", "Missing sourceRef or targetRef"); } - if (mode === "live-vs-ref") { - if (!project.databaseId) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Project has no database ID", - }); - } - if (!targetRef) { - return this.rpc.sendError(id, { code: "BAD_REQUEST", message: "Missing targetRef" }); - } + const projectDir = await projectStoreInstance.resolveProjectDir(projectId); + const [rawSourceJson, rawTargetJson] = await Promise.all([ + gitServiceInstance.getFileAtRef(projectDir, schemaRelPath, sourceRef), + gitServiceInstance.getFileAtRef(projectDir, schemaRelPath, targetRef), + ]); - const projectDir = await projectStoreInstance.resolveProjectDir(projectId); - const rawRefJson = await gitServiceInstance.getFileAtRef( - projectDir, - schemaRelPath, - targetRef, - ); - if (rawRefJson === null) { - return this.rpc.sendError(id, { - code: "NOT_FOUND", - message: `Schema snapshot not found at ref ${targetRef}`, - }); - } + if (rawSourceJson === null) { + throw new RpcInputError("NOT_FOUND", `Schema snapshot not found at ref ${sourceRef}`); + } + if (rawTargetJson === null) { + throw new RpcInputError("NOT_FOUND", `Schema snapshot not found at ref ${targetRef}`); + } - const refAST = normalizeSchemaFile(JSON.parse(rawRefJson)); - const liveAST = await introspectLiveCanonicalAST( - this.dbService, - this.queryExecutor, - project.databaseId, - ); - const result = diffSchemas(liveAST, refAST, { - sourceLabel: "live", - targetLabel: targetRef, + const sourceAST = normalizeSchemaFile(JSON.parse(rawSourceJson)); + const targetAST = normalizeSchemaFile(JSON.parse(rawTargetJson)); + const diff = diffSchemas(sourceAST, targetAST, { + sourceLabel: sourceRef, + targetLabel: targetRef, + }); + return { project, sourceAST, targetAST, diff }; + } + + throw new RpcInputError("BAD_REQUEST", `Unsupported diff mode: ${mode}`); + } + + /** + * Compare two schema sources (live-vs-snapshot, live-vs-ref, ref-vs-ref) + * and return a structured SchemaDiffResult. + */ + async handleDiffSchema(params: any, id: number | string) { + try { + const { diff } = await this.resolveSchemaDiff(params || {}); + return this.rpc.sendResponse(id, { ok: true, data: diff }); + } catch (e: any) { + this.sendMigrationError(id, e, "migration.diffSchema failed"); + } + } + + /** + * Generate a SQL (.sql) or MongoDB (.mql.json) migration from a schema diff, + * optionally persisting it to the project's migrations directory. + */ + async handleGenerateFromDiff(params: any, id: number | string) { + try { + const { + projectId, + mode = "live-vs-snapshot", + sourceRef, + targetRef, + name, + save = false, + acceptRenameIds, + confirmDestructive = false, + concurrentIndexes = false, + } = params || {}; + + const { project, sourceAST, targetAST, diff } = await this.resolveSchemaDiff({ + projectId, + mode, + sourceRef, + targetRef, + }); + + const generated = generateMigrationFromDiff(diff, sourceAST, targetAST, { + name, + acceptRenameIds, + concurrentIndexes, + }); + + if (!save) { + return this.rpc.sendResponse(id, { + ok: true, + data: { + format: generated.format, + filename: generated.filename, + version: generated.version, + content: generated.content, + upSql: generated.upSql, + downSql: generated.downSql, + manifest: generated.manifest, + warnings: generated.warnings, + hasDestructive: generated.hasDestructive, + diff, + }, }); - return this.rpc.sendResponse(id, { ok: true, data: result }); } - if (mode === "ref-vs-ref") { - if (!sourceRef || !targetRef) { - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: "Missing sourceRef or targetRef", - }); - } + if (generated.hasDestructive && !confirmDestructive) { + return this.rpc.sendError(id, { + code: "DESTRUCTIVE_CONFIRMATION_REQUIRED", + message: + "Generated migration contains destructive operations. Pass confirmDestructive: true to save.", + }); + } - const projectDir = await projectStoreInstance.resolveProjectDir(projectId); - const [rawSourceJson, rawTargetJson] = await Promise.all([ - gitServiceInstance.getFileAtRef(projectDir, schemaRelPath, sourceRef), - gitServiceInstance.getFileAtRef(projectDir, schemaRelPath, targetRef), - ]); + const migrationsDir = + diff.dialect === "mongodb" + ? resolveMongoMigrationsDir(await projectStoreInstance.resolveProjectDir(projectId)) + : await projectStoreInstance.resolveMigrationsDir(project.databaseId || projectId); - if (rawSourceJson === null) { - return this.rpc.sendError(id, { - code: "NOT_FOUND", - message: `Schema snapshot not found at ref ${sourceRef}`, - }); - } - if (rawTargetJson === null) { - return this.rpc.sendError(id, { - code: "NOT_FOUND", - message: `Schema snapshot not found at ref ${targetRef}`, - }); - } + const filepath = path.join(migrationsDir, generated.filename); + validateSafeFilePath(filepath, migrationsDir); - const sourceAST = normalizeSchemaFile(JSON.parse(rawSourceJson)); - const targetAST = normalizeSchemaFile(JSON.parse(rawTargetJson)); - const result = diffSchemas(sourceAST, targetAST, { - sourceLabel: sourceRef, - targetLabel: targetRef, - }); - return this.rpc.sendResponse(id, { ok: true, data: result }); + if (!fs.existsSync(migrationsDir)) { + fs.mkdirSync(migrationsDir, { recursive: true }); } + fs.writeFileSync(filepath, generated.content, "utf8"); - return this.rpc.sendError(id, { - code: "BAD_REQUEST", - message: `Unsupported diff mode: ${mode}`, + return this.rpc.sendResponse(id, { + ok: true, + data: { + version: generated.version, + filename: generated.filename, + filepath, + format: generated.format, + content: generated.content, + upSql: generated.upSql, + downSql: generated.downSql, + manifest: generated.manifest, + warnings: generated.warnings, + hasDestructive: generated.hasDestructive, + diff, + }, }); } catch (e: any) { - this.sendMigrationError(id, e, "migration.diffSchema failed"); + this.sendMigrationError(id, e, "migration.generateFromDiff failed"); } } } diff --git a/bridge/src/jsonRpcHandler.ts b/bridge/src/jsonRpcHandler.ts index bb821d7d..4f94c8c9 100644 --- a/bridge/src/jsonRpcHandler.ts +++ b/bridge/src/jsonRpcHandler.ts @@ -199,6 +199,9 @@ export function registerDbHandlers(rpc: Rpc, logger: Logger, sessions: SessionMa rpcRegister(rpc, "migration.delete", (p, id) => migrationHandlers.handleDeleteMigration(p, id)); rpcRegister(rpc, "migration.getSQL", (p, id) => migrationHandlers.handleGetMigrationSQL(p, id)); rpcRegister(rpc, "migration.diffSchema", (p, id) => migrationHandlers.handleDiffSchema(p, id)); + rpcRegister(rpc, "migration.generateFromDiff", (p, id) => + migrationHandlers.handleGenerateFromDiff(p, id), + ); // ========================================== // STATISTICS HANDLERS diff --git a/bridge/src/services/migrationGenerator.ts b/bridge/src/services/migrationGenerator.ts new file mode 100644 index 00000000..bc001bdd --- /dev/null +++ b/bridge/src/services/migrationGenerator.ts @@ -0,0 +1,995 @@ +/** + * Migration Generator Service + * + * Converts a SchemaDiffResult + source/target CanonicalSchemaASTs into either + * a RelWave SQL migration file (-- +up / -- +down) or a MongoDB declarative + * migration manifest (.mql.json). + */ + +import type { + CanonicalCheck, + CanonicalCollection, + CanonicalColumn, + CanonicalDialect, + CanonicalEnum, + CanonicalForeignKey, + CanonicalIndex, + CanonicalMongoIndex, + CanonicalSchemaAST, + CanonicalTable, + CanonicalView, + SchemaDiffItem, + SchemaDiffResult, +} from "../types/schemaDiff"; +import type { MongoMigrationManifest, MongoMigrationStep } from "../types/mongoMigration"; +import { generateMigrationVersion } from "../utils/migrationGenerator"; + +export interface GenerateMigrationOptions { + name?: string; + version?: string; + acceptRenameIds?: string[]; + concurrentIndexes?: boolean; +} + +export interface GeneratedMigrationResult { + format: "sql" | "mql"; + filename: string; + version: string; + content: string; + upSql?: string; + downSql?: string; + manifest?: MongoMigrationManifest; + warnings: string[]; + hasDestructive: boolean; +} + +/** + * Safely slugifies a migration name to `[a-zA-Z0-9_-]+`, falling back to `"schema_diff"`. + */ +export function slugifyMigrationName(name?: string): string { + if (!name) return "schema_diff"; + const slug = name + .trim() + .replace(/[^a-zA-Z0-9_-]+/g, "_") + .replace(/^_+|_+$/g, ""); + return slug || "schema_diff"; +} + +function quoteIdent(name: string, dialect: CanonicalDialect): string { + if (dialect === "mysql" || dialect === "mariadb" || dialect === "clickhouse") { + return `\`${name.replace(/`/g, "``")}\``; + } + return `"${name.replace(/"/g, '""')}"`; +} + +function qualifyName(schema: string | undefined, name: string, dialect: CanonicalDialect): string { + if (dialect === "sqlite" || !schema) { + return quoteIdent(name, dialect); + } + return `${quoteIdent(schema, dialect)}.${quoteIdent(name, dialect)}`; +} + +function buildColumnDefinition(col: CanonicalColumn, dialect: CanonicalDialect): string { + let def = `${quoteIdent(col.name, dialect)} ${col.type}`; + if (!col.nullable && dialect !== "clickhouse") { + def += " NOT NULL"; + } + if (col.defaultValue !== null && col.defaultValue !== undefined) { + def += ` DEFAULT ${col.defaultValue}`; + } + if (col.isPrimaryKey && dialect !== "clickhouse") { + def += " PRIMARY KEY"; + } + if (col.isUnique && !col.isPrimaryKey && dialect !== "clickhouse") { + def += " UNIQUE"; + } + return def; +} + +function buildCreateTableSql( + schema: string | undefined, + table: CanonicalTable, + dialect: CanonicalDialect, + overrideTableName?: string, +): string { + const tableRef = qualifyName(schema, overrideTableName || table.name, dialect); + const defs = table.columns.map((c) => ` ${buildColumnDefinition(c, dialect)}`); + + if (dialect !== "clickhouse") { + for (const chk of table.checks || []) { + defs.push(` CONSTRAINT ${quoteIdent(chk.name, dialect)} CHECK (${chk.expression})`); + } + for (const fk of table.foreignKeys || []) { + const targetRef = qualifyName(fk.referencedSchema || schema, fk.referencedTable, dialect); + const srcCols = fk.columns.map((c) => quoteIdent(c, dialect)).join(", "); + const tgtCols = fk.referencedColumns.map((c) => quoteIdent(c, dialect)).join(", "); + const onDelete = fk.onDelete || "NO ACTION"; + const onUpdate = fk.onUpdate || "NO ACTION"; + defs.push( + ` CONSTRAINT ${quoteIdent(fk.name, dialect)} FOREIGN KEY (${srcCols}) REFERENCES ${targetRef}(${tgtCols}) ON DELETE ${onDelete} ON UPDATE ${onUpdate}`, + ); + } + return `CREATE TABLE ${tableRef} (\n${defs.join(",\n")}\n);`; + } + + const pkCols = table.columns + .filter((c) => c.isPrimaryKey) + .map((c) => quoteIdent(c.name, dialect)); + const orderClause = pkCols.length > 0 ? pkCols.join(", ") : "tuple()"; + return `CREATE TABLE ${tableRef} (\n${defs.join(",\n")}\n) ENGINE = MergeTree() ORDER BY (${orderClause});`; +} + +function buildCreateIndexSql( + schema: string | undefined, + tableName: string, + idx: CanonicalIndex, + dialect: CanonicalDialect, + concurrent?: boolean, +): string { + const tableRef = qualifyName(schema, tableName, dialect); + const cols = idx.columns.map((c) => quoteIdent(c, dialect)).join(", "); + const uniqueStr = idx.unique ? "UNIQUE " : ""; + const concurrentStr = dialect === "postgresql" && concurrent ? "CONCURRENTLY " : ""; + const whereClause = idx.partial ? ` WHERE ${idx.partial}` : ""; + return `CREATE ${uniqueStr}INDEX ${concurrentStr}${quoteIdent(idx.name, dialect)} ON ${tableRef} (${cols})${whereClause};`; +} + +function buildDropIndexSql( + schema: string | undefined, + tableName: string, + indexName: string, + dialect: CanonicalDialect, + concurrent?: boolean, +): string { + if (dialect === "mysql" || dialect === "mariadb") { + return `DROP INDEX ${quoteIdent(indexName, dialect)} ON ${qualifyName(schema, tableName, dialect)};`; + } + const concurrentStr = dialect === "postgresql" && concurrent ? "CONCURRENTLY " : ""; + return `DROP INDEX ${concurrentStr}IF EXISTS ${qualifyName(schema, indexName, dialect)};`; +} + +function buildAddFkSql( + schema: string | undefined, + tableName: string, + fk: CanonicalForeignKey, + dialect: CanonicalDialect, +): string { + const tableRef = qualifyName(schema, tableName, dialect); + const targetRef = qualifyName(fk.referencedSchema || schema, fk.referencedTable, dialect); + const srcCols = fk.columns.map((c) => quoteIdent(c, dialect)).join(", "); + const tgtCols = fk.referencedColumns.map((c) => quoteIdent(c, dialect)).join(", "); + return `ALTER TABLE ${tableRef} ADD CONSTRAINT ${quoteIdent(fk.name, dialect)} FOREIGN KEY (${srcCols}) REFERENCES ${targetRef}(${tgtCols}) ON DELETE ${fk.onDelete || "NO ACTION"} ON UPDATE ${fk.onUpdate || "NO ACTION"};`; +} + +function buildDropFkSql( + schema: string | undefined, + tableName: string, + fkName: string, + dialect: CanonicalDialect, +): string { + const tableRef = qualifyName(schema, tableName, dialect); + if (dialect === "mysql" || dialect === "mariadb") { + return `ALTER TABLE ${tableRef} DROP FOREIGN KEY ${quoteIdent(fkName, dialect)};`; + } + return `ALTER TABLE ${tableRef} DROP CONSTRAINT IF EXISTS ${quoteIdent(fkName, dialect)};`; +} + +function buildAddCheckSql( + schema: string | undefined, + tableName: string, + chk: CanonicalCheck, + dialect: CanonicalDialect, +): string { + const tableRef = qualifyName(schema, tableName, dialect); + return `ALTER TABLE ${tableRef} ADD CONSTRAINT ${quoteIdent(chk.name, dialect)} CHECK (${chk.expression});`; +} + +function buildDropCheckSql( + schema: string | undefined, + tableName: string, + chkName: string, + dialect: CanonicalDialect, +): string { + const tableRef = qualifyName(schema, tableName, dialect); + if (dialect === "mysql" || dialect === "mariadb") { + return `ALTER TABLE ${tableRef} DROP CHECK ${quoteIdent(chkName, dialect)};`; + } + return `ALTER TABLE ${tableRef} DROP CONSTRAINT IF EXISTS ${quoteIdent(chkName, dialect)};`; +} + +function findTableInAst( + ast: CanonicalSchemaAST, + schemaName: string | undefined, + tableName: string, +): CanonicalTable | undefined { + const schema = ast.schemas.find((s) => (schemaName ? s.name === schemaName : true)); + return schema?.tables.find((t) => t.name === tableName); +} + +/** + * Emits the SQLite 12-step table rebuild sequence to transform `fromTable` into `toTable`. + */ +function buildSqliteRebuildSql( + schema: string | undefined, + fromTable: CanonicalTable, + toTable: CanonicalTable, + columnRenames: Map = new Map(), +): string { + const tempName = `__relwave_new_${toTable.name}`; + const tempRef = quoteIdent(tempName, "sqlite"); + const origRef = quoteIdent(toTable.name, "sqlite"); + const fromCols = new Set(fromTable.columns.map((c) => c.name)); + + const targetColIdents: string[] = []; + const sourceColIdents: string[] = []; + for (const col of toTable.columns) { + const mappedOld = columnRenames.get(col.name); + if (mappedOld && fromCols.has(mappedOld)) { + targetColIdents.push(quoteIdent(col.name, "sqlite")); + sourceColIdents.push(quoteIdent(mappedOld, "sqlite")); + } else if (fromCols.has(col.name)) { + targetColIdents.push(quoteIdent(col.name, "sqlite")); + sourceColIdents.push(quoteIdent(col.name, "sqlite")); + } + } + + const lines: string[] = [ + "PRAGMA foreign_keys=OFF;", + "BEGIN;", + buildCreateTableSql(schema, toTable, "sqlite", tempName), + ]; + + if (targetColIdents.length > 0) { + lines.push( + `INSERT INTO ${tempRef} (${targetColIdents.join(", ")}) SELECT ${sourceColIdents.join(", ")} FROM ${quoteIdent(fromTable.name, "sqlite")};`, + ); + } + + lines.push(`DROP TABLE ${quoteIdent(fromTable.name, "sqlite")};`); + lines.push(`ALTER TABLE ${tempRef} RENAME TO ${origRef};`); + + for (const idx of toTable.indexes || []) { + lines.push(buildCreateIndexSql(schema, toTable.name, idx, "sqlite")); + } + + lines.push("PRAGMA foreign_key_check;"); + lines.push("COMMIT;"); + lines.push("PRAGMA foreign_keys=ON;"); + return lines.join("\n"); +} + +function buildColumnModifyStatements( + tableRef: string, + before: CanonicalColumn, + after: CanonicalColumn, + dialect: CanonicalDialect, +): string[] { + const colIdent = quoteIdent(after.name, dialect); + if (dialect === "postgresql" || dialect === "duckdb") { + const stmts: string[] = []; + if (before.type !== after.type) { + stmts.push(`ALTER TABLE ${tableRef} ALTER COLUMN ${colIdent} TYPE ${after.type};`); + } + if (before.nullable !== after.nullable) { + stmts.push( + `ALTER TABLE ${tableRef} ALTER COLUMN ${colIdent} ${after.nullable ? "DROP NOT NULL" : "SET NOT NULL"};`, + ); + } + if (before.defaultValue !== after.defaultValue) { + if (after.defaultValue !== null && after.defaultValue !== undefined) { + stmts.push( + `ALTER TABLE ${tableRef} ALTER COLUMN ${colIdent} SET DEFAULT ${after.defaultValue};`, + ); + } else { + stmts.push(`ALTER TABLE ${tableRef} ALTER COLUMN ${colIdent} DROP DEFAULT;`); + } + } + return stmts; + } + + if (dialect === "clickhouse") { + const defClause = + after.defaultValue !== null && after.defaultValue !== undefined + ? ` DEFAULT ${after.defaultValue}` + : ""; + return [`ALTER TABLE ${tableRef} MODIFY COLUMN ${colIdent} ${after.type}${defClause};`]; + } + + // MySQL / MariaDB + const nullClause = after.nullable ? " NULL" : " NOT NULL"; + const defClause = + after.defaultValue !== null && after.defaultValue !== undefined + ? ` DEFAULT ${after.defaultValue}` + : ""; + return [ + `ALTER TABLE ${tableRef} MODIFY COLUMN ${colIdent} ${after.type}${nullClause}${defClause};`, + ]; +} + +function collectAcceptedRenamePairs( + items: SchemaDiffItem[], + acceptIds: Set, +): { + consumedIds: Set; + tableRenames: Array<{ drop: SchemaDiffItem; add: SchemaDiffItem }>; + columnRenames: Array<{ drop: SchemaDiffItem; add: SchemaDiffItem }>; +} { + const consumedIds = new Set(); + const tableRenames: Array<{ drop: SchemaDiffItem; add: SchemaDiffItem }> = []; + const columnRenames: Array<{ drop: SchemaDiffItem; add: SchemaDiffItem }> = []; + + for (const item of items) { + if (!item.renameCandidate || consumedIds.has(item.id)) continue; + + if (item.type === "TABLE_DROPPED" || item.type === "TABLE_ADDED") { + const isDrop = item.type === "TABLE_DROPPED"; + const peerType = isDrop ? "TABLE_ADDED" : "TABLE_DROPPED"; + const peer = items.find( + (other) => + other.type === peerType && + (other.schema || "") === (item.schema || "") && + other.tableOrCollection === item.renameCandidate && + other.renameCandidate === item.tableOrCollection, + ); + if (peer && (acceptIds.has(item.id) || acceptIds.has(peer.id))) { + consumedIds.add(item.id); + consumedIds.add(peer.id); + tableRenames.push(isDrop ? { drop: item, add: peer } : { drop: peer, add: item }); + } + } else if (item.type === "COLUMN_DROPPED" || item.type === "COLUMN_ADDED") { + const isDrop = item.type === "COLUMN_DROPPED"; + const peerType = isDrop ? "COLUMN_ADDED" : "COLUMN_DROPPED"; + const peer = items.find( + (other) => + other.type === peerType && + (other.schema || "") === (item.schema || "") && + other.tableOrCollection === item.tableOrCollection && + other.objectName === item.renameCandidate && + other.renameCandidate === item.objectName, + ); + if (peer && (acceptIds.has(item.id) || acceptIds.has(peer.id))) { + consumedIds.add(item.id); + consumedIds.add(peer.id); + columnRenames.push(isDrop ? { drop: item, add: peer } : { drop: peer, add: item }); + } + } + } + + return { consumedIds, tableRenames, columnRenames }; +} + +const SQLITE_REBUILD_TRIGGER_TYPES = new Set([ + "COLUMN_MODIFIED", + "COLUMN_DROPPED", + "FK_ADDED", + "FK_DROPPED", + "FK_MODIFIED", + "CHECK_ADDED", + "CHECK_DROPPED", + "CHECK_MODIFIED", +]); + +function generateSqlMigration( + diff: SchemaDiffResult, + sourceAst: CanonicalSchemaAST, + targetAst: CanonicalSchemaAST, + dialect: CanonicalDialect, + version: string, + slug: string, + options: GenerateMigrationOptions, +): GeneratedMigrationResult { + const acceptIds = new Set(options.acceptRenameIds || []); + const concurrent = Boolean(options.concurrentIndexes); + const warnings: string[] = []; + let hasDestructive = false; + + const upStmts: string[] = []; + const downStmts: string[] = []; + + const pushDestructive = (item: SchemaDiffItem, upSql: string, downSql?: string) => { + hasDestructive = true; + warnings.push(item.details); + upStmts.push(`-- WARNING: Destructive operation: ${item.details}\n${upSql}`); + if (downSql) downStmts.push(downSql); + }; + + const { consumedIds, tableRenames, columnRenames } = collectAcceptedRenamePairs( + diff.items, + acceptIds, + ); + + // Table renames + for (const { drop, add } of tableRenames) { + const oldRef = qualifyName(drop.schema, drop.tableOrCollection, dialect); + const newRef = qualifyName(add.schema, add.tableOrCollection, dialect); + if (dialect === "mysql" || dialect === "mariadb" || dialect === "clickhouse") { + upStmts.push(`RENAME TABLE ${oldRef} TO ${newRef};`); + downStmts.push(`RENAME TABLE ${newRef} TO ${oldRef};`); + } else { + upStmts.push( + `ALTER TABLE ${oldRef} RENAME TO ${quoteIdent(add.tableOrCollection, dialect)};`, + ); + downStmts.push( + `ALTER TABLE ${newRef} RENAME TO ${quoteIdent(drop.tableOrCollection, dialect)};`, + ); + } + } + + // SQLite: group table-rebuild triggers by table + const sqliteRebuildTables = new Set(); + if (dialect === "sqlite") { + for (const item of diff.items) { + if (consumedIds.has(item.id)) continue; + if (SQLITE_REBUILD_TRIGGER_TYPES.has(item.type)) { + sqliteRebuildTables.add(`${item.schema || ""}:${item.tableOrCollection}`); + } + } + + for (const key of sqliteRebuildTables) { + const [schema, tableName] = key.split(":"); + const srcTable = findTableInAst(sourceAst, schema || undefined, tableName); + const tgtTable = findTableInAst(targetAst, schema || undefined, tableName); + if (!srcTable || !tgtTable) continue; + + const tableItems = diff.items.filter( + (i) => + !consumedIds.has(i.id) && + (i.schema || "") === schema && + i.tableOrCollection === tableName && + (SQLITE_REBUILD_TRIGGER_TYPES.has(i.type) || + i.type === "COLUMN_ADDED" || + i.type === "INDEX_ADDED" || + i.type === "INDEX_DROPPED" || + i.type === "INDEX_MODIFIED"), + ); + + const renameMapUp = new Map(); + const renameMapDown = new Map(); + for (const pair of columnRenames) { + if ((pair.drop.schema || "") === schema && pair.drop.tableOrCollection === tableName) { + const oldCol = pair.drop.objectName!; + const newCol = pair.add.objectName!; + renameMapUp.set(newCol, oldCol); + renameMapDown.set(oldCol, newCol); + } + } + + const destructiveItems = tableItems.filter((i) => i.severity === "destructive"); + const upRebuild = buildSqliteRebuildSql(schema || undefined, srcTable, tgtTable, renameMapUp); + const downRebuild = buildSqliteRebuildSql( + schema || undefined, + tgtTable, + srcTable, + renameMapDown, + ); + + if (destructiveItems.length > 0) { + hasDestructive = true; + const details = destructiveItems.map((d) => d.details).join("; "); + warnings.push(...destructiveItems.map((d) => d.details)); + upStmts.push(`-- WARNING: Destructive operation: ${details}\n${upRebuild}`); + } else { + upStmts.push(upRebuild); + } + downStmts.push(downRebuild); + + for (const i of tableItems) { + consumedIds.add(i.id); + } + } + } + + // Remaining column renames (non-rebuilt tables) + for (const { drop, add } of columnRenames) { + const key = `${drop.schema || ""}:${drop.tableOrCollection}`; + if (sqliteRebuildTables.has(key)) continue; + const tableRef = qualifyName(drop.schema, drop.tableOrCollection, dialect); + const oldCol = quoteIdent(drop.objectName!, dialect); + const newCol = quoteIdent(add.objectName!, dialect); + upStmts.push(`ALTER TABLE ${tableRef} RENAME COLUMN ${oldCol} TO ${newCol};`); + downStmts.push(`ALTER TABLE ${tableRef} RENAME COLUMN ${newCol} TO ${oldCol};`); + } + + for (const item of diff.items) { + if (consumedIds.has(item.id)) continue; + + switch (item.type) { + case "SCHEMA_ADDED": { + const schemaIdent = quoteIdent(item.tableOrCollection, dialect); + if (dialect === "sqlite") break; + if (dialect === "mysql" || dialect === "mariadb") { + upStmts.push(`CREATE DATABASE IF NOT EXISTS ${schemaIdent};`); + downStmts.push(`DROP DATABASE IF EXISTS ${schemaIdent};`); + } else { + upStmts.push(`CREATE SCHEMA IF NOT EXISTS ${schemaIdent};`); + downStmts.push(`DROP SCHEMA IF EXISTS ${schemaIdent} CASCADE;`); + } + break; + } + case "SCHEMA_DROPPED": { + const schemaIdent = quoteIdent(item.tableOrCollection, dialect); + if (dialect === "sqlite") break; + const dropSql = + dialect === "mysql" || dialect === "mariadb" || dialect === "clickhouse" + ? `DROP DATABASE IF EXISTS ${schemaIdent};` + : `DROP SCHEMA IF EXISTS ${schemaIdent} CASCADE;`; + pushDestructive( + item, + dropSql, + `-- WARNING: Cannot automatically reverse DROP SCHEMA ${item.tableOrCollection}.`, + ); + break; + } + case "ENUM_ADDED": { + if (dialect !== "postgresql") break; + const after = item.after as CanonicalEnum; + const enumRef = qualifyName(item.schema, after.name, dialect); + const vals = after.values.map((v) => `'${v.replace(/'/g, "''")}'`).join(", "); + upStmts.push(`CREATE TYPE ${enumRef} AS ENUM (${vals});`); + downStmts.push(`DROP TYPE IF EXISTS ${enumRef};`); + break; + } + case "ENUM_DROPPED": { + if (dialect !== "postgresql") break; + const before = item.before as CanonicalEnum | undefined; + const enumRef = qualifyName(item.schema, item.tableOrCollection, dialect); + upStmts.push(`DROP TYPE IF EXISTS ${enumRef};`); + if (before) { + const vals = before.values.map((v) => `'${v.replace(/'/g, "''")}'`).join(", "); + downStmts.push(`CREATE TYPE ${enumRef} AS ENUM (${vals});`); + } + break; + } + case "ENUM_MODIFIED": { + if (dialect !== "postgresql") break; + const before = item.before as CanonicalEnum; + const after = item.after as CanonicalEnum; + const enumRef = qualifyName(item.schema, after.name, dialect); + const beforeSet = new Set(before.values); + for (const val of after.values) { + if (!beforeSet.has(val)) { + upStmts.push( + `ALTER TYPE ${enumRef} ADD VALUE IF NOT EXISTS '${val.replace(/'/g, "''")}';`, + ); + } + } + const removed = before.values.filter((v) => !after.values.includes(v)); + if (removed.length > 0) { + const msg = `PostgreSQL does not support removing enum values (${removed.join(", ")}) from ${after.name}`; + warnings.push(msg); + upStmts.push(`-- WARNING: ${msg}`); + } + downStmts.push( + `-- WARNING: PostgreSQL enum value additions cannot be automatically reversed for ${after.name}.`, + ); + break; + } + case "TABLE_ADDED": { + const table = item.after as CanonicalTable; + const tableRef = qualifyName(item.schema, table.name, dialect); + const createSql = buildCreateTableSql(item.schema, table, dialect); + const indexSqls = (table.indexes || []).map((idx) => + buildCreateIndexSql(item.schema, table.name, idx, dialect, false), + ); + upStmts.push([createSql, ...indexSqls].join("\n")); + downStmts.push(`DROP TABLE IF EXISTS ${tableRef};`); + break; + } + case "TABLE_DROPPED": { + const tableRef = qualifyName(item.schema, item.tableOrCollection, dialect); + const before = item.before as CanonicalTable | undefined; + const downSql = before + ? [ + buildCreateTableSql(item.schema, before, dialect), + ...(before.indexes || []).map((idx) => + buildCreateIndexSql(item.schema, before.name, idx, dialect, false), + ), + ].join("\n") + : `-- WARNING: Cannot automatically reverse DROP TABLE ${item.tableOrCollection}.`; + pushDestructive(item, `DROP TABLE IF EXISTS ${tableRef};`, downSql); + break; + } + case "COLUMN_ADDED": { + const after = item.after as CanonicalColumn; + const tableRef = qualifyName(item.schema, item.tableOrCollection, dialect); + upStmts.push( + `ALTER TABLE ${tableRef} ADD COLUMN ${buildColumnDefinition(after, dialect)};`, + ); + downStmts.push(`ALTER TABLE ${tableRef} DROP COLUMN ${quoteIdent(after.name, dialect)};`); + break; + } + case "COLUMN_DROPPED": { + const before = item.before as CanonicalColumn | undefined; + const tableRef = qualifyName(item.schema, item.tableOrCollection, dialect); + const colName = item.objectName || before?.name || ""; + const downSql = before + ? `ALTER TABLE ${tableRef} ADD COLUMN ${buildColumnDefinition(before, dialect)};` + : `-- WARNING: Cannot automatically reverse DROP COLUMN ${colName}.`; + pushDestructive( + item, + `ALTER TABLE ${tableRef} DROP COLUMN ${quoteIdent(colName, dialect)};`, + downSql, + ); + break; + } + case "COLUMN_MODIFIED": { + const before = item.before as CanonicalColumn; + const after = item.after as CanonicalColumn; + const tableRef = qualifyName(item.schema, item.tableOrCollection, dialect); + const upSql = buildColumnModifyStatements(tableRef, before, after, dialect).join("\n"); + const downSql = buildColumnModifyStatements(tableRef, after, before, dialect).join("\n"); + if (item.severity === "destructive") { + pushDestructive(item, upSql, downSql); + } else { + if (upSql) upStmts.push(upSql); + if (downSql) downStmts.push(downSql); + } + break; + } + case "INDEX_ADDED": { + const after = item.after as CanonicalIndex; + upStmts.push( + buildCreateIndexSql(item.schema, item.tableOrCollection, after, dialect, concurrent), + ); + downStmts.push( + buildDropIndexSql(item.schema, item.tableOrCollection, after.name, dialect, concurrent), + ); + break; + } + case "INDEX_DROPPED": { + const before = item.before as CanonicalIndex | undefined; + const idxName = item.objectName || before?.name || ""; + upStmts.push( + buildDropIndexSql(item.schema, item.tableOrCollection, idxName, dialect, concurrent), + ); + if (before) { + downStmts.push( + buildCreateIndexSql(item.schema, item.tableOrCollection, before, dialect, concurrent), + ); + } + break; + } + case "INDEX_MODIFIED": { + const before = item.before as CanonicalIndex; + const after = item.after as CanonicalIndex; + upStmts.push( + [ + buildDropIndexSql( + item.schema, + item.tableOrCollection, + before.name, + dialect, + concurrent, + ), + buildCreateIndexSql(item.schema, item.tableOrCollection, after, dialect, concurrent), + ].join("\n"), + ); + downStmts.push( + [ + buildDropIndexSql(item.schema, item.tableOrCollection, after.name, dialect, concurrent), + buildCreateIndexSql(item.schema, item.tableOrCollection, before, dialect, concurrent), + ].join("\n"), + ); + break; + } + case "FK_ADDED": { + const after = item.after as CanonicalForeignKey; + upStmts.push(buildAddFkSql(item.schema, item.tableOrCollection, after, dialect)); + downStmts.push(buildDropFkSql(item.schema, item.tableOrCollection, after.name, dialect)); + break; + } + case "FK_DROPPED": { + const before = item.before as CanonicalForeignKey | undefined; + const fkName = item.objectName || before?.name || ""; + upStmts.push(buildDropFkSql(item.schema, item.tableOrCollection, fkName, dialect)); + if (before) { + downStmts.push(buildAddFkSql(item.schema, item.tableOrCollection, before, dialect)); + } + break; + } + case "FK_MODIFIED": { + const before = item.before as CanonicalForeignKey; + const after = item.after as CanonicalForeignKey; + upStmts.push( + [ + buildDropFkSql(item.schema, item.tableOrCollection, before.name, dialect), + buildAddFkSql(item.schema, item.tableOrCollection, after, dialect), + ].join("\n"), + ); + downStmts.push( + [ + buildDropFkSql(item.schema, item.tableOrCollection, after.name, dialect), + buildAddFkSql(item.schema, item.tableOrCollection, before, dialect), + ].join("\n"), + ); + break; + } + case "CHECK_ADDED": { + const after = item.after as CanonicalCheck; + upStmts.push(buildAddCheckSql(item.schema, item.tableOrCollection, after, dialect)); + downStmts.push(buildDropCheckSql(item.schema, item.tableOrCollection, after.name, dialect)); + break; + } + case "CHECK_DROPPED": { + const before = item.before as CanonicalCheck | undefined; + const chkName = item.objectName || before?.name || ""; + upStmts.push(buildDropCheckSql(item.schema, item.tableOrCollection, chkName, dialect)); + if (before) { + downStmts.push(buildAddCheckSql(item.schema, item.tableOrCollection, before, dialect)); + } + break; + } + case "CHECK_MODIFIED": { + const before = item.before as CanonicalCheck; + const after = item.after as CanonicalCheck; + upStmts.push( + [ + buildDropCheckSql(item.schema, item.tableOrCollection, before.name, dialect), + buildAddCheckSql(item.schema, item.tableOrCollection, after, dialect), + ].join("\n"), + ); + downStmts.push( + [ + buildDropCheckSql(item.schema, item.tableOrCollection, after.name, dialect), + buildAddCheckSql(item.schema, item.tableOrCollection, before, dialect), + ].join("\n"), + ); + break; + } + case "VIEW_ADDED": { + const after = item.after as CanonicalView; + const viewRef = qualifyName(item.schema, after.name, dialect); + upStmts.push(`CREATE VIEW ${viewRef} AS ${after.definition};`); + downStmts.push(`DROP VIEW IF EXISTS ${viewRef};`); + break; + } + case "VIEW_DROPPED": { + const before = item.before as CanonicalView | undefined; + const viewRef = qualifyName(item.schema, item.tableOrCollection, dialect); + upStmts.push(`DROP VIEW IF EXISTS ${viewRef};`); + if (before) { + downStmts.push(`CREATE VIEW ${viewRef} AS ${before.definition};`); + } + break; + } + case "VIEW_MODIFIED": { + const before = item.before as CanonicalView; + const after = item.after as CanonicalView; + const viewRef = qualifyName(item.schema, after.name, dialect); + if (dialect === "sqlite") { + upStmts.push( + `DROP VIEW IF EXISTS ${viewRef};\nCREATE VIEW ${viewRef} AS ${after.definition};`, + ); + downStmts.push( + `DROP VIEW IF EXISTS ${viewRef};\nCREATE VIEW ${viewRef} AS ${before.definition};`, + ); + } else { + upStmts.push(`CREATE OR REPLACE VIEW ${viewRef} AS ${after.definition};`); + downStmts.push(`CREATE OR REPLACE VIEW ${viewRef} AS ${before.definition};`); + } + break; + } + } + } + + const filename = `${version}_${slug}.sql`; + const upSql = upStmts.length > 0 ? upStmts.join("\n\n") : "-- No changes detected"; + const downSql = + downStmts.length > 0 ? [...downStmts].reverse().join("\n\n") : "-- No rollback statements"; + const content = `-- ${filename}\n\n-- +up\n${upSql}\n\n-- +down\n${downSql}\n`; + + return { + format: "sql", + filename, + version, + content, + upSql, + downSql, + warnings, + hasDestructive, + }; +} + +function toMongoCreateIndexStep(collection: string, idx: CanonicalMongoIndex): MongoMigrationStep { + return { + type: "createIndex", + collection, + key: idx.key as Record, + options: { + name: idx.name, + unique: idx.unique, + sparse: idx.sparse, + ...(idx.expireAfterSeconds !== undefined + ? { expireAfterSeconds: idx.expireAfterSeconds } + : {}), + ...(idx.partialFilterExpression + ? { partialFilterExpression: idx.partialFilterExpression } + : {}), + }, + }; +} + +function generateMongoMigration( + diff: SchemaDiffResult, + version: string, + slug: string, +): GeneratedMigrationResult { + const up: MongoMigrationStep[] = []; + const down: MongoMigrationStep[] = []; + const warnings: string[] = []; + let hasDestructive = false; + let allowIrreversible = false; + + for (const item of diff.items) { + const coll = item.tableOrCollection; + + switch (item.type) { + case "COLLECTION_ADDED": { + const after = item.after as CanonicalCollection; + const options: Record = {}; + if (after.validator) options.validator = after.validator; + if (after.validationLevel) options.validationLevel = after.validationLevel; + if (after.validationAction) options.validationAction = after.validationAction; + + up.push({ + type: "createCollection", + collection: coll, + ...(Object.keys(options).length > 0 ? { options: options as any } : {}), + }); + for (const idx of after.indexes || []) { + if (idx.name === "_id_") continue; + up.push(toMongoCreateIndexStep(coll, idx)); + } + down.push({ type: "dropCollection", collection: coll }); + break; + } + case "COLLECTION_DROPPED": { + hasDestructive = true; + allowIrreversible = true; + warnings.push(`Destructive operation: ${item.details}`); + up.push({ type: "dropCollection", collection: coll }); + const before = item.before as CanonicalCollection | undefined; + if (before) { + down.push({ type: "createCollection", collection: coll }); + } + break; + } + case "MONGO_INDEX_ADDED": { + const after = item.after as CanonicalMongoIndex; + up.push(toMongoCreateIndexStep(coll, after)); + down.push({ type: "dropIndex", collection: coll, indexName: after.name }); + break; + } + case "MONGO_INDEX_DROPPED": { + const before = item.before as CanonicalMongoIndex | undefined; + const indexName = item.objectName || before?.name || ""; + warnings.push(`Dropping index '${indexName}' on collection '${coll}'`); + up.push({ type: "dropIndex", collection: coll, indexName }); + if (before) { + down.push(toMongoCreateIndexStep(coll, before)); + } + break; + } + case "MONGO_INDEX_MODIFIED": { + const before = item.before as CanonicalMongoIndex; + const after = item.after as CanonicalMongoIndex; + warnings.push( + `Modifying index '${after.name}' on collection '${coll}' will drop and recreate it`, + ); + up.push({ type: "dropIndex", collection: coll, indexName: before.name }); + up.push(toMongoCreateIndexStep(coll, after)); + down.push({ type: "dropIndex", collection: coll, indexName: after.name }); + down.push(toMongoCreateIndexStep(coll, before)); + break; + } + case "VALIDATOR_ADDED": { + const after = item.after as { + validator: Record; + validationLevel?: string | null; + validationAction?: string | null; + }; + up.push({ + type: "setValidator", + collection: coll, + validator: after.validator, + ...(after.validationLevel ? { validationLevel: after.validationLevel as any } : {}), + ...(after.validationAction ? { validationAction: after.validationAction as any } : {}), + }); + down.push({ type: "setValidator", collection: coll, validator: {} }); + break; + } + case "VALIDATOR_DROPPED": { + const before = item.before as { + validator: Record; + validationLevel?: string | null; + validationAction?: string | null; + }; + warnings.push(`Dropping schema validator on collection '${coll}'`); + up.push({ type: "setValidator", collection: coll, validator: {} }); + if (before?.validator) { + down.push({ + type: "setValidator", + collection: coll, + validator: before.validator, + ...(before.validationLevel ? { validationLevel: before.validationLevel as any } : {}), + ...(before.validationAction + ? { validationAction: before.validationAction as any } + : {}), + }); + } + break; + } + case "VALIDATOR_MODIFIED": { + const before = item.before as { + validator: Record; + validationLevel?: string | null; + validationAction?: string | null; + }; + const after = item.after as { + validator: Record; + validationLevel?: string | null; + validationAction?: string | null; + }; + up.push({ + type: "setValidator", + collection: coll, + validator: after.validator || {}, + ...(after.validationLevel ? { validationLevel: after.validationLevel as any } : {}), + ...(after.validationAction ? { validationAction: after.validationAction as any } : {}), + }); + down.push({ + type: "setValidator", + collection: coll, + validator: before.validator || {}, + ...(before.validationLevel ? { validationLevel: before.validationLevel as any } : {}), + ...(before.validationAction ? { validationAction: before.validationAction as any } : {}), + }); + break; + } + } + } + + const manifest: MongoMigrationManifest = { + version, + id: `${version}_${slug}`, + name: slug, + description: `Generated from schema diff (${diff.sourceLabel} -> ${diff.targetLabel})`, + ...(allowIrreversible ? { allowIrreversible: true } : {}), + up, + down: [...down].reverse(), + }; + + const filename = `${version}_${slug}.mql.json`; + const content = JSON.stringify(manifest, null, 2); + + return { + format: "mql", + filename, + version, + content, + manifest, + warnings, + hasDestructive, + }; +} + +/** + * Generate a SQL or MongoDB migration artifact from a SchemaDiffResult and its + * source/target CanonicalSchemaASTs. + */ +export function generateMigrationFromDiff( + diff: SchemaDiffResult, + sourceAst: CanonicalSchemaAST, + targetAst: CanonicalSchemaAST, + options: GenerateMigrationOptions = {}, +): GeneratedMigrationResult { + const version = options.version || generateMigrationVersion(); + const slug = slugifyMigrationName(options.name); + const dialect = diff.dialect || targetAst.dialect || sourceAst.dialect; + + if (dialect === "mongodb") { + return generateMongoMigration(diff, version, slug); + } + + return generateSqlMigration(diff, sourceAst, targetAst, dialect, version, slug, options); +} diff --git a/src/__tests__/schemaDiffMigration.test.ts b/src/__tests__/schemaDiffMigration.test.ts new file mode 100644 index 00000000..d9032e9e --- /dev/null +++ b/src/__tests__/schemaDiffMigration.test.ts @@ -0,0 +1,188 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { + canSaveGeneratedMigration, + filterDiffItems, + groupDiffItemsByTarget, + hasRequiredRefs, + toggleRenameCandidateId, +} from "../features/database/hooks/useSchemaDiffMigration"; +import type { GeneratedMigrationResult, SchemaDiffItem } from "../services/bridge/migration"; + +const SAMPLE_ITEMS: SchemaDiffItem[] = [ + { + id: "item-1", + type: "COLUMN_ADDED", + severity: "safe", + schema: "public", + tableOrCollection: "users", + objectName: "bio", + details: "Added nullable column bio (text)", + }, + { + id: "item-2", + type: "COLUMN_MODIFIED", + severity: "warning", + schema: "public", + tableOrCollection: "users", + objectName: "email", + details: "Changed varchar(100) -> varchar(255)", + }, + { + id: "item-3", + type: "COLUMN_DROPPED", + severity: "destructive", + schema: "public", + tableOrCollection: "orders", + objectName: "legacy_ref", + details: "Dropped column legacy_ref", + renameCandidate: "external_ref", + }, +]; + +function makeGenerated( + overrides: Partial = {}, +): GeneratedMigrationResult { + return { + filename: "20261128_test.sql", + format: "sql", + content: "-- +goose Up\nALTER TABLE users ADD COLUMN bio text;", + upSql: "ALTER TABLE users ADD COLUMN bio text;", + downSql: "ALTER TABLE users DROP COLUMN bio;", + warnings: [], + hasDestructive: false, + diff: { + hasChanges: true, + sourceLabel: "snapshot", + targetLabel: "live", + dialect: "postgresql", + summary: { total: 1, safe: 1, warning: 0, destructive: 0 }, + items: [SAMPLE_ITEMS[0]], + }, + ...overrides, + }; +} + +describe("schemaDiffMigration pure helpers", () => { + it("filters diff items by severity", () => { + assert.equal(filterDiffItems(SAMPLE_ITEMS, "all").length, 3); + assert.deepEqual( + filterDiffItems(SAMPLE_ITEMS, "safe").map((i) => i.id), + ["item-1"], + ); + assert.deepEqual( + filterDiffItems(SAMPLE_ITEMS, "warning").map((i) => i.id), + ["item-2"], + ); + assert.deepEqual( + filterDiffItems(SAMPLE_ITEMS, "destructive").map((i) => i.id), + ["item-3"], + ); + }); + + it("groups diff items by schema and table/collection", () => { + const grouped = groupDiffItemsByTarget(SAMPLE_ITEMS); + assert.equal(grouped.length, 2); + assert.equal(grouped[0].target, "public.users"); + assert.equal(grouped[0].items.length, 2); + assert.equal(grouped[1].target, "public.orders"); + assert.equal(grouped[1].items.length, 1); + + const mongoGrouped = groupDiffItemsByTarget([ + { + id: "m-1", + type: "MONGO_INDEX_ADDED", + severity: "safe", + tableOrCollection: "sessions", + objectName: "ttl_idx", + details: "Added TTL index", + }, + ]); + assert.equal(mongoGrouped[0].target, "sessions"); + }); + + it("toggles rename candidate IDs idempotently", () => { + const step1 = toggleRenameCandidateId([], "item-3"); + assert.deepEqual(step1, ["item-3"]); + + const step2 = toggleRenameCandidateId(step1, "item-4"); + assert.deepEqual(step2, ["item-3", "item-4"]); + + const step3 = toggleRenameCandidateId(step2, "item-3"); + assert.deepEqual(step3, ["item-4"]); + }); + + it("gates saving when destructive changes are unconfirmed, empty, or saving", () => { + assert.equal( + canSaveGeneratedMigration({ + generated: null, + confirmDestructive: true, + isSaving: false, + }), + false, + ); + + assert.equal( + canSaveGeneratedMigration({ + generated: makeGenerated({ + diff: { + hasChanges: false, + sourceLabel: "snapshot", + targetLabel: "live", + dialect: "postgresql", + summary: { total: 0, safe: 0, warning: 0, destructive: 0 }, + items: [], + }, + }), + confirmDestructive: true, + isSaving: false, + }), + false, + ); + + assert.equal( + canSaveGeneratedMigration({ + generated: makeGenerated({ hasDestructive: true }), + confirmDestructive: false, + isSaving: false, + }), + false, + ); + + assert.equal( + canSaveGeneratedMigration({ + generated: makeGenerated({ hasDestructive: true }), + confirmDestructive: true, + isSaving: false, + }), + true, + ); + + assert.equal( + canSaveGeneratedMigration({ + generated: makeGenerated({ hasDestructive: false }), + confirmDestructive: false, + isSaving: true, + }), + false, + ); + + assert.equal( + canSaveGeneratedMigration({ + generated: makeGenerated({ hasDestructive: false }), + confirmDestructive: false, + isSaving: false, + }), + true, + ); + }); + + it("validates required Git refs per diff mode", () => { + assert.equal(hasRequiredRefs("live-vs-snapshot", "", ""), true); + assert.equal(hasRequiredRefs("live-vs-ref", "", ""), false); + assert.equal(hasRequiredRefs("live-vs-ref", "", "main"), true); + assert.equal(hasRequiredRefs("ref-vs-ref", "main", ""), false); + assert.equal(hasRequiredRefs("ref-vs-ref", "", "feature"), false); + assert.equal(hasRequiredRefs("ref-vs-ref", "main", "feature"), true); + }); +}); diff --git a/src/features/database/components/MigrationsPanel.tsx b/src/features/database/components/MigrationsPanel.tsx index f30157e9..21f57f3b 100644 --- a/src/features/database/components/MigrationsPanel.tsx +++ b/src/features/database/components/MigrationsPanel.tsx @@ -1,3 +1,4 @@ +import { useState } from "react"; import { CheckCircle2, Clock, @@ -8,6 +9,7 @@ import { Trash2, Eye, RefreshCw, + Sparkles, } from "lucide-react"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Badge } from "@/components/ui/badge"; @@ -18,14 +20,27 @@ import { useMigrationsPanel } from "../hooks/useMigrationsPanel"; import { cn } from "@/lib/utils"; import { formatTimestamp } from "@/lib/utils"; import { MigrationsPanelLoadingState } from "@/features/database/components/MigrationsPanelLoadingState"; +import { useProjectByDatabaseId, useProjectDir } from "@/features/project/hooks/useProjectQueries"; +import { SchemaDiffMigrationDialog } from "./SchemaDiffMigrationDialog"; interface MigrationsPanelProps { migrations: MigrationsData; baselined: boolean; dbId: string; + projectId?: string; } -export default function MigrationsPanel({ migrations, baselined, dbId }: MigrationsPanelProps) { +export default function MigrationsPanel({ + migrations, + baselined, + dbId, + projectId: projectIdProp, +}: MigrationsPanelProps) { + const [diffDialogOpen, setDiffDialogOpen] = useState(false); + const { data: project } = useProjectByDatabaseId(projectIdProp ? undefined : dbId); + const effectiveProjectId = projectIdProp ?? project?.id; + const { data: projectDir } = useProjectDir(effectiveProjectId); + const { allMigrations, applied, @@ -49,23 +64,40 @@ export default function MigrationsPanel({ migrations, baselined, dbId }: Migrati <> -
+
Migrations - - {baselined ? "Baselined" : "Not Baselined"} - - +
+ + {baselined ? "Baselined" : "Not Baselined"} + + + +

Schema version control and migration status @@ -144,6 +176,13 @@ export default function MigrationsPanel({ migrations, baselined, dbId }: Migrati

)} + ); } diff --git a/src/features/database/components/SchemaDiffMigrationDialog.tsx b/src/features/database/components/SchemaDiffMigrationDialog.tsx new file mode 100644 index 00000000..13d4aa58 --- /dev/null +++ b/src/features/database/components/SchemaDiffMigrationDialog.tsx @@ -0,0 +1,573 @@ +import { useMemo } from "react"; +import { + AlertTriangle, + CheckCircle2, + FileCode2, + GitCommitHorizontal, + Info, + Loader2, + RefreshCw, + Save, + ShieldAlert, + Sparkles, +} from "lucide-react"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { ScrollArea } from "@/components/ui/scroll-area"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { Input } from "@/components/ui/input"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Label } from "@/components/ui/label"; +import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; +import { useGitBranches } from "@/features/git/hooks/useGitQueries"; +import type { DiffSeverity, SchemaDiffMode } from "@/services/bridge/migration"; +import { + useSchemaDiffMigration, + type DiffSeverityFilter, +} from "@/features/database/hooks/useSchemaDiffMigration"; +import { cn } from "@/lib/utils"; + +export interface SchemaDiffMigrationDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + projectId?: string; + dbId?: string; + projectDir?: string | null; + onSaved?: () => void; +} + +const SEVERITY_BADGE_STYLES: Record = { + safe: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/30", + warning: "bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/30", + destructive: "bg-destructive/10 text-destructive border-destructive/30", +}; + +function SeverityIcon({ severity }: { severity: DiffSeverity }) { + if (severity === "safe") { + return ; + } + if (severity === "warning") { + return ; + } + return ; +} + +/** + * Interactive dialog for inspecting schema diffs and previewing/saving generated SQL or MQL migrations. + */ +export function SchemaDiffMigrationDialog({ + open, + onOpenChange, + projectId, + dbId, + projectDir, + onSaved, +}: SchemaDiffMigrationDialogProps) { + const { data: branches } = useGitBranches(open && projectDir ? projectDir : undefined); + const branchNames = useMemo(() => (branches ?? []).map((b) => b.name), [branches]); + + const { + mode, + setMode, + sourceRef, + setSourceRef, + targetRef, + setTargetRef, + migrationName, + setMigrationName, + acceptRenameIds, + toggleRenameId, + confirmDestructive, + setConfirmDestructive, + concurrentIndexes, + toggleConcurrentIndexes, + severityFilter, + setSeverityFilter, + diffResult, + groupedItems, + generated, + isScanning, + isGeneratingPreview, + isSaving, + error, + canSave, + runDiff, + saveMigration, + } = useSchemaDiffMigration({ + projectId, + dbId, + projectDir, + open, + onSaved: () => { + onSaved?.(); + onOpenChange(false); + }, + }); + + const handleModeChange = (nextMode: SchemaDiffMode) => { + setMode(nextMode); + if (nextMode === "live-vs-ref" && !targetRef && branchNames.length > 0) { + const current = branches?.find((b) => b.current)?.name ?? branchNames[0]; + setTargetRef(current); + } + if (nextMode === "ref-vs-ref" && branchNames.length > 0) { + if (!sourceRef) setSourceRef(branchNames[0]); + if (!targetRef) { + const current = branches?.find((b) => b.current)?.name ?? branchNames[0]; + setTargetRef(current); + } + } + }; + + const renderRefSelector = ( + label: string, + value: string, + onChange: (val: string) => void, + placeholder: string, + ) => { + if (branchNames.length > 0) { + return ( +
+ + +
+ ); + } + + return ( +
+ + onChange(e.target.value)} + placeholder={placeholder} + className="h-8 text-xs font-mono" + /> +
+ ); + }; + + const formattedManifest = useMemo(() => { + if (!generated) return ""; + if (generated.manifest) { + return JSON.stringify(generated.manifest, null, 2); + } + return generated.content; + }, [generated]); + + return ( + + + + + + Generate Migration from Schema Diff + {diffResult?.dialect && ( + + {diffResult.dialect} + + )} + + + Compare schemas, review change severity and rename suggestions, and preview the + generated migration before saving. + + + + {/* Top Configuration Bar */} +
+
+ + +
+ + {mode === "ref-vs-ref" && + renderRefSelector("Source Ref", sourceRef, setSourceRef, "e.g. main")} + + {mode !== "live-vs-snapshot" && + renderRefSelector( + mode === "live-vs-ref" ? "Target Branch / Ref" : "Target Ref", + targetRef, + setTargetRef, + "e.g. HEAD", + )} + +
+ + setMigrationName(e.target.value)} + placeholder="e.g. add_user_profile_index" + className="h-8 text-xs" + /> +
+ + +
+ + {/* Error Banner */} + {error && ( +
+ + + Diff / Generation Error + {error} + +
+ )} + + {/* Main Split Inspector & Preview */} +
+ {/* Left Pane: Diff Inspector */} +
+
+
+ + Safe: {diffResult?.summary.safe ?? 0} + + + Warning: {diffResult?.summary.warning ?? 0} + + + Destructive: {diffResult?.summary.destructive ?? 0} + +
+ +
+ {(["all", "safe", "warning", "destructive"] as DiffSeverityFilter[]).map((f) => ( + + ))} +
+
+ + +
+ {!projectId ? ( +
+ No project linked to this database connection. +
+ ) : isScanning ? ( +
+ + Scanning schema differences... +
+ ) : !diffResult ? ( +
+ Select comparison targets and click Re-scan to inspect schema differences. +
+ ) : !diffResult.hasChanges ? ( +
+ +

Schemas are in sync

+

+ No differences detected between {diffResult.sourceLabel} and{" "} + {diffResult.targetLabel}. +

+
+ ) : groupedItems.length === 0 ? ( +
+ No diff items match the "{severityFilter}" severity filter. +
+ ) : ( + groupedItems.map((group) => ( +
+
+ + {group.target} + + + {group.items.length} + +
+
+ {group.items.map((item) => { + const isRenameAccepted = acceptRenameIds.includes(item.id); + return ( +
+
+
+ + + {item.objectName ?? item.tableOrCollection} + + + {item.type} + +
+ + {item.severity} + +
+ +

+ {item.details} +

+ + {item.renameCandidate && ( + + )} +
+ ); + })} +
+
+ )) + )} +
+
+
+ + {/* Right Pane: Migration Preview */} +
+
+
+ + + {generated?.filename ?? "Migration Preview"} + +
+ + {generated?.format === "sql" && ( + + )} +
+ + {generated && generated.warnings.length > 0 && ( +
+ + + Warnings + + {generated.warnings.map((w, idx) => ( +
• {w}
+ ))} +
+
+
+ )} + +
+ {isGeneratingPreview ? ( +
+ + Generating migration preview... +
+ ) : !generated ? ( +
+ {diffResult && !diffResult.hasChanges + ? "No migration needed." + : "Migration SQL / MQL preview will appear here."} +
+ ) : generated.format === "sql" ? ( + + + + +up SQL + + + +down SQL + + + Full File + + + + + +
+                        {generated.upSql ?? generated.content}
+                      
+
+
+ + + +
+                        {generated.downSql ?? "-- No down SQL generated"}
+                      
+
+
+ + + +
+                        {generated.content}
+                      
+
+
+
+ ) : ( + +
+                    {formattedManifest}
+                  
+
+ )} +
+
+
+ + {/* Footer */} + +
+ {generated?.hasDestructive && ( + + )} +
+ +
+ + + + + {projectDir && ( + + )} +
+
+
+
+ ); +} diff --git a/src/features/database/hooks/useSchemaDiffMigration.ts b/src/features/database/hooks/useSchemaDiffMigration.ts new file mode 100644 index 00000000..801c23e1 --- /dev/null +++ b/src/features/database/hooks/useSchemaDiffMigration.ts @@ -0,0 +1,367 @@ +import { useState, useCallback, useEffect, useMemo, useRef } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { toast } from "sonner"; +import { + migrationService, + type DiffSeverity, + type GeneratedMigrationResult, + type SchemaDiffItem, + type SchemaDiffMode, + type SchemaDiffResult, +} from "@/services/bridge/migration"; +import { gitService } from "@/services/bridge/git"; +import { gitKeys } from "@/features/git/hooks/useGitQueries"; +import { useInvalidateCache } from "@/features/project/hooks/useDbQueries"; + +export type DiffSeverityFilter = "all" | DiffSeverity; + +export interface GroupedDiffItems { + target: string; + items: SchemaDiffItem[]; +} + +/** + * Filter diff items by severity level. + */ +export function filterDiffItems( + items: SchemaDiffItem[], + severityFilter: DiffSeverityFilter, +): SchemaDiffItem[] { + if (severityFilter === "all") return items; + return items.filter((item) => item.severity === severityFilter); +} + +/** + * Group diff items by `schema.tableOrCollection` (or `tableOrCollection`). + */ +export function groupDiffItemsByTarget(items: SchemaDiffItem[]): GroupedDiffItems[] { + const groups = new Map(); + for (const item of items) { + const key = item.schema ? `${item.schema}.${item.tableOrCollection}` : item.tableOrCollection; + const list = groups.get(key); + if (list) { + list.push(item); + } else { + groups.set(key, [item]); + } + } + return Array.from(groups.entries()).map(([target, groupItems]) => ({ + target, + items: groupItems, + })); +} + +/** + * Toggle a rename candidate item ID in the accepted rename list. + */ +export function toggleRenameCandidateId(currentIds: string[], itemId: string): string[] { + if (currentIds.includes(itemId)) { + return currentIds.filter((id) => id !== itemId); + } + return [...currentIds, itemId]; +} + +/** + * Determine whether saving the generated migration is allowed. + */ +export function canSaveGeneratedMigration(params: { + generated: GeneratedMigrationResult | null; + confirmDestructive: boolean; + isSaving: boolean; +}): boolean { + const { generated, confirmDestructive, isSaving } = params; + if (!generated || isSaving) return false; + if (!generated.diff.hasChanges) return false; + if (generated.hasDestructive && !confirmDestructive) return false; + return true; +} + +/** + * Determine whether the selected diff mode has all required Git refs. + */ +export function hasRequiredRefs( + mode: SchemaDiffMode, + sourceRef: string, + targetRef: string, +): boolean { + if (mode === "live-vs-snapshot") return true; + if (mode === "live-vs-ref") return targetRef.trim().length > 0; + return sourceRef.trim().length > 0 && targetRef.trim().length > 0; +} + +export interface UseSchemaDiffMigrationOptions { + projectId?: string; + dbId?: string; + projectDir?: string | null; + open?: boolean; + onSaved?: () => void; +} + +/** + * Manage schema diff scanning, migration preview generation, rename acceptance, + * destructive confirmation gating, and saving/staging migrations. + */ +export function useSchemaDiffMigration({ + projectId, + dbId, + projectDir, + open = false, + onSaved, +}: UseSchemaDiffMigrationOptions) { + const queryClient = useQueryClient(); + const { invalidateDatabase } = useInvalidateCache(); + + const [mode, setMode] = useState("live-vs-snapshot"); + const [sourceRef, setSourceRef] = useState(""); + const [targetRef, setTargetRef] = useState(""); + const [migrationName, setMigrationName] = useState(""); + const [acceptRenameIds, setAcceptRenameIds] = useState([]); + const [confirmDestructive, setConfirmDestructive] = useState(false); + const [concurrentIndexes, setConcurrentIndexes] = useState(false); + const [severityFilter, setSeverityFilter] = useState("all"); + + const [diffResult, setDiffResult] = useState(null); + const [generated, setGenerated] = useState(null); + const [isScanning, setIsScanning] = useState(false); + const [isGeneratingPreview, setIsGeneratingPreview] = useState(false); + const [isSaving, setIsSaving] = useState(false); + const [error, setError] = useState(null); + + const migrationNameRef = useRef(migrationName); + migrationNameRef.current = migrationName; + const acceptRenameIdsRef = useRef(acceptRenameIds); + acceptRenameIdsRef.current = acceptRenameIds; + const concurrentIndexesRef = useRef(concurrentIndexes); + concurrentIndexesRef.current = concurrentIndexes; + + const generatePreview = useCallback( + async (opts?: { + mode?: SchemaDiffMode; + sourceRef?: string; + targetRef?: string; + name?: string; + renameIds?: string[]; + concurrent?: boolean; + }) => { + if (!projectId) return; + const activeMode = opts?.mode ?? mode; + const activeSource = opts?.sourceRef ?? sourceRef; + const activeTarget = opts?.targetRef ?? targetRef; + if (!hasRequiredRefs(activeMode, activeSource, activeTarget)) return; + + setIsGeneratingPreview(true); + setError(null); + try { + const preview = await migrationService.generateFromDiff({ + projectId, + mode: activeMode, + sourceRef: activeMode === "ref-vs-ref" ? activeSource.trim() : undefined, + targetRef: activeMode !== "live-vs-snapshot" ? activeTarget.trim() : undefined, + name: (opts?.name ?? migrationNameRef.current).trim() || undefined, + save: false, + acceptRenameIds: opts?.renameIds ?? acceptRenameIdsRef.current, + confirmDestructive: true, + concurrentIndexes: opts?.concurrent ?? concurrentIndexesRef.current, + }); + setGenerated(preview); + } catch (err: any) { + setError(err?.message ?? "Failed to generate migration preview"); + } finally { + setIsGeneratingPreview(false); + } + }, + [projectId, mode, sourceRef, targetRef], + ); + + const runDiff = useCallback( + async (opts?: { mode?: SchemaDiffMode; sourceRef?: string; targetRef?: string }) => { + if (!projectId) return; + const activeMode = opts?.mode ?? mode; + const activeSource = opts?.sourceRef ?? sourceRef; + const activeTarget = opts?.targetRef ?? targetRef; + + if (!hasRequiredRefs(activeMode, activeSource, activeTarget)) { + setDiffResult(null); + setGenerated(null); + return; + } + + setIsScanning(true); + setError(null); + setConfirmDestructive(false); + setAcceptRenameIds([]); + + try { + const diff = await migrationService.diffSchema({ + projectId, + mode: activeMode, + sourceRef: activeMode === "ref-vs-ref" ? activeSource.trim() : undefined, + targetRef: activeMode !== "live-vs-snapshot" ? activeTarget.trim() : undefined, + detectRenames: true, + }); + setDiffResult(diff); + + if (diff.hasChanges) { + await generatePreview({ + mode: activeMode, + sourceRef: activeSource, + targetRef: activeTarget, + renameIds: [], + }); + } else { + setGenerated(null); + } + } catch (err: any) { + setDiffResult(null); + setGenerated(null); + setError(err?.message ?? "Failed to diff schema"); + } finally { + setIsScanning(false); + } + }, + [projectId, mode, sourceRef, targetRef, generatePreview], + ); + + // Auto-scan when dialog opens in live-vs-snapshot mode (or when refs are already set) + useEffect(() => { + if (!open || !projectId) return; + if (hasRequiredRefs(mode, sourceRef, targetRef)) { + void runDiff(); + } + // Intentionally trigger on dialog open or mode/ref changes + }, [open, projectId, mode, sourceRef, targetRef, runDiff]); + + const toggleRenameId = useCallback( + (itemId: string) => { + const nextIds = toggleRenameCandidateId(acceptRenameIds, itemId); + setAcceptRenameIds(nextIds); + void generatePreview({ renameIds: nextIds }); + }, + [acceptRenameIds, generatePreview], + ); + + const toggleConcurrentIndexes = useCallback( + (checked: boolean) => { + setConcurrentIndexes(checked); + if (diffResult?.hasChanges) { + void generatePreview({ concurrent: checked }); + } + }, + [diffResult?.hasChanges, generatePreview], + ); + + const filteredItems = useMemo( + () => filterDiffItems(diffResult?.items ?? [], severityFilter), + [diffResult?.items, severityFilter], + ); + + const groupedItems = useMemo(() => groupDiffItemsByTarget(filteredItems), [filteredItems]); + + const canSave = useMemo( + () => + canSaveGeneratedMigration({ + generated, + confirmDestructive, + isSaving, + }), + [generated, confirmDestructive, isSaving], + ); + + const saveMigration = useCallback( + async (stageInGit = false) => { + if (!projectId || !canSave) return; + + setIsSaving(true); + setError(null); + try { + const saved = await migrationService.generateFromDiff({ + projectId, + mode, + sourceRef: mode === "ref-vs-ref" ? sourceRef.trim() : undefined, + targetRef: mode !== "live-vs-snapshot" ? targetRef.trim() : undefined, + name: migrationName.trim() || undefined, + save: true, + acceptRenameIds, + confirmDestructive, + concurrentIndexes, + }); + + if (stageInGit && projectDir && saved.filepath) { + await gitService.gitStage(projectDir, [saved.filepath]); + await Promise.all([ + queryClient.invalidateQueries({ queryKey: gitKeys.status(projectDir) }), + queryClient.invalidateQueries({ queryKey: gitKeys.changes(projectDir) }), + ]); + } + + if (dbId) { + await invalidateDatabase(dbId); + await queryClient.invalidateQueries({ queryKey: ["mongoMigrations", dbId] }); + } else { + await queryClient.invalidateQueries({ queryKey: ["projects"] }); + } + + toast.success( + stageInGit ? "Migration saved & staged in Git" : "Migration saved successfully", + { + description: saved.filename, + }, + ); + onSaved?.(); + } catch (err: any) { + const message = err?.message ?? "Failed to save migration"; + setError(message); + toast.error("Failed to save migration", { description: message }); + } finally { + setIsSaving(false); + } + }, + [ + projectId, + canSave, + mode, + sourceRef, + targetRef, + migrationName, + acceptRenameIds, + confirmDestructive, + concurrentIndexes, + projectDir, + dbId, + queryClient, + invalidateDatabase, + onSaved, + ], + ); + + return { + mode, + setMode, + sourceRef, + setSourceRef, + targetRef, + setTargetRef, + migrationName, + setMigrationName, + acceptRenameIds, + toggleRenameId, + confirmDestructive, + setConfirmDestructive, + concurrentIndexes, + toggleConcurrentIndexes, + severityFilter, + setSeverityFilter, + diffResult, + filteredItems, + groupedItems, + generated, + isScanning, + isGeneratingPreview, + isSaving, + error, + canSave, + runDiff, + generatePreview, + saveMigration, + }; +} diff --git a/src/features/git/components/GitStatusPanel.tsx b/src/features/git/components/GitStatusPanel.tsx index 7c31208b..37adc8a7 100644 --- a/src/features/git/components/GitStatusPanel.tsx +++ b/src/features/git/components/GitStatusPanel.tsx @@ -13,6 +13,7 @@ import { Eye, RotateCcw, RefreshCw, + Sparkles, } from "lucide-react"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; @@ -32,6 +33,8 @@ import { toast } from "sonner"; import type { GitFileChange } from "@/features/git/types"; import { gitService } from "@/services/bridge/git"; import { projectService } from "@/services/bridge/project"; +import { useProject } from "@/features/project/hooks/useProjectQueries"; +import { SchemaDiffMigrationDialog } from "@/features/database/components/SchemaDiffMigrationDialog"; import { GitHistoryGraph } from "./GitHistoryGraph"; import { GitStatusPanelLoadingState } from "./GitStatusPanelLoadingState"; @@ -102,6 +105,8 @@ export default function GitStatusPanel({ projectDir, projectId }: GitStatusPanel const [diffLoading, setDiffLoading] = useState(false); const [syncing, setSyncing] = useState(false); + const [schemaDiffDialogOpen, setSchemaDiffDialogOpen] = useState(false); + const { data: project } = useProject(projectId || undefined); if (!projectDir) { return ( @@ -213,6 +218,15 @@ export default function GitStatusPanel({ projectDir, projectId }: GitStatusPanel Migration Sync
+
); } diff --git a/src/features/mongodb/components/migrations/MongoMigrationsPanel.tsx b/src/features/mongodb/components/migrations/MongoMigrationsPanel.tsx index 7c050cea..c99bc582 100644 --- a/src/features/mongodb/components/migrations/MongoMigrationsPanel.tsx +++ b/src/features/mongodb/components/migrations/MongoMigrationsPanel.tsx @@ -13,8 +13,11 @@ import { Clock, History, CheckCircle2, + Sparkles, } from "lucide-react"; import { useDatabase } from "@/features/project/hooks/useDbQueries"; +import { useProjectByDatabaseId, useProjectDir } from "@/features/project/hooks/useProjectQueries"; +import { SchemaDiffMigrationDialog } from "@/features/database/components/SchemaDiffMigrationDialog"; import { useMongoMigrations } from "../../hooks/useMongoMigrations"; import { MongoMigrationCard, MigrationCardData } from "./MongoMigrationCard"; import { MongoMigrationValidateDialog } from "./MongoMigrationValidateDialog"; @@ -24,12 +27,14 @@ import { MongoMigrationDetailDrawer } from "./MongoMigrationDetailDrawer"; export interface MongoMigrationsPanelProps { dbId: string; + projectId?: string; databaseName?: string; isReadOnly?: boolean; } export function MongoMigrationsPanel({ dbId, + projectId: projectIdProp, databaseName, isReadOnly: isReadOnlyProp, }: MongoMigrationsPanelProps) { @@ -38,9 +43,14 @@ export function MongoMigrationsPanel({ const isReadOnly = isReadOnlyProp ?? Boolean((dbConn as any)?.readOnly || (dbConn as any)?.readonly); + const { data: project } = useProjectByDatabaseId(projectIdProp ? undefined : dbId); + const effectiveProjectId = projectIdProp ?? project?.id; + const { data: projectDir } = useProjectDir(effectiveProjectId); + const { data: migrationsData, isLoading, isFetching, refetch } = useMongoMigrations(dbId); // Dialog and drawer state + const [diffDialogOpen, setDiffDialogOpen] = useState(false); const [validateOpen, setValidateOpen] = useState(false); const [applyTarget, setApplyTarget] = useState<{ id?: string; name?: string } | null>(null); const [rollbackTarget, setRollbackTarget] = useState<{ @@ -245,6 +255,24 @@ export function MongoMigrationsPanel({ Refresh + + + )} + + ); + } + + const summary = data?.summary ?? { + total: 0, + unusedCount: 0, + duplicateCount: 0, + totalSizeBytes: 0, + }; + + return ( + +
+ {/* Header Bar */} +
+
+ {data?.dialect && ( + + {data.dialect} + + )} + + {filteredAndSorted.length} of {summary.total} indexes shown + +
+ + +
+ + {/* Summary Cards */} +
+ + +
+ + Total Indexes +
+
{summary.total}
+
+
+ + + +
+ + Unused Indexes +
+
+ {summary.unusedCount} +
+
+
+ + + +
+ + Duplicate Indexes +
+
+ {summary.duplicateCount} +
+
+
+ + + +
+ + Total Size +
+
+ {formatIndexBytes(summary.totalSizeBytes)} +
+
+
+
+ + {/* Filter Pills & Search */} +
+
+ {FILTER_OPTIONS.map((opt) => { + const active = statusFilter === opt.value; + return ( + + ); + })} +
+ +
+ + setSearchTerm(e.target.value)} + placeholder="Search index, table, column…" + className="h-8 pl-8 text-xs" + /> +
+
+ + {/* Sortable Table */} + {filteredAndSorted.length === 0 ? ( +
+ +

No indexes match the current filter.

+
+ ) : ( +
+ + + + + + + + + + Columns + + + + + + + + + + + + + {filteredAndSorted.map((entry) => { + const redundantTarget = + entry.redundantWith ?? + duplicateMap.get(`${entry.tableOrCollection}:${entry.name}`); + + return ( + + +
+ {entry.name} + {entry.primary && ( + + PK + + )} + {entry.unique && !entry.primary && ( + + UQ + + )} +
+
+ + {entry.schema + ? `${entry.schema}.${entry.tableOrCollection}` + : entry.tableOrCollection} + + + {entry.columns.join(", ") || "—"} + + + {entry.scans !== undefined ? entry.scans.toLocaleString() : "—"} + + + {formatIndexBytes(entry.sizeBytes)} + + + {entry.status === "duplicate" ? ( + + + + + Duplicate + + + +

+ {redundantTarget + ? `Redundant with ${redundantTarget}` + : entry.reason || "Duplicate index definition"} +

+
+
+ ) : entry.status === "unused" ? ( + + + + + Unused + + + +

{entry.reason || "0 index scans recorded"}

+
+
+ ) : ( + + + Healthy + + )} +
+
+ ); + })} +
+
+
+ )} +
+
+ ); +} diff --git a/src/features/database/hooks/useDatabaseDetailPage.ts b/src/features/database/hooks/useDatabaseDetailPage.ts index 0a5755ca..88561996 100644 --- a/src/features/database/hooks/useDatabaseDetailPage.ts +++ b/src/features/database/hooks/useDatabaseDetailPage.ts @@ -19,6 +19,7 @@ export const useDatabaseDetailPage = () => { const [migrationsOpen, setMigrationsOpen] = useState(false); const [chartOpen, setChartOpen] = useState(false); + const [indexHealthOpen, setIndexHealthOpen] = useState(false); const [insertDialogOpen, setInsertDialogOpen] = useState(false); const [sidebarOpen, setSidebarOpen] = useState(true); @@ -31,6 +32,8 @@ export const useDatabaseDetailPage = () => { setMigrationsOpen, chartOpen, setChartOpen, + indexHealthOpen, + setIndexHealthOpen, insertDialogOpen, setInsertDialogOpen, sidebarOpen, diff --git a/src/features/database/hooks/useIndexHealth.ts b/src/features/database/hooks/useIndexHealth.ts new file mode 100644 index 00000000..b994d416 --- /dev/null +++ b/src/features/database/hooks/useIndexHealth.ts @@ -0,0 +1,25 @@ +import { useQuery } from "@tanstack/react-query"; +import { indexHealthService, type IndexHealthReport } from "@/services/bridge/indexHealth"; + +export const indexHealthKeys = { + all: ["indexHealth"] as const, + detail: (dbId: string, tableOrCollection?: string) => + ["indexHealth", dbId, tableOrCollection ?? "all"] as const, +}; + +/** + * Fetches index health diagnostics for a database connection via TanStack Query. + */ +export function useIndexHealth( + dbId: string | undefined, + enabled = true, + tableOrCollection?: string, +) { + return useQuery({ + queryKey: indexHealthKeys.detail(dbId ?? "", tableOrCollection), + queryFn: () => indexHealthService.getIndexHealth(dbId!, tableOrCollection), + enabled: Boolean(dbId) && enabled, + staleTime: 30_000, + retry: 1, + }); +} diff --git a/src/features/workspace/components/ExplainPlanDialog.tsx b/src/features/workspace/components/ExplainPlanDialog.tsx new file mode 100644 index 00000000..ac28bd2c --- /dev/null +++ b/src/features/workspace/components/ExplainPlanDialog.tsx @@ -0,0 +1,562 @@ +import { useState, useEffect, useCallback } from "react"; +import { + Activity, + AlertCircle, + AlertTriangle, + CheckCircle2, + ChevronDown, + ChevronRight, + Clock, + Copy, + Check, + Database, + FileCode2, + Gauge, + Layers, + Loader2, + Play, + RefreshCw, +} from "lucide-react"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { Badge } from "@/components/ui/badge"; +import { Switch } from "@/components/ui/switch"; +import { Label } from "@/components/ui/label"; +import { ScrollArea } from "@/components/ui/scroll-area"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { cn } from "@/lib/utils"; +import { + queryService, + type ExplainBottleneck, + type ExplainPlanNode, + type NormalizedExplainPlan, +} from "@/services/bridge/query"; + +/** + * Computes the selectivity ratio (`rowsReturned / rowsExamined`) for an execution plan. + * Returns `null` when inputs are missing, non-finite, or `rowsExamined <= 0`. + */ +export function computeSelectivityRatio( + rowsExamined?: number, + rowsReturned?: number, +): number | null { + if ( + rowsExamined === undefined || + rowsReturned === undefined || + !Number.isFinite(rowsExamined) || + !Number.isFinite(rowsReturned) || + rowsExamined <= 0 || + rowsReturned < 0 + ) { + return null; + } + return rowsReturned / rowsExamined; +} + +/** + * Recursively counts the total number of operator nodes in an execution plan tree. + */ +export function countPlanNodes(node: ExplainPlanNode | null | undefined): number { + if (!node) return 0; + let total = 1; + if (Array.isArray(node.children)) { + for (const child of node.children) { + total += countPlanNodes(child); + } + } + return total; +} + +/** + * Returns the highest severity level across a list of detected bottlenecks. + */ +export function getWorstSeverity( + bottlenecks: ExplainBottleneck[], +): "critical" | "warning" | "none" { + let worst: "critical" | "warning" | "none" = "none"; + for (const b of bottlenecks) { + if (b.severity === "critical") return "critical"; + if (b.severity === "warning") worst = "warning"; + } + return worst; +} + +function formatMetricMs(value?: number): string { + if (value === undefined || !Number.isFinite(value)) return "—"; + return `${value.toFixed(2)} ms`; +} + +function formatMetricCount(value?: number): string { + if (value === undefined || !Number.isFinite(value)) return "—"; + return value.toLocaleString(); +} + +function formatSelectivity(ratio: number | null): string { + if (ratio === null) return "—"; + return `${(ratio * 100).toFixed(1)}%`; +} + +interface PlanTreeNodeViewProps { + node: ExplainPlanNode; + depth?: number; +} + +function PlanTreeNodeView({ node, depth = 0 }: PlanTreeNodeViewProps) { + const [expanded, setExpanded] = useState(true); + const hasChildren = Array.isArray(node.children) && node.children.length > 0; + const isSeqScan = /seq\s*scan|collscan|full\s*scan|table\s*scan/i.test(node.nodeType); + + return ( +
0 && "ml-5 border-l border-border/50 pl-3")}> +
+
+
+ {hasChildren ? ( + + ) : ( + + )} + + + {node.nodeType} + + + {node.relation && ( + + + {node.relation} + + )} + + {node.indexName && ( + + idx: {node.indexName} + + )} +
+ +
+ {node.cost !== undefined && ( + cost: {node.cost.toFixed(1)} + )} + {node.rows !== undefined && ( + est: {node.rows.toLocaleString()} + )} + {node.actualRows !== undefined && ( + + act: {node.actualRows.toLocaleString()} + + )} + {node.actualTimeMs !== undefined && ( + + {node.actualTimeMs.toFixed(2)} ms + + )} +
+
+ + {node.filter && ( +
+ Filter: {node.filter} +
+ )} +
+ + {hasChildren && expanded && ( +
+ {node.children.map((child, idx) => ( + + ))} +
+ )} +
+ ); +} + +export interface ExplainPlanDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + dbId: string; + sql?: string; + collection?: string; + filter?: unknown; + pipeline?: unknown[]; +} + +/** + * Modal dialog displaying a normalized query execution plan, summary metrics, + * detected bottlenecks, recursive plan tree, and raw JSON output. + */ +export function ExplainPlanDialog({ + open, + onOpenChange, + dbId, + sql, + collection, + filter, + pipeline, +}: ExplainPlanDialogProps) { + const [analyze, setAnalyze] = useState(false); + const [plan, setPlan] = useState(null); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + const [activeTab, setActiveTab] = useState<"tree" | "raw">("tree"); + const [copied, setCopied] = useState(false); + + const runExplain = useCallback( + async (useAnalyze: boolean) => { + if (!dbId || (!sql?.trim() && !collection)) return; + setLoading(true); + setError(null); + try { + const result = await queryService.explainPlan({ + dbId, + sql: sql?.trim(), + collection, + filter, + pipeline, + analyze: useAnalyze, + }); + setPlan(result); + } catch (err: any) { + setError(err?.message ?? String(err)); + setPlan(null); + } finally { + setLoading(false); + } + }, + [dbId, sql, collection, filter, pipeline], + ); + + useEffect(() => { + if (open) { + runExplain(analyze); + } + }, [open, analyze, runExplain]); + + const handleCopyRaw = async () => { + if (!plan) return; + try { + await navigator.clipboard.writeText(JSON.stringify(plan.rawPlan, null, 2)); + setCopied(true); + setTimeout(() => setCopied(false), 1800); + } catch { + // Clipboard API may be unavailable in restricted contexts + } + }; + + const selectivity = plan ? computeSelectivityRatio(plan.rowsExamined, plan.rowsReturned) : null; + const nodeCount = plan ? countPlanNodes(plan.planTree) : 0; + const worstSeverity = plan ? getWorstSeverity(plan.bottlenecks) : "none"; + + const shortQuery = + (sql?.trim() || collection || "").length > 90 + ? (sql?.trim() || collection || "").slice(0, 90).replace(/\s+/g, " ") + "…" + : (sql?.trim() || collection || "").replace(/\s+/g, " "); + + return ( + + + +
+
+ + + Execution Plan + {plan?.dialect && ( + + {plan.dialect} + + )} + + + {shortQuery || "No query selected"} + +
+
+ + {/* Controls Bar: EXPLAIN vs EXPLAIN ANALYZE + Re-run */} +
+
+
+ + +
+ {analyze && ( + + + Executes read-only SELECT queries to measure actual timings + + )} +
+ + +
+
+ + {/* Body */} +
+ {loading ? ( +
+ + + {analyze ? "Running EXPLAIN ANALYZE…" : "Computing execution plan…"} + +
+ ) : error ? ( +
+ +
+

Failed to compute execution plan

+

{error}

+
+
+ ) : plan ? ( + <> + {/* Summary Metrics Bar */} +
+
+
+ + Execution Time +
+
+ {formatMetricMs(plan.executionTimeMs)} +
+
+ +
+
+ + Planning Time +
+
+ {formatMetricMs(plan.planningTimeMs)} +
+
+ +
+
+ + Total Cost +
+
+ {plan.totalCost !== undefined ? plan.totalCost.toFixed(2) : "—"} +
+
+ +
+
+ + Examined / Returned +
+
+ {formatMetricCount(plan.rowsExamined)} / {formatMetricCount(plan.rowsReturned)} +
+
+ +
+
+ + Selectivity +
+
+ {formatSelectivity(selectivity)} +
+
+
+ + {/* Bottleneck Alerts */} + {plan.bottlenecks.length > 0 ? ( +
+ {plan.bottlenecks.map((b, idx) => { + const isCritical = b.severity === "critical"; + return ( +
+ {isCritical ? ( + + ) : ( + + )} +
+
+ + {b.type} + + {b.target && ( + {b.target} + )} +
+

{b.details}

+
+
+ ); + })} +
+ ) : ( +
+ + No execution bottlenecks detected. +
+ )} + + {/* Plan Tree vs Raw JSON Tabs */} + setActiveTab(v as "tree" | "raw")} + className="flex-1 min-h-0 flex flex-col" + > +
+ + + + Plan Tree ({nodeCount} {nodeCount === 1 ? "node" : "nodes"}) + + + + Raw JSON + + + + {worstSeverity !== "none" && ( + + {plan.bottlenecks.length}{" "} + {plan.bottlenecks.length === 1 ? "bottleneck" : "bottlenecks"} + + )} +
+ + + + + + + + + + +
+                      {JSON.stringify(plan.rawPlan, null, 2)}
+                    
+
+
+
+ + ) : null} +
+
+
+ ); +} + +interface ExplainPlanButtonProps { + dbId: string; + sql: string; + disabled?: boolean; +} + +/** + * Toolbar button that opens the `ExplainPlanDialog` for the active SQL query. + */ +export function ExplainPlanButton({ dbId, sql, disabled }: ExplainPlanButtonProps) { + const [open, setOpen] = useState(false); + + return ( + <> + + + + + ); +} diff --git a/src/features/workspace/components/WorkspaceHeader.tsx b/src/features/workspace/components/WorkspaceHeader.tsx index 50a032bc..9129ae03 100644 --- a/src/features/workspace/components/WorkspaceHeader.tsx +++ b/src/features/workspace/components/WorkspaceHeader.tsx @@ -1,6 +1,7 @@ import { Play, Square, Database, Loader2, Sparkles } from "lucide-react"; import { Button } from "@/components/ui/button"; import { ExplainQueryButton } from "./ExplainQueryButton"; +import { ExplainPlanButton } from "./ExplainPlanDialog"; interface WorkspaceHeaderProps { dbId: string; @@ -56,6 +57,13 @@ export function WorkspaceHeader({ dbId={dbId} /> + {/* Execution Plan */} + + {/* NL to SQL Query */}