diff --git a/bridge/__tests__/connectors/clickhouse.batch.test.ts b/bridge/__tests__/connectors/clickhouse.batch.test.ts index 2abef9c6..d3a97c6b 100644 --- a/bridge/__tests__/connectors/clickhouse.batch.test.ts +++ b/bridge/__tests__/connectors/clickhouse.batch.test.ts @@ -136,6 +136,9 @@ describe("ClickHouse getSchemaMetadataBatch unit tests", () => { expect(userTable!.columns[0].is_primary_key).toBe(true); expect(userTable!.primaryKeys).toHaveLength(1); expect(userTable!.primaryKeys[0].column_name).toBe("id"); + expect(userTable!.reportedPrimaryKeys).toEqual(["id"]); + expect(result.indexMetadataError).toBeUndefined(); + expect(result.columnMetadataErrors).toBeUndefined(); const orderTable = result.tables.get("orders"); expect(orderTable).toBeDefined(); @@ -191,7 +194,7 @@ describe("ClickHouse getSchemaMetadataBatch unit tests", () => { const q = String(query); // listTables query - if (q.includes("FROM system.tables")) { + if (q.includes("FROM system.tables") && !q.includes("primary_key")) { return { json: async () => [ { schema: "testdb", name: "student", type: "BASE TABLE" }, @@ -201,6 +204,16 @@ describe("ClickHouse getSchemaMetadataBatch unit tests", () => { }; } + if (q.includes("primary_key, sorting_key FROM system.tables")) { + return { + json: async () => [ + { name: "student", primary_key: "id", sorting_key: "id" }, + { name: "persons", primary_key: "tuple()", sorting_key: "tuple()" }, + { name: "TestTable", primary_key: "tuple()", sorting_key: "tuple()" }, + ], + }; + } + // Batch queries fail if (q.includes("ORDER BY `table`")) { throw new Error("Batch query failed"); @@ -254,6 +267,7 @@ describe("ClickHouse getSchemaMetadataBatch unit tests", () => { expect(studentMeta).toBeDefined(); expect(studentMeta!.columns).toHaveLength(2); expect(studentMeta!.primaryKeys[0].column_name).toBe("id"); + expect(studentMeta!.reportedPrimaryKeys).toEqual(["id"]); }); it("should filter tables when array of table names is passed", async () => { @@ -304,4 +318,214 @@ describe("ClickHouse getSchemaMetadataBatch unit tests", () => { expect(result.tables.has("student")).toBe(true); expect(result.tables.has("persons")).toBe(false); }); + + it("distinguishes reportedPrimaryKeys from listPrimaryKeys first-column UI fallback for ORDER BY tuple() tables", async () => { + mockQuery.mockImplementation(async ({ query }: any) => { + const q = String(query); + + if (q.includes("FROM system.tables")) { + return { + json: async () => [ + { schema: "testdb", name: "logs", type: "BASE TABLE" }, + { schema: "testdb", name: "users", type: "BASE TABLE" }, + ], + }; + } + + if (q.includes("FROM system.columns") && !q.includes("is_in_primary_key = 1")) { + if (q.includes("ORDER BY `table`")) { + return { + json: async () => [ + { + table: "logs", + name: "ts", + type: "DateTime", + not_nullable: 1, + is_in_primary_key: 0, + is_in_sorting_key: 0, + }, + { + table: "users", + name: "id", + type: "UInt64", + not_nullable: 1, + is_in_primary_key: 1, + is_in_sorting_key: 1, + }, + ], + }; + } + return { + json: async () => [{ name: "ts", type: "DateTime", not_nullable: 1 }], + }; + } + + if (q.includes("is_in_primary_key = 1")) { + if (q.includes("ORDER BY `table`")) { + return { + json: async () => [{ table: "users", column_name: "id" }], + }; + } + return { json: async () => [] }; + } + + return { json: async () => [] }; + }); + + const result = await clickhouseConnector.getSchemaMetadataBatch(mockConfig, "testdb"); + const logs = result.tables.get("logs")!; + const users = result.tables.get("users")!; + + expect(logs.reportedPrimaryKeys).toEqual([]); + expect(logs.primaryKeys).toEqual([{ column_name: "ts" }]); + expect(users.reportedPrimaryKeys).toEqual(["id"]); + expect(users.primaryKeys).toEqual([{ column_name: "id" }]); + }); + + it("reports indexMetadataError when CLICKHOUSE_BATCH_GET_INDEXES throws without hiding empty index success", async () => { + mockQuery.mockImplementation(async ({ query }: any) => { + const q = String(query); + + if (q.includes("FROM system.tables")) { + return { + json: async () => [{ schema: "testdb", name: "events", type: "BASE TABLE" }], + }; + } + if (q.includes("FROM system.columns") && !q.includes("is_in_primary_key = 1")) { + return { + json: async () => [ + { + table: "events", + name: "id", + type: "UInt64", + not_nullable: 1, + is_in_primary_key: 1, + is_in_sorting_key: 1, + }, + ], + }; + } + if (q.includes("is_in_primary_key = 1")) { + return { + json: async () => [{ table: "events", column_name: "id" }], + }; + } + if (q.includes("system.data_skipping_indices")) { + throw new Error("Permission denied on system.data_skipping_indices"); + } + + return { json: async () => [] }; + }); + + const result = await clickhouseConnector.getSchemaMetadataBatch(mockConfig, "testdb"); + expect( + (result.indexMetadataError as any)?.message ?? String(result.indexMetadataError), + ).toContain("Permission denied"); + expect(result.tables.get("events")!.indexes).toEqual([]); + }); + + it("records columnMetadataErrors for a single failing table while preserving other loaded tables", async () => { + mockQuery.mockImplementation(async ({ query, query_params }: any) => { + const q = String(query); + + if (q.includes("FROM system.tables")) { + return { + json: async () => [ + { schema: "testdb", name: "users", type: "BASE TABLE" }, + { schema: "testdb", name: "broken_table", type: "BASE TABLE" }, + ], + }; + } + if ( + q.includes("ORDER BY `table`") && + q.includes("FROM system.columns") && + !q.includes("is_in_primary_key = 1") + ) { + return { + json: async () => [ + { + table: "users", + name: "id", + type: "UInt64", + not_nullable: 1, + is_in_primary_key: 1, + is_in_sorting_key: 1, + }, + ], + }; + } + if ( + q.includes( + "WHERE database = {target_schema: String} AND `table` = {target_table: String}", + ) && + !q.includes("is_in_primary_key = 1") + ) { + if (query_params?.target_table === "broken_table") { + throw new Error("Table metadata corrupted"); + } + } + if (q.includes("is_in_primary_key = 1")) { + return { json: async () => [{ table: "users", column_name: "id" }] }; + } + return { json: async () => [] }; + }); + + const result = await clickhouseConnector.getSchemaMetadataBatch(mockConfig, "testdb"); + expect(result.tables.get("users")!.columns).toHaveLength(1); + expect(result.tables.get("broken_table")!.columns).toEqual([]); + expect(result.columnMetadataErrors).toEqual({ + broken_table: "Table metadata corrupted", + }); + expect(result.columnMetadataError).toContain("broken_table"); + }); + + it("throws when batch columns query fails and no table recovers via fallback", async () => { + mockQuery.mockImplementation(async ({ query }: any) => { + const q = String(query); + + if (q.includes("FROM system.tables")) { + return { + json: async () => [{ schema: "testdb", name: "users", type: "BASE TABLE" }], + }; + } + if (q.includes("FROM system.columns") && !q.includes("is_in_primary_key = 1")) { + throw new Error("ClickHouse columns unavailable"); + } + return { json: async () => [] }; + }); + + await expect(clickhouseConnector.getSchemaMetadataBatch(mockConfig, "testdb")).rejects.toThrow( + /Failed to retrieve ClickHouse column metadata/, + ); + }); + + it("does not promote fallback listPrimaryKeys to reportedPrimaryKeys", async () => { + mockQuery.mockImplementation(async ({ query }: any) => { + const q = String(query); + if (q.includes("FROM system.tables")) { + return { json: async () => [{ schema: "testdb", name: "events", type: "BASE TABLE" }] }; + } + if (q.includes("is_in_primary_key = 1")) { + return { json: async () => [] }; + } + if (q.includes("FROM system.columns")) { + return { + json: async () => [ + { table: "events", name: "id", type: "UInt64", not_nullable: 1, is_in_primary_key: 0 }, + ], + }; + } + return { json: async () => [] }; + }); + + const mockListPks = jest + .spyOn(clickhouseConnector, "listPrimaryKeys") + .mockResolvedValue([{ column_name: "id" }]); + + const result = await clickhouseConnector.getSchemaMetadataBatch(mockConfig, "testdb"); + const events = result.tables.get("events")!; + expect(events.primaryKeys).toEqual([{ column_name: "id" }]); + expect(events.reportedPrimaryKeys).toEqual([]); + mockListPks.mockRestore(); + }); }); diff --git a/bridge/__tests__/explainCollector.test.ts b/bridge/__tests__/explainCollector.test.ts new file mode 100644 index 00000000..874a629e --- /dev/null +++ b/bridge/__tests__/explainCollector.test.ts @@ -0,0 +1,815 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; +import Database from "better-sqlite3"; +import mysql from "mysql2/promise"; +import { DBType } from "../src/types"; +import * as postgresConnector from "../src/connectors/postgres"; +import * as duckdbConnector from "../src/connectors/duckdb"; +import * as clickhouseConnector from "../src/connectors/clickhouse"; +import * as mongoConnector from "../src/connectors/mongo"; +import { + collectExplainPlan, + isReadOnlySelectSql, + normalizeDuckdbExplain, + normalizeMongoExplain, + normalizeMysqlExplain, + normalizePostgresExplain, +} from "../src/services/explainCollector"; + +describe("explainCollector", () => { + describe("isReadOnlySelectSql", () => { + it("allows SELECT, WITH, and VALUES with leading comments/whitespace", () => { + expect(isReadOnlySelectSql(" SELECT * FROM users")).toBe(true); + expect(isReadOnlySelectSql("-- comment\nSELECT id FROM users;")).toBe(true); + expect(isReadOnlySelectSql("/* block */ WITH cte AS (SELECT 1) SELECT * FROM cte")).toBe( + true, + ); + expect(isReadOnlySelectSql("VALUES (1, 'a;b')")).toBe(true); + expect(isReadOnlySelectSql("SELECT ';' AS semi")).toBe(true); + expect(isReadOnlySelectSql("SELECT replace(name, 'a', 'b') FROM users")).toBe(true); + expect(isReadOnlySelectSql("SELECT replace ('abc', 'a', 'x')")).toBe(true); + expect(isReadOnlySelectSql("SELECT $$a;b$$")).toBe(true); + expect(isReadOnlySelectSql("SELECT $tag$a;b;DROP TABLE x$tag$")).toBe(true); + expect(isReadOnlySelectSql("SELECT $é$a;b$é$")).toBe(true); + expect(isReadOnlySelectSql("SELECT $e\u0301$a;b$e\u0301$")).toBe(true); + expect(isReadOnlySelectSql("SELECT $é\u0301$a;b$é\u0301$")).toBe(true); + }); + + it("blocks mutating statements and multi-statement chains", () => { + expect(isReadOnlySelectSql("SELECT $$a;b$$; DROP TABLE users")).toBe(false); + expect(isReadOnlySelectSql("SELECT $e\u0301$a;b$e\u0301$; DROP TABLE users")).toBe(false); + expect(isReadOnlySelectSql("SELECT col$$a; DROP TABLE users")).toBe(false); + expect(isReadOnlySelectSql("SELECT col\u0301$$a; DROP TABLE users")).toBe(false); + expect(isReadOnlySelectSql("INSERT INTO users VALUES (1)")).toBe(false); + expect(isReadOnlySelectSql("UPDATE users SET name = 'x'")).toBe(false); + expect(isReadOnlySelectSql("DELETE FROM users")).toBe(false); + expect(isReadOnlySelectSql("DROP TABLE users")).toBe(false); + expect(isReadOnlySelectSql("ALTER TABLE users ADD COLUMN a INT")).toBe(false); + expect(isReadOnlySelectSql("TRUNCATE TABLE users")).toBe(false); + expect(isReadOnlySelectSql("CREATE TABLE t (id INT)")).toBe(false); + expect(isReadOnlySelectSql("REPLACE INTO t VALUES (1)")).toBe(false); + expect(isReadOnlySelectSql("WITH d AS (REPLACE INTO t VALUES (1)) SELECT * FROM d")).toBe( + false, + ); + expect(isReadOnlySelectSql("MERGE INTO t USING s ON t.id = s.id")).toBe(false); + expect(isReadOnlySelectSql("GRANT SELECT ON t TO u")).toBe(false); + expect(isReadOnlySelectSql("REVOKE SELECT ON t FROM u")).toBe(false); + expect(isReadOnlySelectSql("SELECT 1; DROP TABLE users")).toBe(false); + expect(isReadOnlySelectSql("WITH d AS (DELETE FROM users RETURNING *) SELECT * FROM d")).toBe( + false, + ); + }); + }); + + describe("collectExplainPlan safety guard", () => { + it("rejects analyze: true on mutating SQL with VALIDATION_ERROR", async () => { + const mutatingQueries = [ + "INSERT INTO users (name) VALUES ('alice')", + "UPDATE users SET name = 'bob'", + "DELETE FROM users WHERE id = 1", + "SELECT 1; DELETE FROM users", + ]; + + for (const sql of mutatingQueries) { + await expect( + collectExplainPlan({ path: ":memory:" }, DBType.SQLITE, { sql, analyze: true }), + ).rejects.toMatchObject({ code: "VALIDATION_ERROR" }); + } + }); + + it("rejects multi-statement SQL even when analyze is false", async () => { + await expect( + collectExplainPlan({ path: ":memory:" }, DBType.SQLITE, { + sql: "SELECT 1; DELETE FROM users", + analyze: false, + }), + ).rejects.toMatchObject({ code: "VALIDATION_ERROR" }); + }); + + it("allows semicolons inside PostgreSQL dollar-quoted strings even when analyze is false", async () => { + const mockClient = { + query: jest.fn(async () => ({ + rows: [{ "QUERY PLAN": [{ Plan: { "Node Type": "Result" } }] }], + })), + release: jest.fn(), + }; + jest.spyOn(postgresConnector, "getPool").mockReturnValue({ + connect: jest.fn(async () => mockClient), + } as any); + + const res = await collectExplainPlan({} as any, DBType.POSTGRES, { + sql: "SELECT $$a;b$$, $é$c;d$é$", + analyze: false, + }); + expect(res.dialect).toBe(DBType.POSTGRES); + jest.restoreAllMocks(); + }); + + it("rejects non-string sql with VALIDATION_ERROR instead of TypeError", async () => { + await expect( + collectExplainPlan({ path: ":memory:" }, DBType.SQLITE, { + sql: 42 as unknown as string, + analyze: false, + }), + ).rejects.toMatchObject({ code: "VALIDATION_ERROR" }); + }); + }); + + describe("live SQLite EXPLAIN QUERY PLAN", () => { + let tmpDir: string; + let dbPath: string; + + beforeAll(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "relwave-explain-")); + dbPath = path.join(tmpDir, "test.db"); + const db = new Database(dbPath); + db.exec(` + CREATE TABLE users ( + id INTEGER PRIMARY KEY, + email TEXT NOT NULL, + age INTEGER NOT NULL + ); + CREATE INDEX idx_users_email ON users (email); + INSERT INTO users (email, age) VALUES ('a@example.com', 30), ('b@example.com', 25); + `); + db.close(); + }); + + afterAll(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + it("detects FULL_SCAN on unindexed column", async () => { + const plan = await collectExplainPlan({ path: dbPath, readonly: true }, DBType.SQLITE, { + sql: "SELECT * FROM users WHERE age = 30", + }); + + expect(plan.dialect).toBe(DBType.SQLITE); + expect(plan.bottlenecks.some((b) => b.type === "FULL_SCAN" && b.target === "users")).toBe( + true, + ); + }); + + it("detects SEARCH USING INDEX on indexed column without FULL_SCAN", async () => { + const plan = await collectExplainPlan({ path: dbPath, readonly: true }, DBType.SQLITE, { + sql: "SELECT id, email FROM users WHERE email = 'a@example.com'", + }); + + expect(plan.bottlenecks.some((b) => b.type === "FULL_SCAN")).toBe(false); + const serialized = JSON.stringify(plan.planTree); + expect(serialized).toContain("idx_users_email"); + }); + }); + + describe("plan normalizers", () => { + it("normalizes PostgreSQL EXPLAIN (ANALYZE, FORMAT JSON)", () => { + const rawPg = [ + { + "QUERY PLAN": [ + { + Plan: { + "Node Type": "Sort", + "Total Cost": 15000.5, + "Plan Rows": 2500, + "Actual Rows": 2000, + "Actual Total Time": 12.4, + "Sort Method": "external merge", + "Sort Space Type": "Disk", + Plans: [ + { + "Node Type": "Seq Scan", + "Relation Name": "orders", + "Total Cost": 1200.0, + "Plan Rows": 2500, + "Actual Rows": 2000, + "Rows Removed by Filter": 50000, + Filter: "(status = 'pending')", + }, + ], + }, + "Planning Time": 0.45, + "Execution Time": 14.2, + }, + ], + }, + ]; + + const res = normalizePostgresExplain(rawPg, "SELECT * FROM orders", true); + expect(res.dialect).toBe(DBType.POSTGRES); + expect(res.analyzed).toBe(true); + expect(res.executionTimeMs).toBe(14.2); + expect(res.planningTimeMs).toBe(0.45); + expect(res.totalCost).toBe(15000.5); + expect(res.bottlenecks.map((b) => b.type)).toEqual( + expect.arrayContaining(["FULL_SCAN", "FILESORT", "HIGH_COST", "LOW_SELECTIVITY"]), + ); + }); + + it("normalizes MySQL EXPLAIN FORMAT=JSON", () => { + const rawMysql = [ + { + EXPLAIN: JSON.stringify({ + query_block: { + select_id: 1, + cost_info: { query_cost: "450.25" }, + ordering_operation: { + using_filesort: true, + using_temporary_table: true, + table: { + table_name: "events", + access_type: "ALL", + rows_examined_per_scan: 5000, + cost_info: { read_cost: "400", eval_cost: "50.25" }, + attached_condition: "(events.type = 'click')", + }, + }, + }, + }), + }, + ]; + + const res = normalizeMysqlExplain( + rawMysql, + "SELECT * FROM events ORDER BY created_at", + false, + ); + expect(res.dialect).toBe(DBType.MYSQL); + expect(res.totalCost).toBe(450.25); + expect(res.rowsExamined).toBe(5000); + expect(res.bottlenecks.map((b) => b.type)).toEqual( + expect.arrayContaining(["FULL_SCAN", "FILESORT", "TEMP_TABLE"]), + ); + }); + + it("normalizes MongoDB executionStats with COLLSCAN, SORT, and IXSCAN", () => { + const rawMongo = { + queryPlanner: { winningPlan: { stage: "SORT" } }, + executionStats: { + executionSuccess: true, + nReturned: 5, + executionTimeMillis: 18, + totalKeysExamined: 0, + totalDocsExamined: 2500, + executionStages: { + stage: "SORT", + nReturned: 5, + inputStage: { + stage: "COLLSCAN", + nReturned: 5, + filter: { status: "active" }, + }, + }, + }, + }; + + const res = normalizeMongoExplain(rawMongo, "db.users.find({status:'active'})", true); + expect(res.dialect).toBe(DBType.MONGODB); + expect(res.executionTimeMs).toBe(18); + expect(res.rowsExamined).toBe(2500); + expect(res.rowsReturned).toBe(5); + expect(res.bottlenecks.map((b) => b.type)).toEqual( + expect.arrayContaining(["FULL_SCAN", "FILESORT", "LOW_SELECTIVITY"]), + ); + + const ixExplain = normalizeMongoExplain( + { + executionStats: { + nReturned: 10, + executionTimeMillis: 1, + totalDocsExamined: 10, + executionStages: { + stage: "FETCH", + nReturned: 10, + inputStage: { stage: "IXSCAN", indexName: "email_1", nReturned: 10 }, + }, + }, + }, + "db.users.find({email:'a@b.com'})", + true, + ); + expect(ixExplain.bottlenecks).toHaveLength(0); + expect(ixExplain.planTree.children[0].indexName).toBe("email_1"); + }); + + it("multiplies PostgreSQL measured scan counts by Actual Loops in rowsExamined", () => { + const rawPg = [ + { + "QUERY PLAN": [ + { + Plan: { + "Node Type": "Nested Loop", + "Actual Rows": 50, + "Actual Loops": 1, + Plans: [ + { + "Node Type": "Index Scan", + "Relation Name": "items", + "Plan Rows": 5, + "Actual Rows": 10, + "Rows Removed by Filter": 2, + "Actual Loops": 100, + }, + ], + }, + }, + ], + }, + ]; + + const res = normalizePostgresExplain(rawPg, "SELECT * FROM items", true); + expect(res.rowsExamined).toBe(1200); + }); + + it("parses MySQL EXPLAIN ANALYZE estimated and actual rows separately", () => { + const textPlan = + "-> Nested loop inner join (cost=76470.00 rows=76470) (actual time=0.042..155.829 rows=227103 loops=1)\n" + + " -> Table scan on t1 (cost=1.25 rows=10) (actual time=0.025..0.038 rows=10 loops=1)"; + + const res = normalizeMysqlExplain(textPlan, "SELECT * FROM t1 JOIN t2", true, DBType.MYSQL); + expect(res.analyzed).toBe(true); + expect(res.planTree.rows).toBe(76470); + expect(res.planTree.actualRows).toBe(227103); + expect(res.rowsReturned).toBe(227103); + expect(res.executionTimeMs).toBe(155.829); + }); + + it("reads MariaDB plan-only table.rows and ANALYZE FORMAT=JSON r_* fields", () => { + const mariaPlanOnly = [ + { + EXPLAIN: JSON.stringify({ + query_block: { + select_id: 1, + nested_loop: [ + { + table: { + table_name: "orders", + access_type: "ALL", + rows: 4200, + }, + }, + ], + }, + }), + }, + ]; + + const planOnlyRes = normalizeMysqlExplain( + mariaPlanOnly, + "SELECT * FROM orders", + false, + DBType.MARIADB, + ); + expect(planOnlyRes.rowsExamined).toBe(4200); + expect(planOnlyRes.bottlenecks.some((b) => b.type === "FULL_SCAN")).toBe(true); + + const mariaAnalyzed = [ + { + EXPLAIN: JSON.stringify({ + query_block: { + select_id: 1, + r_total_time_ms: 12.5, + table: { + table_name: "orders", + access_type: "ref", + key: "idx_status", + rows: 100, + r_loops: 2, + r_rows: 45, + r_total_time_ms: 8.2, + }, + }, + }), + }, + ]; + + const analyzedRes = normalizeMysqlExplain( + mariaAnalyzed, + "SELECT * FROM orders WHERE status = 'open'", + true, + DBType.MARIADB, + ); + expect(analyzedRes.executionTimeMs).toBe(12.5); + expect(analyzedRes.planTree.rows).toBe(100); + expect(analyzedRes.planTree.actualRows).toBe(90); + expect(analyzedRes.planTree.actualTimeMs).toBe(8.2); + expect(analyzedRes.rowsExamined).toBe(90); + expect(analyzedRes.rowsReturned).toBe(90); + + // With r_filtered present, separate unfiltered rows read (rowsExamined) from filtered output (rowsReturned) + const mariaFiltered = [ + { + EXPLAIN: JSON.stringify({ + query_block: { + select_id: 1, + r_total_time_ms: 4.5, + table: { + table_name: "orders", + access_type: "ALL", + rows: 1000, + r_loops: 1, + r_rows: 1000, + r_filtered: 1, + r_total_time_ms: 4.2, + }, + }, + }), + }, + ]; + const filteredRes = normalizeMysqlExplain( + mariaFiltered, + "SELECT * FROM orders WHERE status = 'rare'", + true, + DBType.MARIADB, + ); + expect(filteredRes.rowsExamined).toBe(1000); + expect(filteredRes.rowsReturned).toBe(10); + expect(filteredRes.planTree.actualRows).toBe(10); + + // Grouping query keeps unfiltered rowsExamined and preserves undefined rowsReturned fallback + const mariaGrouped = [ + { + EXPLAIN: JSON.stringify({ + query_block: { + select_id: 1, + grouping_operation: { + using_temporary_table: true, + table: { + table_name: "orders", + access_type: "ALL", + rows: 1000, + r_loops: 1, + r_rows: 1000, + r_filtered: 10, + }, + }, + }, + }), + }, + ]; + const groupedRes = normalizeMysqlExplain( + mariaGrouped, + "SELECT status, COUNT(*) FROM orders GROUP BY status", + true, + DBType.MARIADB, + ); + expect(groupedRes.rowsExamined).toBe(1000); + expect(groupedRes.rowsReturned).toBeUndefined(); + + // Unexecuted inner scan (r_loops: 0, r_rows: null) counts as 0 rows read instead of estimated rows, + // and multi-table nested_loop leaves rowsReturned unset while preserving per-scan actualRows. + const mariaLeftJoin = [ + { + EXPLAIN: JSON.stringify({ + query_block: { + select_id: 1, + nested_loop: [ + { + table: { + table_name: "users", + access_type: "ALL", + rows: 50, + r_loops: 1, + r_rows: 10, + }, + }, + { + table: { + table_name: "orders", + access_type: "ref", + rows: 500, + r_loops: 0, + r_rows: null, + }, + }, + ], + }, + }), + }, + ]; + const leftJoinRes = normalizeMysqlExplain( + mariaLeftJoin, + "SELECT * FROM users LEFT JOIN orders ON users.id = orders.user_id", + true, + DBType.MARIADB, + ); + expect(leftJoinRes.rowsExamined).toBe(10); + expect(leftJoinRes.rowsReturned).toBeUndefined(); + expect(leftJoinRes.planTree.children).toHaveLength(2); + expect(leftJoinRes.planTree.children[0].actualRows).toBe(10); + expect(leftJoinRes.planTree.children[1].actualRows).toBe(0); + }); + + it("decodes DuckDB 1.5.6 profiler JSON separately from plan-only JSON", () => { + const duckPlanOnly = [ + { + explain_key: "physical_plan", + explain_value: JSON.stringify([ + { + name: "PROJECTION", + extra_info: { "Estimated Cardinality": "23" }, + children: [ + { + name: "SEQ_SCAN", + extra_info: { Table: "users", Filters: "age=30", "Estimated Cardinality": "23" }, + children: [], + }, + ], + }, + ]), + }, + ]; + + const planOnlyRes = normalizeDuckdbExplain( + duckPlanOnly, + "SELECT * FROM users WHERE age = 30", + false, + ); + expect(planOnlyRes.planTree.nodeType).toBe("PROJECTION"); + expect(planOnlyRes.planTree.children[0].nodeType).toBe("SEQ_SCAN"); + expect(planOnlyRes.planTree.children[0].relation).toBe("users"); + expect(planOnlyRes.planTree.children[0].filter).toBe("age=30"); + expect(planOnlyRes.bottlenecks).toEqual([ + expect.objectContaining({ type: "FULL_SCAN", target: "users" }), + ]); + + const duckAnalyzed = [ + { + explain_key: "analyzed_plan", + explain_value: JSON.stringify({ + cumulative_rows_scanned: 1000, + latency: 0.0025, + result_set_size: 0, + rows_returned: 0, + children: [ + { + operator_name: "EXPLAIN_ANALYZE", + operator_cardinality: 0, + operator_rows_scanned: 0, + operator_timing: 0.000001, + children: [ + { + operator_name: "PROJECTION", + operator_cardinality: 20, + operator_rows_scanned: 0, + operator_timing: 0.000002, + result_set_size: 480, + extra_info: { "Estimated Cardinality": "23" }, + children: [ + { + operator_name: "SEQ_SCAN", + operator_type: "TABLE_SCAN", + operator_cardinality: 20, + operator_rows_scanned: 1000, + operator_timing: 0.00025, + result_set_size: 480, + extra_info: { + Table: "memory.main.users", + Filters: "age=30", + "Estimated Cardinality": "23", + }, + children: [], + }, + ], + }, + ], + }, + ], + }), + }, + ]; + + const analyzedRes = normalizeDuckdbExplain( + duckAnalyzed, + "SELECT * FROM users WHERE age = 30", + true, + ); + expect(analyzedRes.analyzed).toBe(true); + expect(analyzedRes.executionTimeMs).toBeCloseTo(2.5, 4); + expect(analyzedRes.rowsExamined).toBe(1000); + expect(analyzedRes.rowsReturned).toBe(20); + expect(analyzedRes.planTree.nodeType).toBe("PROJECTION"); + expect(analyzedRes.planTree.actualRows).toBe(20); + const scanNode = analyzedRes.planTree.children[0]; + expect(scanNode.nodeType).toBe("SEQ_SCAN"); + expect(scanNode.relation).toBe("memory.main.users"); + expect(scanNode.actualRows).toBe(20); + expect(scanNode.actualTimeMs).toBeCloseTo(0.25, 4); + expect(analyzedRes.bottlenecks).toEqual([ + expect.objectContaining({ type: "FULL_SCAN", target: "memory.main.users" }), + ]); + + // Preserves cumulative_rows_scanned: 0 + const duckZeroCumulative = normalizeDuckdbExplain( + [ + { + explain_key: "analyzed_plan", + explain_value: JSON.stringify({ + cumulative_rows_scanned: 0, + latency: 0.001, + children: [ + { + operator_name: "SEQ_SCAN", + operator_cardinality: 0, + operator_rows_scanned: 0, + children: [], + }, + ], + }), + }, + ], + "SELECT * FROM empty_table", + true, + ); + expect(duckZeroCumulative.rowsExamined).toBe(0); + + // Preserves operator-sum 0 when operators supply operator_rows_scanned: 0 + const duckZeroOpSum = normalizeDuckdbExplain( + [ + { + explain_key: "analyzed_plan", + explain_value: JSON.stringify({ + latency: 0.001, + children: [ + { + operator_name: "SEQ_SCAN", + operator_cardinality: 0, + operator_rows_scanned: 0, + children: [], + }, + ], + }), + }, + ], + "SELECT * FROM empty_table", + true, + ); + expect(duckZeroOpSum.rowsExamined).toBe(0); + + // Leaves rowsExamined undefined when neither cumulative_rows_scanned nor operator_rows_scanned is present + const duckMissingScanCount = normalizeDuckdbExplain( + [ + { + explain_key: "analyzed_plan", + explain_value: JSON.stringify({ + latency: 0.001, + children: [ + { + operator_name: "RESULT_COLLECTOR", + operator_cardinality: 1, + children: [], + }, + ], + }), + }, + ], + "SELECT 1", + true, + ); + expect(duckMissingScanCount.rowsExamined).toBeUndefined(); + }); + + it("recognizes runtime stats inside MongoDB aggregation $cursor.executionStats", () => { + const aggExplain = { + stages: [ + { + $cursor: { + queryPlanner: { winningPlan: { stage: "COLLSCAN" } }, + executionStats: { + nReturned: 500, + executionTimeMillis: 24, + totalDocsExamined: 1200, + executionStages: { stage: "COLLSCAN", nReturned: 500 }, + }, + }, + }, + { $group: { _id: "$status", count: { $sum: 1 } } }, + ], + }; + + const res = normalizeMongoExplain(aggExplain, "db.orders.aggregate([...])", true); + expect(res.analyzed).toBe(true); + expect(res.executionTimeMs).toBe(24); + expect(res.rowsExamined).toBe(1200); + expect(res.rowsReturned).toBeUndefined(); + }); + }); + + describe("collectExplainPlan dialect dispatch", () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it("uses BEGIN READ ONLY for PostgreSQL analyze: true", async () => { + const queries: string[] = []; + const mockClient = { + query: jest.fn(async (sql: string) => { + queries.push(sql); + if (sql.startsWith("EXPLAIN")) { + return { rows: [{ "QUERY PLAN": [{ Plan: { "Node Type": "Result" } }] }] }; + } + return { rows: [] }; + }), + release: jest.fn(), + }; + jest.spyOn(postgresConnector, "getPool").mockReturnValue({ + connect: jest.fn(async () => mockClient), + } as any); + + const res = await collectExplainPlan({} as any, DBType.POSTGRES, { + sql: "SELECT 1;", + analyze: true, + }); + + expect(queries[0]).toBe("BEGIN READ ONLY"); + expect(queries[1]).toContain("EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) SELECT 1"); + expect(queries[2]).toBe("ROLLBACK"); + expect(res.analyzed).toBe(true); + }); + + it("uses queryPlanner for MongoDB plan-only and executionStats for analyze: true", async () => { + const spy = jest.spyOn(mongoConnector, "explainMql").mockResolvedValue({ + queryPlanner: { winningPlan: { stage: "COLLSCAN" } }, + } as any); + + const planOnly = await collectExplainPlan({} as any, DBType.MONGODB, { + collection: "users", + filter: {}, + analyze: false, + }); + expect(spy).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ verbosity: "queryPlanner" }), + ); + expect(planOnly.analyzed).toBe(false); + + await collectExplainPlan({} as any, DBType.MONGODB, { + collection: "users", + filter: {}, + analyze: true, + }); + expect(spy).toHaveBeenLastCalledWith( + expect.anything(), + expect.objectContaining({ verbosity: "executionStats" }), + ); + }); + + it("uses ANALYZE FORMAT=JSON for MariaDB when analyze: true", async () => { + const executed: string[] = []; + const mockConn = { + query: jest.fn(async (q: string) => { + executed.push(q); + return [[{ EXPLAIN: JSON.stringify({ query_block: { select_id: 1 } }) }]]; + }), + release: jest.fn(), + }; + jest.spyOn(mysql, "createPool").mockReturnValue({ + getConnection: jest.fn(async () => mockConn), + end: jest.fn(async () => {}), + } as any); + + await collectExplainPlan({} as any, DBType.MARIADB, { sql: "SELECT 1", analyze: true }); + expect(executed[0]).toBe("ANALYZE FORMAT=JSON SELECT 1"); + + await collectExplainPlan({} as any, DBType.MARIADB, { sql: "SELECT 1", analyze: false }); + expect(executed[1]).toBe("EXPLAIN FORMAT=JSON SELECT 1"); + }); + + it("uses EXPLAIN ANALYZE for DuckDB analyze: true and keeps plan-only as analyzed: false", async () => { + const spy = jest + .spyOn(duckdbConnector, "runQuery") + .mockResolvedValue([{ explain_value: "SEQ_SCAN" }] as any); + + const planOnly = await collectExplainPlan({ path: ":memory:" } as any, DBType.DUCKDB, { + sql: "SELECT 1", + analyze: false, + }); + expect(spy).toHaveBeenCalledWith(expect.anything(), "EXPLAIN (FORMAT JSON) SELECT 1"); + expect(planOnly.analyzed).toBe(false); + + const analyzed = await collectExplainPlan({ path: ":memory:" } as any, DBType.DUCKDB, { + sql: "SELECT 1", + analyze: true, + }); + expect(spy).toHaveBeenLastCalledWith( + expect.anything(), + "EXPLAIN (ANALYZE, FORMAT JSON) SELECT 1", + ); + expect(analyzed.analyzed).toBe(true); + }); + + it("marks ClickHouse EXPLAIN PLAN as analyzed: false even when analyze: true", async () => { + jest.spyOn(clickhouseConnector, "getClient").mockReturnValue({ + query: jest.fn(async () => ({ + json: async () => [{ explain: "Expression" }], + })), + } as any); + + const res = await collectExplainPlan({} as any, DBType.CLICKHOUSE, { + sql: "SELECT 1", + analyze: true, + }); + expect(res.analyzed).toBe(false); + }); + }); +}); 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__/indexStatsService.test.ts b/bridge/__tests__/indexStatsService.test.ts new file mode 100644 index 00000000..3acfbe0d --- /dev/null +++ b/bridge/__tests__/indexStatsService.test.ts @@ -0,0 +1,798 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; +import Database from "better-sqlite3"; +import mysql from "mysql2/promise"; +import { DBType } from "../src/types"; +import { IndexHealthEntry } from "../src/types/performance"; +import { collectIndexHealth, detectDuplicateIndexes } from "../src/services/indexStatsService"; +import { listCollections, mongoConnector } from "../src/connectors/mongo"; +import { getPool as getPgPool } from "../src/connectors/postgres"; +import { runQuery as runDuckDBQuery } from "../src/connectors/duckdb"; +import { getClient as getClickHouseClient } from "../src/connectors/clickhouse"; + +jest.mock("mysql2/promise", () => { + const actual = jest.requireActual("mysql2/promise"); + return { + __esModule: true, + ...actual, + default: { + ...actual.default, + createPool: jest.fn(), + }, + }; +}); + +jest.mock("../src/connectors/mongo", () => { + const actual = jest.requireActual("../src/connectors/mongo"); + return { + ...actual, + listCollections: jest.fn(), + mongoConnector: { + ...actual.mongoConnector, + listIndexes: jest.fn(), + getIndexStats: jest.fn(), + }, + }; +}); + +jest.mock("../src/connectors/postgres", () => ({ + getPool: jest.fn(), +})); + +jest.mock("../src/connectors/duckdb", () => ({ + runQuery: jest.fn(), +})); + +jest.mock("../src/connectors/clickhouse", () => ({ + getClient: jest.fn(), +})); + +describe("indexStatsService", () => { + describe("detectDuplicateIndexes", () => { + it("detects exact duplicate and strict-prefix redundant indexes", () => { + const entries: IndexHealthEntry[] = [ + { + schema: "public", + tableOrCollection: "orders", + indexName: "orders_pkey", + columns: ["id"], + isUnique: true, + isPrimary: true, + scans: 100, + sizeBytes: 4096, + status: "healthy", + }, + { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_customer", + columns: ["customer_id"], + isUnique: false, + isPrimary: false, + scans: 10, + sizeBytes: 2048, + status: "healthy", + }, + { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_customer_created", + columns: ["customer_id", "created_at"], + isUnique: false, + isPrimary: false, + scans: 50, + sizeBytes: 4096, + status: "healthy", + }, + { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_email_unique", + columns: ["email"], + isUnique: true, + isPrimary: false, + scans: 20, + sizeBytes: 2048, + status: "healthy", + }, + { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_email_dup", + columns: ["email"], + isUnique: false, + isPrimary: false, + scans: 0, + sizeBytes: 2048, + status: "unused", + }, + { + schema: "public", + tableOrCollection: "orders", + indexName: "uniq_orders_tenant_code", + columns: ["tenant_id"], + isUnique: true, + isPrimary: false, + scans: 5, + sizeBytes: 1024, + status: "healthy", + }, + { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_tenant_status", + columns: ["tenant_id", "status"], + isUnique: false, + isPrimary: false, + scans: 5, + sizeBytes: 2048, + status: "healthy", + }, + ]; + + const pairs = detectDuplicateIndexes(entries); + expect(pairs).toHaveLength(2); + expect(pairs).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + indexName: "idx_orders_customer", + redundantWith: "idx_orders_customer_created", + }), + expect.objectContaining({ + indexName: "idx_orders_email_dup", + redundantWith: "idx_orders_email_unique", + }), + ]), + ); + // Unique prefix index (uniq_orders_tenant_code) must NOT be flagged as redundant + expect(pairs.some((p) => p.indexName === "uniq_orders_tenant_code")).toBe(false); + }); + + it("never marks a unique partial/non-replaceable index as duplicate of a non-unique index", () => { + const uniquePartial: IndexHealthEntry = { + schema: "main", + tableOrCollection: "users", + indexName: "uq_partial_email", + columns: ["email"], + isUnique: true, + isPrimary: false, + scans: null, + sizeBytes: null, + status: "healthy", + }; + const fullNonUnique: IndexHealthEntry = { + schema: "main", + tableOrCollection: "users", + indexName: "idx_full_email", + columns: ["email"], + isUnique: false, + isPrimary: false, + scans: null, + sizeBytes: null, + status: "healthy", + }; + const meta = new WeakMap(); + meta.set(uniquePartial, { canReplace: false }); + + expect(detectDuplicateIndexes([uniquePartial, fullNonUnique], meta)).toEqual([]); + + // Adding a full unique index should supersede both the partial unique and full non-unique indexes + const fullUnique: IndexHealthEntry = { + schema: "main", + tableOrCollection: "users", + indexName: "uq_full_email", + columns: ["email"], + isUnique: true, + isPrimary: false, + scans: null, + sizeBytes: null, + status: "healthy", + }; + const withFullUnique = detectDuplicateIndexes( + [uniquePartial, fullNonUnique, fullUnique], + meta, + ); + expect(withFullUnique).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + indexName: "uq_partial_email", + redundantWith: "uq_full_email", + }), + expect.objectContaining({ + indexName: "idx_full_email", + redundantWith: "uq_full_email", + }), + ]), + ); + }); + + it("does not collide schema/table pairs containing '::'", () => { + const entries: IndexHealthEntry[] = [ + { + schema: "a::b", + tableOrCollection: "c", + indexName: "idx_1", + columns: ["email"], + isUnique: false, + isPrimary: false, + scans: 10, + sizeBytes: 1024, + status: "healthy", + }, + { + schema: "a", + tableOrCollection: "b::c", + indexName: "idx_2", + columns: ["email", "status"], + isUnique: false, + isPrimary: false, + scans: 10, + sizeBytes: 1024, + status: "healthy", + }, + ]; + + expect(detectDuplicateIndexes(entries)).toEqual([]); + }); + }); + + describe("live SQLite collectIndexHealth", () => { + let tmpDir: string; + let dbPath: string; + + beforeAll(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "relwave-idx-")); + dbPath = path.join(tmpDir, "test.db"); + const db = new Database(dbPath); + db.exec(` + CREATE TABLE items ( + id INTEGER PRIMARY KEY, + sku TEXT NOT NULL, + category TEXT NOT NULL + ); + CREATE INDEX idx_items_sku ON items (sku); + CREATE INDEX idx_items_sku_cat ON items (sku, category); + + CREATE TABLE sqliteEvents ( + id INTEGER PRIMARY KEY, + email TEXT NOT NULL, + active INTEGER NOT NULL + ); + CREATE INDEX idx_a_partial_email ON sqliteEvents (email) WHERE active = 1; + CREATE INDEX idx_z_full_email ON sqliteEvents (email); + + CREATE TABLE sqliteUniquePartial ( + id INTEGER PRIMARY KEY, + email TEXT NOT NULL, + active INTEGER NOT NULL + ); + CREATE UNIQUE INDEX uq_partial_email ON sqliteUniquePartial (email) WHERE active = 1; + CREATE INDEX idx_full_non_unique_email ON sqliteUniquePartial (email); + `); + db.close(); + }); + + afterAll(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + it("introspects SQLite indexes with scans: null and detects prefix duplicate", async () => { + const report = await collectIndexHealth({ path: dbPath, readonly: true }, DBType.SQLITE); + + expect(report.dialect).toBe(DBType.SQLITE); + expect(report.summary.total).toBe(6); + expect(report.summary.duplicateCount).toBe(2); + expect(report.indexes.every((i) => i.scans === null)).toBe(true); + // User table starting with 'sqlite' (without underscore) must be included + expect(report.indexes.some((i) => i.tableOrCollection === "sqliteEvents")).toBe(true); + // Partial index idx_a_partial_email must NOT replace full index idx_z_full_email + expect(report.duplicateIndexes.some((d) => d.indexName === "idx_z_full_email")).toBe(false); + expect(report.indexes.find((i) => i.indexName === "idx_a_partial_email")?.isPartial).toBe( + true, + ); + expect(report.indexes.find((i) => i.indexName === "idx_z_full_email")?.isPartial).toBe(false); + // Unique partial index uq_partial_email must NOT be flagged as duplicate of non-unique idx_full_non_unique_email + expect(report.duplicateIndexes.some((d) => d.indexName === "uq_partial_email")).toBe(false); + expect(report.duplicateIndexes.some((d) => d.indexName === "idx_full_non_unique_email")).toBe( + false, + ); + expect(report.duplicateIndexes).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + tableOrCollection: "items", + indexName: "idx_items_sku", + redundantWith: "idx_items_sku_cat", + }), + ]), + ); + }); + + it("distinguishes SQLite index collations while flagging identical-collation duplicates", async () => { + const collDir = fs.mkdtempSync(path.join(os.tmpdir(), "relwave-idx-coll-")); + const collDbPath = path.join(collDir, "coll.db"); + const db = new Database(collDbPath); + db.exec(` + CREATE TABLE users ( + id INTEGER PRIMARY KEY, + email TEXT NOT NULL + ); + CREATE UNIQUE INDEX a_binary ON users (email COLLATE BINARY); + CREATE UNIQUE INDEX z_nocase ON users (email COLLATE NOCASE); + CREATE UNIQUE INDEX z_nocase_dup ON users (email COLLATE NOCASE); + `); + db.close(); + + try { + const report = await collectIndexHealth( + { path: collDbPath, readonly: true }, + DBType.SQLITE, + ); + expect(report.duplicateIndexes).toEqual([ + expect.objectContaining({ + tableOrCollection: "users", + indexName: "z_nocase_dup", + redundantWith: "z_nocase", + }), + ]); + expect(report.duplicateIndexes.some((d) => d.indexName === "z_nocase")).toBe(false); + } finally { + fs.rmSync(collDir, { recursive: true, force: true }); + } + }); + }); + + describe("MySQL performance_schema fallback", () => { + it("falls back gracefully to scans: null when performance_schema query fails", async () => { + const mockConn = { + query: jest + .fn() + .mockResolvedValueOnce([ + [ + { + schema_name: "app", + table_name: "users", + index_name: "PRIMARY", + non_unique: 0, + column_name: "id", + seq_in_index: 1, + }, + { + schema_name: "app", + table_name: "users", + index_name: "idx_users_email", + non_unique: 1, + column_name: "email", + seq_in_index: 1, + }, + ], + ]) + .mockRejectedValueOnce( + new Error( + "SELECT command denied to user for table 'table_io_waits_summary_by_index_usage'", + ), + ), + release: jest.fn(), + }; + const mockPool = { + getConnection: jest.fn().mockResolvedValue(mockConn), + end: jest.fn().mockResolvedValue(undefined), + }; + (mysql.createPool as jest.Mock).mockReturnValue(mockPool); + + const report = await collectIndexHealth( + { host: "localhost", port: 3306, user: "root", database: "app" }, + DBType.MYSQL, + ); + + expect(report.dialect).toBe(DBType.MYSQL); + expect(report.summary.total).toBe(2); + expect(report.indexes.every((i) => i.scans === null)).toBe(true); + expect(report.summary.unusedCount).toBe(0); + expect(mockConn.release).toHaveBeenCalled(); + expect(mockPool.end).toHaveBeenCalled(); + }); + }); + + describe("MongoDB collectIndexHealth", () => { + it("flags ops === 0 (excluding _id_) as unused and detects prefix-redundant keys", async () => { + (listCollections as jest.Mock).mockResolvedValue([{ name: "users" }]); + (mongoConnector.listIndexes as jest.Mock).mockResolvedValue({ + collection: "users", + totalSizeBytes: 16384, + indexes: [ + { name: "_id_", key: { _id: 1 }, sizeBytes: 4096, unique: true, isIdIndex: true }, + { name: "email_1", key: { email: 1 }, sizeBytes: 4096, unique: false, isIdIndex: false }, + { + name: "email_1_status_1", + key: { email: 1, status: 1 }, + sizeBytes: 8192, + unique: false, + isIdIndex: false, + }, + { name: "unused_1", key: { age: 1 }, sizeBytes: 2048, unique: false, isIdIndex: false }, + ], + }); + (mongoConnector.getIndexStats as jest.Mock).mockResolvedValue({ + collection: "users", + stats: { + _id_: { name: "_id_", ops: 0, since: "2026-01-01T00:00:00Z" }, + email_1: { name: "email_1", ops: 12, since: "2026-01-01T00:00:00Z" }, + email_1_status_1: { name: "email_1_status_1", ops: 55, since: "2026-01-01T00:00:00Z" }, + unused_1: { name: "unused_1", ops: 0, since: "2026-01-01T00:00:00Z" }, + }, + }); + + const report = await collectIndexHealth({ database: "app" }, DBType.MONGODB); + + expect(report.dialect).toBe(DBType.MONGODB); + expect(report.summary.total).toBe(4); + expect(report.unusedIndexes.map((i) => i.indexName)).toEqual(["unused_1"]); + expect(report.duplicateIndexes).toEqual([ + expect.objectContaining({ + tableOrCollection: "users", + indexName: "email_1", + redundantWith: "email_1_status_1", + }), + ]); + expect(report.summary.totalSizeBytes).toBe(18432); + }); + + it("skips views, preserves unique indexes with ops === 0, and distinguishes key types", async () => { + (listCollections as jest.Mock).mockResolvedValue([ + { name: "users", type: "collection" }, + { name: "users_view", type: "view" }, + ]); + (mongoConnector.listIndexes as jest.Mock).mockResolvedValue({ + collection: "users", + totalSizeBytes: 8192, + indexes: [ + { + name: "uniq_email", + key: { email: 1 }, + sizeBytes: 4096, + unique: true, + isIdIndex: false, + }, + { + name: "a_hashed_email", + key: { email: "hashed" }, + sizeBytes: 2048, + unique: false, + isIdIndex: false, + }, + { + name: "z_asc_email", + key: { email: 1 }, + sizeBytes: 2048, + unique: false, + isIdIndex: false, + }, + ], + }); + (mongoConnector.getIndexStats as jest.Mock).mockResolvedValue({ + collection: "users", + stats: { + uniq_email: { name: "uniq_email", ops: 0 }, + a_hashed_email: { name: "a_hashed_email", ops: 5 }, + z_asc_email: { name: "z_asc_email", ops: 5 }, + }, + }); + + const report = await collectIndexHealth({ database: "app" }, DBType.MONGODB); + + expect(mongoConnector.listIndexes).toHaveBeenCalledTimes(1); + expect(mongoConnector.listIndexes).toHaveBeenCalledWith( + { database: "app" }, + { collection: "users" }, + ); + // Unique index with 0 ops must NOT be flagged unused, while preserving scans: 0 + const uniq = report.indexes.find((i) => i.indexName === "uniq_email"); + expect(uniq?.scans).toBe(0); + expect(uniq?.status).not.toBe("unused"); + expect(report.unusedIndexes).toEqual([]); + // z_asc_email is duplicate of uniq_email (both { email: 1 }), NOT a_hashed_email ({ email: "hashed" }) + expect(report.duplicateIndexes).toEqual([ + expect.objectContaining({ + indexName: "z_asc_email", + redundantWith: "uniq_email", + }), + ]); + }); + }); + + describe("PostgreSQL invalid index handling", () => { + it("keeps invalid indexes in inventory but excludes them from replacement selection", async () => { + const mockClient = { + query: jest.fn().mockResolvedValue({ + rows: [ + { + schema_name: "public", + table_name: "users", + index_name: "a_invalid_email", + scans: 0, + size_bytes: 1024, + is_unique: false, + is_primary: false, + is_valid: false, + columns: ["email"], + }, + { + schema_name: "public", + table_name: "users", + index_name: "z_valid_email", + scans: 10, + size_bytes: 2048, + is_unique: false, + is_primary: false, + is_valid: true, + columns: ["email"], + }, + ], + }), + release: jest.fn(), + }; + (getPgPool as jest.Mock).mockReturnValue({ + connect: jest.fn().mockResolvedValue(mockClient), + }); + + const report = await collectIndexHealth( + { host: "localhost", port: 5432, database: "app" }, + DBType.POSTGRES, + ); + + expect(report.indexes).toHaveLength(2); + expect(report.duplicateIndexes).toEqual([ + expect.objectContaining({ + indexName: "a_invalid_email", + redundantWith: "z_valid_email", + }), + ]); + expect(report.duplicateIndexes.some((d) => d.indexName === "z_valid_email")).toBe(false); + }); + + it("populates sqlDefinition, predicate, and isPartial for PostgreSQL partial indexes", async () => { + const mockClient = { + query: jest.fn().mockResolvedValue({ + rows: [ + { + schema_name: "public", + table_name: "users", + index_name: "idx_a_partial_email", + scans: 0, + size_bytes: 1024, + is_unique: false, + is_primary: false, + is_valid: true, + sql_definition: + "CREATE INDEX idx_a_partial_email ON public.users USING btree (email) WHERE (active = true)", + predicate: "(active = true)", + is_partial: true, + columns: ["email"], + }, + { + schema_name: "public", + table_name: "users", + index_name: "idx_z_full_email", + scans: 10, + size_bytes: 2048, + is_unique: false, + is_primary: false, + is_valid: true, + sql_definition: "CREATE INDEX idx_z_full_email ON public.users USING btree (email)", + predicate: null, + is_partial: false, + columns: ["email"], + }, + ], + }), + release: jest.fn(), + }; + (getPgPool as jest.Mock).mockReturnValue({ + connect: jest.fn().mockResolvedValue(mockClient), + }); + + const report = await collectIndexHealth( + { host: "localhost", port: 5432, database: "app" }, + DBType.POSTGRES, + ); + + const partialEntry = report.indexes.find((i) => i.indexName === "idx_a_partial_email"); + const fullEntry = report.indexes.find((i) => i.indexName === "idx_z_full_email"); + expect(partialEntry).toMatchObject({ + isPartial: true, + predicate: "(active = true)", + sqlDefinition: + "CREATE INDEX idx_a_partial_email ON public.users USING btree (email) WHERE (active = true)", + }); + expect(fullEntry).toMatchObject({ + isPartial: false, + predicate: null, + sqlDefinition: "CREATE INDEX idx_z_full_email ON public.users USING btree (email)", + }); + // Partial index must NOT replace full index + expect(report.duplicateIndexes.some((d) => d.indexName === "idx_z_full_email")).toBe(false); + }); + }); + + describe("MySQL SUB_PART and missing perf_schema row", () => { + it("distinguishes prefix indexes via SUB_PART and keeps missing perf_schema scans as null", async () => { + const mockConn = { + query: jest + .fn() + .mockResolvedValueOnce([ + [ + { + schema_name: "app", + table_name: "users", + index_name: "a_email_prefix", + non_unique: 1, + column_name: "email", + seq_in_index: 1, + sub_part: 10, + }, + { + schema_name: "app", + table_name: "users", + index_name: "z_email_full", + non_unique: 1, + column_name: "email", + seq_in_index: 1, + sub_part: null, + }, + ], + ]) + .mockResolvedValueOnce([ + [{ table_name: "users", index_name: "a_email_prefix", scans: 0 }], + ]), + release: jest.fn(), + }; + const mockPool = { + getConnection: jest.fn().mockResolvedValue(mockConn), + end: jest.fn().mockResolvedValue(undefined), + }; + (mysql.createPool as jest.Mock).mockReturnValue(mockPool); + + const report = await collectIndexHealth( + { host: "localhost", port: 3306, user: "root", database: "app" }, + DBType.MYSQL, + ); + + expect(report.duplicateIndexes).toEqual([]); + const prefixIdx = report.indexes.find((i) => i.indexName === "a_email_prefix"); + const fullIdx = report.indexes.find((i) => i.indexName === "z_email_full"); + expect(prefixIdx?.scans).toBe(0); + expect(prefixIdx?.status).toBe("unused"); + expect(fullIdx?.scans).toBeNull(); + expect(fullIdx?.status).toBe("healthy"); + }); + }); + + describe("DuckDB and ClickHouse index comparisons", () => { + it("parses DuckDB expressions/trailing-semicolon SQL and disables strict-prefix rule", async () => { + (runDuckDBQuery as jest.Mock).mockResolvedValue([ + { + schema_name: "main", + table_name: "orders", + index_name: "idx_customer", + is_unique: false, + is_primary: false, + expressions: "[customer_id]", + sql: "CREATE INDEX idx_customer ON orders (customer_id);", + }, + { + schema_name: "main", + table_name: "orders", + index_name: "idx_customer_created", + is_unique: false, + is_primary: false, + expressions: null, + sql: "CREATE INDEX idx_customer_created ON orders (customer_id, created_at);", + }, + { + schema_name: "main", + table_name: "orders", + index_name: "idx_customer_dup", + is_unique: false, + is_primary: false, + expressions: "[customer_id]", + sql: "CREATE INDEX idx_customer_dup ON orders (customer_id);", + }, + ]); + + const report = await collectIndexHealth({ path: ":memory:" }, DBType.DUCKDB); + + expect(report.indexes.find((i) => i.indexName === "idx_customer")?.columns).toEqual([ + "customer_id", + ]); + expect(report.indexes.find((i) => i.indexName === "idx_customer_created")?.columns).toEqual([ + "customer_id", + "created_at", + ]); + // Only exact duplicate flagged; idx_customer is NOT flagged as prefix-redundant with idx_customer_created + expect(report.duplicateIndexes).toEqual([ + expect.objectContaining({ + indexName: "idx_customer_dup", + redundantWith: "idx_customer", + }), + ]); + }); + + it("compares ClickHouse skip-index type_full and granularity", async () => { + (getClickHouseClient as jest.Mock).mockReturnValue({ + query: jest.fn().mockResolvedValue({ + json: jest.fn().mockResolvedValue([ + { + database: "default", + table: "events", + index_name: "idx_minmax", + expr: "user_id", + type_full: "minmax", + granularity: 1, + }, + { + database: "default", + table: "events", + index_name: "idx_bloom", + expr: "user_id", + type_full: "bloom_filter(0.01)", + granularity: 1, + }, + { + database: "default", + table: "events", + index_name: "idx_minmax_dup", + expr: "user_id", + type_full: "minmax", + granularity: 1, + }, + ]), + }), + }); + + const report = await collectIndexHealth( + { host: "localhost", database: "default" }, + DBType.CLICKHOUSE, + ); + + expect(report.duplicateIndexes).toEqual([ + expect.objectContaining({ + indexName: "idx_minmax_dup", + redundantWith: "idx_minmax", + }), + ]); + expect(report.duplicateIndexes.some((d) => d.indexName === "idx_bloom")).toBe(false); + }); + + it("does not flag unique index as duplicate if NULLS NOT DISTINCT rule differs", () => { + const u1: IndexHealthEntry = { + schema: "public", + tableOrCollection: "accounts", + indexName: "idx_acc_email_distinct", + columns: ["email"], + isUnique: true, + isPrimary: false, + scans: null, + sizeBytes: null, + status: "healthy", + }; + const u2: IndexHealthEntry = { + schema: "public", + tableOrCollection: "accounts", + indexName: "idx_acc_email_not_distinct", + columns: ["email"], + isUnique: true, + isPrimary: false, + scans: null, + sizeBytes: null, + status: "healthy", + }; + const meta = new WeakMap(); + meta.set(u1, { comparisonKeys: ["email"], nullsNotDistinct: false }); + meta.set(u2, { comparisonKeys: ["email"], nullsNotDistinct: true }); + + const pairs = detectDuplicateIndexes([u1, u2], meta); + expect(pairs).toHaveLength(0); + }); + }); +}); diff --git a/bridge/__tests__/migrationGenerator.test.ts b/bridge/__tests__/migrationGenerator.test.ts new file mode 100644 index 00000000..af04da38 --- /dev/null +++ b/bridge/__tests__/migrationGenerator.test.ts @@ -0,0 +1,2094 @@ +import { describe, expect, test } from "@jest/globals"; +import fs from "fs"; +import os from "os"; +import path from "path"; +import Database from "better-sqlite3"; +import { diffSchemas } from "../src/services/schemaDiffEngine"; +import { + generateIndexMigration, + generateMigrationFromDiff, + slugifyMigrationName, + UnsupportedMigrationError, +} from "../src/services/migrationGenerator"; +import { applyMigration, rollbackMigration } from "../src/connectors/sqlite"; +import { SQLITE_CREATE_MIGRATION_TABLE } from "../src/queries/sqlite/migrations"; +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: true }), + ], + { + 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).not.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).not.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); + }); + + test("Composite primary key emits single table-level PRIMARY KEY in original column order", () => { + const source: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [{ name: "public", tables: [], enums: [], views: [] }], + }; + const target: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + tbl("tenant_users", [ + col("user_id", "integer", { nullable: false, isPrimaryKey: true }), + col("tenant_id", "integer", { nullable: false, isPrimaryKey: true }), + col("role", "text", { nullable: false }), + ]), + ], + enums: [], + views: [], + }, + ], + }; + + const diff = diffSchemas(source, target); + const res = generateMigrationFromDiff(diff, source, target, { version: "20261128120007" }); + expect(res.upSql).toContain('PRIMARY KEY ("user_id", "tenant_id")'); + expect(res.upSql).not.toContain('"user_id" integer NOT NULL PRIMARY KEY'); + expect(res.upSql).not.toContain('"tenant_id" integer NOT NULL PRIMARY KEY'); + }); + + test("SQLite rebuild with zero mapped columns preserves defaulted rows and rejects NOT NULL without default", () => { + const source: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [tbl("items", [col("a", "integer", { nullable: true })])], + enums: [], + views: [], + }, + ], + }; + const targetWithDefault: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [tbl("items", [col("b", "text", { nullable: false, defaultValue: "'x'" })])], + enums: [], + views: [], + }, + ], + }; + + const diffOk = diffSchemas(source, targetWithDefault, { detectRenames: false }); + const resOk = generateMigrationFromDiff(diffOk, source, targetWithDefault, { + version: "20261128120008", + }); + expect(resOk.upSql).toContain( + 'INSERT INTO "__relwave_new_items" ("b") SELECT \'x\' FROM "items";', + ); + + const targetNoDefault: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [tbl("items", [col("b", "text", { nullable: false })])], + enums: [], + views: [], + }, + ], + }; + const diffBad = diffSchemas(source, targetNoDefault, { detectRenames: false }); + expect(() => + generateMigrationFromDiff(diffBad, source, targetNoDefault, { version: "20261128120009" }), + ).toThrow(UnsupportedMigrationError); + }); + + test("SQLite rebuild preserves unaffected triggers and rejects triggers referencing dropped columns", () => { + const baseTrigger = { + name: "trg_items_audit", + sql: 'CREATE TRIGGER "trg_items_audit" AFTER INSERT ON "items" BEGIN SELECT 1; END', + }; + const sourceWithTrigger: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [ + { + ...tbl("items", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("old_col", "text"), + ]), + triggers: [baseTrigger], + } as CanonicalTable, + ], + enums: [], + views: [], + }, + ], + }; + const target: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [tbl("items", [col("id", "integer", { nullable: false, isPrimaryKey: true })])], + enums: [], + views: [], + }, + ], + }; + + const diffOk = diffSchemas(sourceWithTrigger, target, { detectRenames: false }); + const resOk = generateMigrationFromDiff(diffOk, sourceWithTrigger, target, { + version: "20261128120010", + }); + expect(resOk.upSql).toContain(baseTrigger.sql); + + const sourceBadTrigger: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [ + { + ...tbl("items", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("old_col", "text"), + ]), + triggers: [ + { + name: "trg_bad", + sql: "CREATE TRIGGER trg_bad AFTER INSERT ON items BEGIN SELECT NEW.old_col; END", + }, + ], + } as CanonicalTable, + ], + enums: [], + views: [], + }, + ], + }; + const diffBad = diffSchemas(sourceBadTrigger, target, { detectRenames: false }); + expect(() => + generateMigrationFromDiff(diffBad, sourceBadTrigger, target, { version: "20261128120011" }), + ).toThrow(UnsupportedMigrationError); + }); + + test("PostgreSQL COLUMN_MODIFIED primary-key change emits warning instead of No changes detected", () => { + const source: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [tbl("items", [col("id", "integer", { nullable: false, isPrimaryKey: false })])], + enums: [], + views: [], + }, + ], + }; + const target: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [tbl("items", [col("id", "integer", { nullable: false, isPrimaryKey: true })])], + enums: [], + views: [], + }, + ], + }; + + const diff = diffSchemas(source, target); + const res = generateMigrationFromDiff(diff, source, target, { version: "20261128120012" }); + expect(res.upSql).not.toBe("-- No changes detected"); + expect(res.upSql).toContain("Unsupported automatic primary-key change"); + expect(res.warnings.some((w) => w.includes("Primary key change"))).toBe(true); + }); + + test("acceptRenameIds generates residual changes on renamed tables and renamed columns", () => { + const source: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + tbl("old_users", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("email", "text", { nullable: false }), + col("full_name", "text", { nullable: true, defaultValue: null }), + ]), + ], + enums: [], + views: [], + }, + ], + }; + const target: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + tbl("users", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("email", "text", { nullable: false }), + col("full_name", "text", { nullable: false, defaultValue: "'anon'" }), + col("active", "boolean", { nullable: false, defaultValue: "true" }), + ]), + ], + enums: [], + views: [], + }, + ], + }; + + const diff = diffSchemas(source, target, { detectRenames: true }); + const dropTable = diff.items.find((i) => i.type === "TABLE_DROPPED")!; + const res = generateMigrationFromDiff(diff, source, target, { + version: "20261128120013", + acceptRenameIds: [dropTable.id], + }); + expect(res.upSql).toContain('ALTER TABLE "public"."old_users" RENAME TO "users";'); + expect(res.upSql).toContain('ALTER TABLE "public"."users" ADD COLUMN "active"'); + expect(res.upSql).toContain( + 'ALTER TABLE "public"."users" ALTER COLUMN "full_name" SET NOT NULL;', + ); + expect(res.upSql).toContain("SET DEFAULT 'anon';"); + + // Column rename with residual default change + const colSource: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [tbl("t", [col("id", "integer"), col("old_c", "text", { defaultValue: "'a'" })])], + enums: [], + views: [], + }, + ], + }; + const colTarget: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [tbl("t", [col("id", "integer"), col("new_c", "text", { defaultValue: "'b'" })])], + enums: [], + views: [], + }, + ], + }; + const colDiff = diffSchemas(colSource, colTarget, { detectRenames: true }); + const dropCol = colDiff.items.find((i) => i.type === "COLUMN_DROPPED")!; + const colRes = generateMigrationFromDiff(colDiff, colSource, colTarget, { + version: "20261128120014", + acceptRenameIds: [dropCol.id], + }); + expect(colRes.upSql).toContain('RENAME COLUMN "old_c" TO "new_c";'); + expect(colRes.upSql).toContain("ALTER COLUMN \"new_c\" SET DEFAULT 'b';"); + }); + + test("Orders SQL statements by dependency and expands SCHEMA_ADDED objects", () => { + const source: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [{ name: "public", tables: [], enums: [], views: [] }], + }; + const target: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { name: "public", tables: [], enums: [], views: [] }, + { + name: "reporting", + enums: [{ name: "status_enum", values: ["open", "closed"] }], + tables: [ + tbl( + "child_orders", + [col("id", "integer", { isPrimaryKey: true }), col("parent_id", "integer")], + { + foreignKeys: [ + { + name: "fk_parent", + columns: ["parent_id"], + referencedSchema: "reporting", + referencedTable: "parent_users", + referencedColumns: ["id"], + onDelete: "CASCADE", + onUpdate: "NO ACTION", + }, + ], + }, + ), + tbl("parent_users", [col("id", "integer", { isPrimaryKey: true })]), + ], + views: [{ name: "v_orders", definition: "SELECT id FROM reporting.child_orders" }], + }, + ], + }; + + const diff = diffSchemas(source, target); + const res = generateMigrationFromDiff(diff, source, target, { version: "20261128120015" }); + const schemaIdx = res.upSql!.indexOf('CREATE SCHEMA IF NOT EXISTS "reporting";'); + const enumIdx = res.upSql!.indexOf('CREATE TYPE "reporting"."status_enum"'); + const parentIdx = res.upSql!.indexOf('CREATE TABLE "reporting"."parent_users"'); + const childIdx = res.upSql!.indexOf('CREATE TABLE "reporting"."child_orders"'); + const viewIdx = res.upSql!.indexOf('CREATE VIEW "reporting"."v_orders"'); + + expect(schemaIdx).toBeGreaterThanOrEqual(0); + expect(enumIdx).toBeGreaterThan(schemaIdx); + expect(parentIdx).toBeGreaterThan(enumIdx); + expect(childIdx).toBeGreaterThan(parentIdx); + expect(viewIdx).toBeGreaterThan(childIdx); + }); + + test("PostgreSQL ENUM_MODIFIED preserves label order with BEFORE/AFTER and warns on reordering", () => { + const source: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [], + enums: [ + { name: "prio", values: ["low", "high"] }, + { name: "reord", values: ["b", "a"] }, + ], + views: [], + }, + ], + }; + const target: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [], + enums: [ + { name: "prio", values: ["first", "low", "medium", "high"] }, + { name: "reord", values: ["a", "b"] }, + ], + views: [], + }, + ], + }; + + const diff = diffSchemas(source, target); + const res = generateMigrationFromDiff(diff, source, target, { version: "20261128120016" }); + expect(res.upSql).toContain( + "ALTER TYPE \"public\".\"prio\" ADD VALUE IF NOT EXISTS 'first' BEFORE 'low';", + ); + expect(res.upSql).toContain( + "ALTER TYPE \"public\".\"prio\" ADD VALUE IF NOT EXISTS 'medium' AFTER 'low';", + ); + expect(res.warnings.some((w) => w.includes("cannot reorder existing enum values"))).toBe(true); + }); + + test("ClickHouse index changes and MongoDB view creation throw UnsupportedMigrationError", () => { + expect(() => + generateIndexMigration({ + dialect: "clickhouse", + createIndexes: [{ tableOrCollection: "events", indexName: "idx_e", columns: ["id"] }], + }), + ).toThrow(UnsupportedMigrationError); + + const mongoSource: CanonicalSchemaAST = { dialect: "mongodb", schemas: [], collections: [] }; + const mongoTarget: CanonicalSchemaAST = { + dialect: "mongodb", + schemas: [], + collections: [{ name: "active_view", type: "view", indexes: [] }], + }; + const mongoDiff = diffSchemas(mongoSource, mongoTarget); + expect(() => + generateMigrationFromDiff(mongoDiff, mongoSource, mongoTarget, { + version: "20261128120017", + }), + ).toThrow(UnsupportedMigrationError); + }); + + test("MongoDB rollback reverses operation groups without reversing MONGO_INDEX_MODIFIED internal steps", () => { + const source: CanonicalSchemaAST = { + dialect: "mongodb", + schemas: [], + collections: [ + { + name: "users", + type: "collection", + indexes: [ + { name: "_id_", key: { _id: 1 }, unique: true, sparse: false }, + { name: "email_idx", key: { email: 1 }, unique: false, sparse: false }, + ], + }, + ], + }; + const target: CanonicalSchemaAST = { + dialect: "mongodb", + schemas: [], + collections: [ + { + name: "users", + type: "collection", + indexes: [ + { name: "_id_", key: { _id: 1 }, unique: true, sparse: false }, + { name: "email_idx", key: { email: -1 }, unique: true, sparse: false }, + ], + }, + ], + }; + + const diff = diffSchemas(source, target); + const res = generateMigrationFromDiff(diff, source, target, { version: "20261128120018" }); + const down = res.manifest!.down!; + expect(down).toHaveLength(2); + expect(down[0].type).toBe("dropIndex"); + expect(down[1].type).toBe("createIndex"); + }); + + test("generateIndexMigration requires authoritative metadata for drop rollback", () => { + const sqlNoMeta = generateIndexMigration({ + dialect: "postgresql", + version: "20261128120019", + dropIndexes: [ + { schema: "public", tableOrCollection: "users", indexName: "idx_u", columns: ["email"] }, + ], + }); + expect(sqlNoMeta.downSql).toContain("MANUAL ROLLBACK REQUIRED"); + expect(sqlNoMeta.warnings.some((w) => w.includes("manual recreation"))).toBe(true); + + const sqlWithMeta = generateIndexMigration({ + dialect: "postgresql", + version: "20261128120020", + dropIndexes: [ + { + schema: "public", + tableOrCollection: "users", + indexName: "idx_u", + columns: ["email"], + unique: true, + }, + ], + }); + expect(sqlWithMeta.downSql).toContain( + 'CREATE UNIQUE INDEX "idx_u" ON "public"."users" ("email");', + ); + + const mongoNoMeta = generateIndexMigration({ + dialect: "mongodb", + version: "20261128120021", + dropIndexes: [{ tableOrCollection: "users", indexName: "idx_u", columns: ["email"] }], + }); + expect(mongoNoMeta.manifest!.allowIrreversible).toBe(true); + expect(mongoNoMeta.manifest!.down).toEqual([]); + + const mongoWithMeta = generateIndexMigration({ + dialect: "mongodb", + version: "20261128120022", + dropIndexes: [ + { + tableOrCollection: "users", + indexName: "idx_u", + key: { email: -1 }, + unique: true, + }, + ], + }); + expect(mongoWithMeta.manifest!.allowIrreversible).toBeUndefined(); + expect(mongoWithMeta.manifest!.down).toEqual([ + { + type: "createIndex", + collection: "users", + key: { email: -1 }, + options: { name: "idx_u", unique: true }, + }, + ]); + }); + + test("Inline 11: Composite primary key uses table.primaryKeyColumns order over name-sorted columns", () => { + const source: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [{ name: "public", tables: [], enums: [], views: [] }], + }; + const target: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + { + ...tbl("memberships", [ + // Sorted alphabetically (tenant_id before user_id) as normalizeColumns produces + col("tenant_id", "integer", { nullable: false, isPrimaryKey: true }), + col("user_id", "integer", { nullable: false, isPrimaryKey: true }), + ]), + primaryKeyColumns: ["user_id", "tenant_id"], + } as CanonicalTable, + ], + enums: [], + views: [], + }, + ], + }; + + const diff = diffSchemas(source, target); + const res = generateMigrationFromDiff(diff, source, target, { version: "20261128120030" }); + expect(res.upSql).toContain('PRIMARY KEY ("user_id", "tenant_id")'); + expect(res.upSql).not.toContain('PRIMARY KEY ("tenant_id", "user_id")'); + expect(res.upSql).not.toContain('"user_id" integer NOT NULL PRIMARY KEY'); + }); + + test("Inline 12: SQLite trigger check detects quoted special-char dropped columns and rejects unverifiable triggers", () => { + const target: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [tbl("items", [col("id", "integer", { nullable: false, isPrimaryKey: true })])], + enums: [], + views: [], + }, + ], + }; + + for (const trigSql of [ + 'CREATE TRIGGER trg_q AFTER INSERT ON items BEGIN SELECT NEW."qty$"; END', + "CREATE TRIGGER trg_bt AFTER INSERT ON items BEGIN SELECT NEW.`qty$`; END", + "CREATE TRIGGER trg_br AFTER INSERT ON items BEGIN SELECT NEW.[qty$]; END", + 'CREATE TRIGGER trg_upd AFTER UPDATE OF "qty$" ON items BEGIN SELECT 1; END', + 'CREATE TRIGGER trg_unclosed AFTER INSERT ON items BEGIN SELECT "unclosed; END', + "CREATE TRIGGER trg_incomplete AFTER INSERT ON items", + ]) { + const src: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [ + { + ...tbl("items", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("qty$", "integer"), + ]), + triggers: [{ name: "trg_test", sql: trigSql }], + } as CanonicalTable, + ], + enums: [], + views: [], + }, + ], + }; + const diff = diffSchemas(src, target, { detectRenames: false }); + expect(() => + generateMigrationFromDiff(diff, src, target, { version: "20261128120031" }), + ).toThrow(UnsupportedMigrationError); + } + + // String literal mentioning the dropped column name is not a column identifier reference + const srcSafeStringLit: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [ + { + ...tbl("items", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("qty$", "integer"), + ]), + triggers: [ + { + name: "trg_safe", + sql: "CREATE TRIGGER trg_safe AFTER INSERT ON items BEGIN SELECT 'qty$'; END", + }, + ], + } as CanonicalTable, + ], + enums: [], + views: [], + }, + ], + }; + const diffSafe = diffSchemas(srcSafeStringLit, target, { detectRenames: false }); + const resSafe = generateMigrationFromDiff(diffSafe, srcSafeStringLit, target, { + version: "20261128120032", + }); + expect(resSafe.upSql).toContain("CREATE TRIGGER trg_safe"); + }); + + test("Inline 13 & V3 Inline 1: SQLite rebuild directive toggles foreign_keys, ordinary migrations keep ON DELETE CASCADE active, and state asserts apply + rollback", async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "relwave-sqlite-fk-")); + try { + const dbPath = path.join(tmpDir, "test.db"); + const db = new Database(dbPath); + db.exec(SQLITE_CREATE_MIGRATION_TABLE); + db.exec(` + CREATE TABLE parents (id INTEGER PRIMARY KEY); + CREATE TABLE children (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES parents(id)); + INSERT INTO parents (id) VALUES (1); + INSERT INTO children (id, parent_id) VALUES (10, 1); + + CREATE TABLE cascade_parents (id INTEGER PRIMARY KEY); + CREATE TABLE cascade_children ( + id INTEGER PRIMARY KEY, + parent_id INTEGER REFERENCES cascade_parents(id) ON DELETE CASCADE + ); + INSERT INTO cascade_parents (id) VALUES (1); + INSERT INTO cascade_children (id, parent_id) VALUES (20, 1); + `); + db.close(); + + // Ordinary migration (without -- @relwave-sqlite-rebuild) keeps PRAGMA foreign_keys = ON, + // so ON DELETE CASCADE executes normally even if parent 1 is deleted and reinserted. + // Even a string literal containing the marker text must not disable foreign_keys. + const cascadeMigPath = path.join(tmpDir, "20261128120032_cascade_ordinary.sql"); + fs.writeFileSync( + cascadeMigPath, + [ + "-- 20261128120032_cascade_ordinary.sql", + "", + "-- +up", + "SELECT '-- @relwave-sqlite-rebuild';", + "DELETE FROM cascade_parents WHERE id = 1;", + "INSERT INTO cascade_parents (id) VALUES (1);", + "", + "-- +down", + "SELECT 1;", + "", + ].join("\n"), + "utf8", + ); + await expect(applyMigration({ path: dbPath }, cascadeMigPath)).resolves.toBe(true); + const afterCascadeDb = new Database(dbPath); + const cascadeChildCount = ( + afterCascadeDb.prepare("SELECT COUNT(*) AS c FROM cascade_children").get() as { c: number } + ).c; + afterCascadeDb.close(); + expect(cascadeChildCount).toBe(0); + + // A rebuild migration that creates a dangling FK violation should be rolled back by PRAGMA foreign_key_check + const badMigPath = path.join(tmpDir, "20261128120033_bad_fk.sql"); + fs.writeFileSync( + badMigPath, + `-- 20261128120033_bad_fk.sql\n\n-- +up\n-- @relwave-sqlite-rebuild\nDELETE FROM parents WHERE id = 1;\n\n-- +down\nINSERT INTO parents (id) VALUES (1);\n`, + "utf8", + ); + + await expect(applyMigration({ path: dbPath }, badMigPath)).rejects.toThrow( + /foreign_key_check/i, + ); + + // Verify transaction rolled back: parent row 1 is still intact and bad migration not recorded + const verifyAfterFail = new Database(dbPath); + const parentsCount = ( + verifyAfterFail.prepare("SELECT COUNT(*) AS c FROM parents").get() as { c: number } + ).c; + const migCount = ( + verifyAfterFail + .prepare("SELECT COUNT(*) AS c FROM schema_migrations WHERE version = '20261128120033'") + .get() as { c: number } + ).c; + verifyAfterFail.close(); + expect(parentsCount).toBe(1); + expect(migCount).toBe(0); + + // A valid rebuild migration that preserves FK integrity commits cleanly and rolls back cleanly + const goodMigPath = path.join(tmpDir, "20261128120034_valid_rebuild.sql"); + fs.writeFileSync( + goodMigPath, + [ + "-- 20261128120034_valid_rebuild.sql", + "", + "-- +up", + "-- @relwave-sqlite-rebuild", + 'CREATE TABLE "__relwave_new_parents" ("id" integer PRIMARY KEY, "label" text);', + 'INSERT INTO "__relwave_new_parents" ("id") SELECT "id" FROM "parents";', + 'DROP TABLE "parents";', + 'ALTER TABLE "__relwave_new_parents" RENAME TO "parents";', + "", + "-- +down", + "-- @relwave-sqlite-rebuild", + 'CREATE TABLE "__relwave_new_parents" ("id" integer PRIMARY KEY);', + 'INSERT INTO "__relwave_new_parents" ("id") SELECT "id" FROM "parents";', + 'DROP TABLE "parents";', + 'ALTER TABLE "__relwave_new_parents" RENAME TO "parents";', + "", + ].join("\n"), + "utf8", + ); + + await expect(applyMigration({ path: dbPath }, goodMigPath)).resolves.toBe(true); + const afterApplyDb = new Database(dbPath); + const colsAfterApply = afterApplyDb.prepare("PRAGMA table_info(parents)").all() as Array<{ + name: string; + }>; + const migAfterApply = afterApplyDb + .prepare("SELECT version FROM schema_migrations WHERE version = '20261128120034'") + .get() as { version: string } | undefined; + const childAfterApply = afterApplyDb + .prepare("SELECT parent_id FROM children WHERE id = 10") + .get() as { parent_id: number } | undefined; + afterApplyDb.close(); + expect(colsAfterApply.some((c) => c.name === "label")).toBe(true); + expect(migAfterApply?.version).toBe("20261128120034"); + expect(childAfterApply?.parent_id).toBe(1); + + await expect( + rollbackMigration({ path: dbPath }, "20261128120034", goodMigPath), + ).resolves.toBe(true); + const afterRollbackDb = new Database(dbPath); + const colsAfterRollback = afterRollbackDb + .prepare("PRAGMA table_info(parents)") + .all() as Array<{ + name: string; + }>; + const migAfterRollback = afterRollbackDb + .prepare("SELECT version FROM schema_migrations WHERE version = '20261128120034'") + .get() as { version: string } | undefined; + const childAfterRollback = afterRollbackDb + .prepare("SELECT parent_id FROM children WHERE id = 10") + .get() as { parent_id: number } | undefined; + afterRollbackDb.close(); + expect(colsAfterRollback.some((c) => c.name === "label")).toBe(false); + expect(migAfterRollback).toBeUndefined(); + expect(childAfterRollback?.parent_id).toBe(1); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + + test("Inline 14: FK_MODIFIED drops old FK before dropping old target and adds new FK after creating new target", () => { + const source: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + tbl("old_parent", [col("id", "integer", { nullable: false, isPrimaryKey: true })]), + tbl( + "child", + [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("parent_id", "integer"), + ], + { + foreignKeys: [ + { + name: "fk_parent", + columns: ["parent_id"], + referencedSchema: "public", + referencedTable: "old_parent", + referencedColumns: ["id"], + onDelete: "NO ACTION", + onUpdate: "NO ACTION", + }, + ], + }, + ), + ], + enums: [], + views: [], + }, + ], + }; + + const target: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + tbl("new_parent", [col("id", "integer", { nullable: false, isPrimaryKey: true })]), + tbl( + "child", + [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("parent_id", "integer"), + ], + { + foreignKeys: [ + { + name: "fk_parent", + columns: ["parent_id"], + referencedSchema: "public", + referencedTable: "new_parent", + referencedColumns: ["id"], + onDelete: "NO ACTION", + onUpdate: "NO ACTION", + }, + ], + }, + ), + ], + enums: [], + views: [], + }, + ], + }; + + const diff = diffSchemas(source, target, { detectRenames: false }); + const res = generateMigrationFromDiff(diff, source, target, { version: "20261128120035" }); + + const up = res.upSql!; + const dropFkIdx = up.indexOf( + 'ALTER TABLE "public"."child" DROP CONSTRAINT IF EXISTS "fk_parent";', + ); + const dropOldIdx = up.indexOf('DROP TABLE IF EXISTS "public"."old_parent";'); + const createNewIdx = up.indexOf('CREATE TABLE "public"."new_parent"'); + const addFkIdx = up.indexOf( + 'ALTER TABLE "public"."child" ADD CONSTRAINT "fk_parent" FOREIGN KEY ("parent_id") REFERENCES "public"."new_parent"', + ); + expect(dropFkIdx).toBeGreaterThanOrEqual(0); + expect(dropOldIdx).toBeGreaterThan(dropFkIdx); + expect(createNewIdx).toBeGreaterThan(dropOldIdx); + expect(addFkIdx).toBeGreaterThan(createNewIdx); + + const down = res.downSql!; + const downDropFkIdx = down.indexOf( + 'ALTER TABLE "public"."child" DROP CONSTRAINT IF EXISTS "fk_parent";', + ); + const downDropNewIdx = down.indexOf('DROP TABLE IF EXISTS "public"."new_parent";'); + const downCreateOldIdx = down.indexOf('CREATE TABLE "public"."old_parent"'); + const downAddFkIdx = down.indexOf( + 'ALTER TABLE "public"."child" ADD CONSTRAINT "fk_parent" FOREIGN KEY ("parent_id") REFERENCES "public"."old_parent"', + ); + expect(downDropFkIdx).toBeGreaterThanOrEqual(0); + expect(downDropNewIdx).toBeGreaterThan(downDropFkIdx); + expect(downCreateOldIdx).toBeGreaterThan(downDropNewIdx); + expect(downAddFkIdx).toBeGreaterThan(downCreateOldIdx); + }); + + test("Inline 15 & 18: Colon-containing schema/table names do not collide or split incorrectly", () => { + // Inline 15: schema "a" table "b:c" vs schema "a:b" table "c" + const source: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { name: "a", tables: [], enums: [], views: [] }, + { name: "a:b", tables: [], enums: [], views: [] }, + ], + }; + const target: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "a", + tables: [tbl("b:c", [col("id", "integer", { isPrimaryKey: true })])], + enums: [], + views: [], + }, + { + name: "a:b", + tables: [tbl("c", [col("id", "integer", { isPrimaryKey: true })])], + enums: [], + views: [], + }, + ], + }; + + const diffAdd = diffSchemas(source, target); + const resAdd = generateMigrationFromDiff(diffAdd, source, target, { + version: "20261128120036", + }); + expect(resAdd.upSql).toContain('CREATE TABLE "a"."b:c"'); + expect(resAdd.upSql).toContain('CREATE TABLE "a:b"."c"'); + + const diffDrop = diffSchemas(target, source); + const resDrop = generateMigrationFromDiff(diffDrop, target, source, { + version: "20261128120037", + }); + expect(resDrop.upSql).toContain('DROP TABLE IF EXISTS "a"."b:c";'); + expect(resDrop.upSql).toContain('DROP TABLE IF EXISTS "a:b"."c";'); + + // Inline 18: SQLite table named "sales:daily" routes through rebuild instead of MODIFY COLUMN + const sqSrc: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [ + tbl("sales:daily", [ + col("id", "integer", { isPrimaryKey: true }), + col("amt", "integer"), + ]), + ], + enums: [], + views: [], + }, + ], + }; + const sqTgt: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [ + tbl("sales:daily", [col("id", "integer", { isPrimaryKey: true }), col("amt", "real")]), + ], + enums: [], + views: [], + }, + ], + }; + const sqDiff = diffSchemas(sqSrc, sqTgt); + const sqRes = generateMigrationFromDiff(sqDiff, sqSrc, sqTgt, { version: "20261128120038" }); + expect(sqRes.upSql).toContain('CREATE TABLE "__relwave_new_sales:daily"'); + expect(sqRes.upSql).not.toContain("MODIFY COLUMN"); + }); + + test("Inline 16: Cyclic FK TABLE_DROPPED drops cyclic FKs before DROP TABLE and recreates tables before FKs on rollback", () => { + const source: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + tbl("a", [col("id", "integer", { isPrimaryKey: true }), col("b_id", "integer")], { + foreignKeys: [ + { + name: "fk_a_b", + columns: ["b_id"], + referencedSchema: "public", + referencedTable: "b", + referencedColumns: ["id"], + onDelete: "NO ACTION", + onUpdate: "NO ACTION", + }, + ], + }), + tbl("b", [col("id", "integer", { isPrimaryKey: true }), col("a_id", "integer")], { + foreignKeys: [ + { + name: "fk_b_a", + columns: ["a_id"], + referencedSchema: "public", + referencedTable: "a", + referencedColumns: ["id"], + onDelete: "NO ACTION", + onUpdate: "NO ACTION", + }, + ], + }), + ], + enums: [], + views: [], + }, + ], + }; + const target: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [{ name: "public", tables: [], enums: [], views: [] }], + }; + + const diff = diffSchemas(source, target); + const res = generateMigrationFromDiff(diff, source, target, { version: "20261128120039" }); + const up = res.upSql!; + const dropFkA = up.indexOf('ALTER TABLE "public"."a" DROP CONSTRAINT IF EXISTS "fk_a_b";'); + const dropFkB = up.indexOf('ALTER TABLE "public"."b" DROP CONSTRAINT IF EXISTS "fk_b_a";'); + const dropTableA = up.indexOf('DROP TABLE IF EXISTS "public"."a";'); + const dropTableB = up.indexOf('DROP TABLE IF EXISTS "public"."b";'); + expect(dropFkA).toBeGreaterThanOrEqual(0); + expect(dropFkB).toBeGreaterThanOrEqual(0); + expect(dropTableA).toBeGreaterThan(dropFkA); + expect(dropTableA).toBeGreaterThan(dropFkB); + expect(dropTableB).toBeGreaterThan(dropFkA); + expect(dropTableB).toBeGreaterThan(dropFkB); + + const down = res.downSql!; + const createA = down.indexOf('CREATE TABLE "public"."a"'); + const createB = down.indexOf('CREATE TABLE "public"."b"'); + const addFkA = down.indexOf('ALTER TABLE "public"."a" ADD CONSTRAINT "fk_a_b"'); + const addFkB = down.indexOf('ALTER TABLE "public"."b" ADD CONSTRAINT "fk_b_a"'); + expect(createA).toBeGreaterThanOrEqual(0); + expect(createB).toBeGreaterThanOrEqual(0); + expect(addFkA).toBeGreaterThan(createA); + expect(addFkA).toBeGreaterThan(createB); + expect(addFkB).toBeGreaterThan(createA); + expect(addFkB).toBeGreaterThan(createB); + }); + + test("Inline 17: Accepted table rename residual columns referencing new ENUM_ADDED run after CREATE TYPE", () => { + const source: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + tbl("old_orders", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("total", "integer", { nullable: false }), + ]), + ], + enums: [], + views: [], + }, + ], + }; + const target: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + tbl("orders", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("total", "integer", { nullable: false }), + col("status", '"public"."order_status"', { nullable: false }), + ]), + ], + enums: [{ name: "order_status", values: ["open", "closed"] }], + views: [], + }, + ], + }; + + const diff = diffSchemas(source, target, { detectRenames: true }); + const dropTable = diff.items.find((i) => i.type === "TABLE_DROPPED")!; + const res = generateMigrationFromDiff(diff, source, target, { + version: "20261128120040", + acceptRenameIds: [dropTable.id], + }); + + const createTypeIdx = res.upSql!.indexOf('CREATE TYPE "public"."order_status" AS ENUM'); + const renameIdx = res.upSql!.indexOf('ALTER TABLE "public"."old_orders" RENAME TO "orders";'); + const addColIdx = res.upSql!.indexOf('ALTER TABLE "public"."orders" ADD COLUMN "status"'); + expect(createTypeIdx).toBeGreaterThanOrEqual(0); + expect(renameIdx).toBeGreaterThan(createTypeIdx); + expect(addColIdx).toBeGreaterThan(renameIdx); + }); + + test("Inline 19: SQLite column rename with residual default change routes through table rebuild", () => { + const source: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [ + tbl("cfg", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("old_c", "text", { nullable: false, defaultValue: "'a'" }), + ]), + ], + enums: [], + views: [], + }, + ], + }; + const target: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [ + tbl("cfg", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("new_c", "text", { nullable: false, defaultValue: "'b'" }), + ]), + ], + enums: [], + views: [], + }, + ], + }; + + const diff = diffSchemas(source, target, { detectRenames: true }); + const dropCol = diff.items.find((i) => i.type === "COLUMN_DROPPED")!; + expect(dropCol.renameCandidate).toBe("new_c"); + + const res = generateMigrationFromDiff(diff, source, target, { + version: "20261128120041", + acceptRenameIds: [dropCol.id], + }); + expect(res.upSql).toContain('CREATE TABLE "__relwave_new_cfg"'); + expect(res.upSql).toContain("DEFAULT 'b'"); + expect(res.upSql).toContain( + 'INSERT INTO "__relwave_new_cfg" ("id", "new_c") SELECT "id", "old_c" FROM "cfg";', + ); + expect(res.upSql).not.toContain("MODIFY COLUMN"); + + // Pure SQLite column rename without residual change still uses direct RENAME COLUMN + const pureTarget: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [ + tbl("cfg", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("new_c", "text", { nullable: false, defaultValue: "'a'" }), + ]), + ], + enums: [], + views: [], + }, + ], + }; + const pureDiff = diffSchemas(source, pureTarget, { detectRenames: true }); + const pureDrop = pureDiff.items.find((i) => i.type === "COLUMN_DROPPED")!; + const pureRes = generateMigrationFromDiff(pureDiff, source, pureTarget, { + version: "20261128120042", + acceptRenameIds: [pureDrop.id], + }); + expect(pureRes.upSql).toContain('ALTER TABLE "cfg" RENAME COLUMN "old_c" TO "new_c";'); + expect(pureRes.upSql).not.toContain("__relwave_new_cfg"); + }); + + test("Inline 20: MongoDB TABLE_MODIFIED view/collection transition throws UnsupportedMigrationError", () => { + const source: CanonicalSchemaAST = { + dialect: "mongodb", + schemas: [], + collections: [{ name: "reports", type: "view", indexes: [] }], + }; + const target: CanonicalSchemaAST = { + dialect: "mongodb", + schemas: [], + collections: [{ name: "reports", type: "collection", indexes: [] }], + }; + const diff = diffSchemas(source, target); + expect(() => + generateMigrationFromDiff(diff, source, target, { version: "20261128120043" }), + ).toThrow(UnsupportedMigrationError); + }); + + test("Inline 21: Preserves supported PostgreSQL index methods on rollback, requires manual rollback for unsupported, and avoids double CREATE VIEW prefix", () => { + const supported = generateIndexMigration({ + dialect: "postgresql", + version: "20261128120044", + dropIndexes: [ + { + schema: "public", + tableOrCollection: "tokens", + indexName: "idx_tok_hash", + sqlDefinition: { + name: "idx_tok_hash", + columns: ["token"], + unique: false, + indexType: "hash", + }, + }, + { + schema: "public", + tableOrCollection: "docs", + indexName: "idx_docs_gin", + sqlDefinition: { + name: "idx_docs_gin", + columns: ["payload"], + unique: false, + indexType: "gin", + }, + }, + { + schema: "public", + tableOrCollection: "events", + indexName: "idx_events_btree", + sqlDefinition: { + name: "idx_events_btree", + columns: ["created_at"], + unique: false, + indexType: "btree", + }, + }, + ], + }); + expect(supported.downSql).toContain( + 'CREATE INDEX "idx_tok_hash" ON "public"."tokens" USING hash ("token");', + ); + expect(supported.downSql).toContain( + 'CREATE INDEX "idx_docs_gin" ON "public"."docs" USING gin ("payload");', + ); + expect(supported.downSql).toContain( + 'CREATE INDEX "idx_events_btree" ON "public"."events" ("created_at");', + ); + + const unsupported = generateIndexMigration({ + dialect: "postgresql", + version: "20261128120045", + dropIndexes: [ + { + schema: "public", + tableOrCollection: "embeddings", + indexName: "idx_vec", + sqlDefinition: { + name: "idx_vec", + columns: ["vec"], + unique: false, + indexType: "ivfflat", + }, + }, + ], + }); + expect(unsupported.downSql).toContain("MANUAL ROLLBACK REQUIRED"); + expect(unsupported.warnings.some((w) => w.includes("manual recreation"))).toBe(true); + + // View definition containing full CREATE VIEW ... AS DDL is not double-prefixed + const viewSource: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [{ name: "main", tables: [], enums: [], views: [] }], + }; + const viewTarget: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [], + enums: [], + views: [{ name: "v_items", definition: 'CREATE VIEW "v_items" AS SELECT 1 AS x;' }], + }, + ], + }; + const viewDiff = diffSchemas(viewSource, viewTarget); + const viewRes = generateMigrationFromDiff(viewDiff, viewSource, viewTarget, { + version: "20261128120046", + }); + expect(viewRes.upSql).toBe('CREATE VIEW "v_items" AS SELECT 1 AS x;'); + }); + + test("V3 Inline 1, 9, 10, 11, 12, 17, 20: rebuild marker, view columns, single-quoted trigger idents, dropped table unsupported index, supporting unique index ordering, PK diff error, and partial index drop rollback", () => { + // V3 Inline 1: generated SQLite rebuild emits -- @relwave-sqlite-rebuild in both upSql and downSql + const sqSrc: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [ + tbl("items", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("qty", "integer"), + ]), + ], + enums: [], + views: [], + }, + ], + }; + const sqTgt: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [ + tbl("items", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("qty", "real"), + ]), + ], + enums: [], + views: [], + }, + ], + }; + const sqDiff = diffSchemas(sqSrc, sqTgt); + const sqRes = generateMigrationFromDiff(sqDiff, sqSrc, sqTgt, { version: "20261129000001" }); + expect(sqRes.upSql).toContain("-- @relwave-sqlite-rebuild"); + expect(sqRes.downSql).toContain("-- @relwave-sqlite-rebuild"); + + // V3 Inline 9: retain explicit view column lists in forward and rollback SQL + const viewSrc: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [], + enums: [], + views: [ + { name: "v_old", definition: "CREATE VIEW v_old(display_id) AS SELECT id FROM items" }, + ], + }, + ], + }; + const viewTgt: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [], + enums: [], + views: [ + { + name: "v_new", + definition: "CREATE VIEW v_new(display_id, label) AS SELECT id, name FROM items;", + }, + { + name: "v_cols_prop", + columns: ["a", "b"], + definition: "SELECT 1, 2", + } as any, + ], + }, + ], + }; + const viewDiff = diffSchemas(viewSrc, viewTgt); + const viewRes = generateMigrationFromDiff(viewDiff, viewSrc, viewTgt, { + version: "20261129000002", + }); + expect(viewRes.upSql).toContain( + 'CREATE VIEW "v_new" (display_id, label) AS SELECT id, name FROM items;', + ); + expect(viewRes.upSql).toContain('CREATE VIEW "v_cols_prop" ("a", "b") AS SELECT 1, 2;'); + expect(viewRes.downSql).toContain('CREATE VIEW "v_old" (display_id) AS SELECT id FROM items;'); + + // V3 Inline 10: single-quoted qualified identifiers in SQLite triggers (NEW.'qty$', OLD.'qty$', tbl.'qty$') + const dropQtyTarget: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [tbl("items", [col("id", "integer", { nullable: false, isPrimaryKey: true })])], + enums: [], + views: [], + }, + ], + }; + for (const trigSql of [ + "CREATE TRIGGER trg_new_sq AFTER INSERT ON items BEGIN SELECT NEW.'qty$'; END", + "CREATE TRIGGER trg_old_sq AFTER DELETE ON items BEGIN SELECT OLD.'qty$'; END", + "CREATE TRIGGER trg_tbl_sq AFTER INSERT ON items BEGIN SELECT items.'qty$'; END", + ]) { + const trigSrc: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [ + { + ...tbl("items", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("qty$", "integer"), + ]), + triggers: [{ name: "trg_sq", sql: trigSql }], + } as CanonicalTable, + ], + enums: [], + views: [], + }, + ], + }; + const trigDiff = diffSchemas(trigSrc, dropQtyTarget, { detectRenames: false }); + expect(() => + generateMigrationFromDiff(trigDiff, trigSrc, dropQtyTarget, { version: "20261129000003" }), + ).toThrow(UnsupportedMigrationError); + } + + // V3 Inline 11: TABLE_DROPPED with PostgreSQL ivfflat index emits manual rollback warning & succeeds forward DROP TABLE + const pgDropSrc: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + tbl( + "embeddings", + [col("id", "integer", { isPrimaryKey: true }), col("vec", "vector")], + { + indexes: [ + { name: "idx_vec", columns: ["vec"], unique: false, indexType: "ivfflat" }, + ], + }, + ), + ], + enums: [], + views: [], + }, + ], + }; + const pgEmptyTgt: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [{ name: "public", tables: [], enums: [], views: [] }], + }; + const pgDropDiff = diffSchemas(pgDropSrc, pgEmptyTgt); + const pgDropRes = generateMigrationFromDiff(pgDropDiff, pgDropSrc, pgEmptyTgt, { + version: "20261129000004", + }); + expect(pgDropRes.upSql).toContain('DROP TABLE IF EXISTS "public"."embeddings";'); + expect(pgDropRes.downSql).toContain("MANUAL ROLLBACK REQUIRED"); + expect(pgDropRes.warnings.some((w) => w.includes("manual recreation"))).toBe(true); + + // Forward INDEX_ADDED with ivfflat still throws UnsupportedMigrationError + const pgAddIdxDiff = diffSchemas(pgEmptyTgt, pgDropSrc); + expect(() => + generateMigrationFromDiff(pgAddIdxDiff, pgEmptyTgt, pgDropSrc, { + version: "20261129000005", + }), + ).toThrow(UnsupportedMigrationError); + + // V3 Inline 12: supporting non-partial unique INDEX_ADDED before referencing TABLE_ADDED FK (PostgreSQL & SQLite) + const pgFkSrc: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + tbl("parent", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("code", "text", { nullable: false }), + ]), + ], + enums: [], + views: [], + }, + ], + }; + const pgFkTgt: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + tbl( + "parent", + [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("code", "text", { nullable: false }), + ], + { + indexes: [{ name: "idx_parent_code", columns: ["code"], unique: true }], + }, + ), + tbl( + "child", + [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("parent_code", "text", { nullable: false }), + ], + { + foreignKeys: [ + { + name: "fk_child_parent_code", + columns: ["parent_code"], + referencedSchema: "public", + referencedTable: "parent", + referencedColumns: ["code"], + onDelete: "NO ACTION", + onUpdate: "NO ACTION", + }, + ], + }, + ), + ], + enums: [], + views: [], + }, + ], + }; + const pgFkDiff = diffSchemas(pgFkSrc, pgFkTgt); + const pgFkRes = generateMigrationFromDiff(pgFkDiff, pgFkSrc, pgFkTgt, { + version: "20261129000006", + }); + const upIdxPos = pgFkRes.upSql!.indexOf('CREATE UNIQUE INDEX "idx_parent_code"'); + const upFkPos = pgFkRes.upSql!.indexOf('ADD CONSTRAINT "fk_child_parent_code"'); + expect(upIdxPos).toBeGreaterThanOrEqual(0); + expect(upFkPos).toBeGreaterThan(upIdxPos); + const downDropFkPos = pgFkRes.downSql!.indexOf( + 'DROP CONSTRAINT IF EXISTS "fk_child_parent_code"', + ); + const downDropIdxPos = pgFkRes.downSql!.indexOf( + 'DROP INDEX IF EXISTS "public"."idx_parent_code"', + ); + expect(downDropFkPos).toBeGreaterThanOrEqual(0); + expect(downDropIdxPos).toBeGreaterThan(downDropFkPos); + + // SQLite: supporting unique INDEX_ADDED on existing parent runs before CREATE TABLE child + const sqFkSrc: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [ + tbl("parent", [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("code", "text", { nullable: false }), + ]), + ], + enums: [], + views: [], + }, + ], + }; + const sqFkTgt: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [ + tbl( + "parent", + [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("code", "text", { nullable: false }), + ], + { + indexes: [{ name: "idx_parent_code", columns: ["code"], unique: true }], + }, + ), + tbl( + "child", + [ + col("id", "integer", { nullable: false, isPrimaryKey: true }), + col("parent_code", "text", { nullable: false }), + ], + { + foreignKeys: [ + { + name: "fk_child_parent_code", + columns: ["parent_code"], + referencedSchema: "main", + referencedTable: "parent", + referencedColumns: ["code"], + onDelete: "NO ACTION", + onUpdate: "NO ACTION", + }, + ], + }, + ), + ], + enums: [], + views: [], + }, + ], + }; + const sqFkDiff = diffSchemas(sqFkSrc, sqFkTgt); + const sqFkRes = generateMigrationFromDiff(sqFkDiff, sqFkSrc, sqFkTgt, { + version: "20261129000007", + }); + const sqUpIdxPos = sqFkRes.upSql!.indexOf('CREATE UNIQUE INDEX "idx_parent_code"'); + const sqUpTblPos = sqFkRes.upSql!.indexOf('CREATE TABLE "child"'); + expect(sqUpIdxPos).toBeGreaterThanOrEqual(0); + expect(sqUpTblPos).toBeGreaterThan(sqUpIdxPos); + const sqDownDropTblPos = sqFkRes.downSql!.indexOf('DROP TABLE IF EXISTS "child";'); + const sqDownDropIdxPos = sqFkRes.downSql!.indexOf('DROP INDEX IF EXISTS "idx_parent_code";'); + expect(sqDownDropTblPos).toBeGreaterThanOrEqual(0); + expect(sqDownDropIdxPos).toBeGreaterThan(sqDownDropTblPos); + + // V3 Inline 17: TABLE_MODIFIED with primaryKeyColumns or diffSchemas PK reorder throws UnsupportedMigrationError + const pkDiff = { + hasChanges: true, + sourceLabel: "src", + targetLabel: "tgt", + dialect: "postgresql" as const, + summary: { total: 1, safe: 0, warning: 1, destructive: 0 }, + items: [ + { + id: "TABLE_MODIFIED:public:memberships", + type: "TABLE_MODIFIED" as const, + severity: "warning" as const, + schema: "public", + tableOrCollection: "memberships", + before: { primaryKeyColumns: ["tenant_id", "user_id"] }, + after: { primaryKeyColumns: ["user_id", "tenant_id"] }, + details: "Primary key order changed", + }, + ], + }; + expect(() => + generateMigrationFromDiff(pkDiff, pgEmptyTgt, pgEmptyTgt, { version: "20261129000008" }), + ).toThrow(UnsupportedMigrationError); + + const pkReorderSrc: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + { + ...tbl("memberships", [ + col("tenant_id", "integer", { nullable: false, isPrimaryKey: true }), + col("user_id", "integer", { nullable: false, isPrimaryKey: true }), + ]), + primaryKeyColumns: ["tenant_id", "user_id"], + } as CanonicalTable, + ], + enums: [], + views: [], + }, + ], + }; + const pkReorderTgt: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + { + ...tbl("memberships", [ + col("tenant_id", "integer", { nullable: false, isPrimaryKey: true }), + col("user_id", "integer", { nullable: false, isPrimaryKey: true }), + ]), + primaryKeyColumns: ["user_id", "tenant_id"], + } as CanonicalTable, + ], + enums: [], + views: [], + }, + ], + }; + const pkReorderDiff = diffSchemas(pkReorderSrc, pkReorderTgt); + expect(() => + generateMigrationFromDiff(pkReorderDiff, pkReorderSrc, pkReorderTgt, { + version: "20261129000011", + }), + ).toThrow(UnsupportedMigrationError); + + // V3 Inline 20 bridge: generateIndexMigration dropIndexes predicate and isPartial handling + const withPred = generateIndexMigration({ + dialect: "postgresql", + version: "20261129000009", + dropIndexes: [ + { + schema: "public", + tableOrCollection: "users", + indexName: "idx_active_email", + columns: ["email"], + unique: true, + isPartial: true, + predicate: "active = true", + }, + ], + }); + expect(withPred.downSql).toContain( + 'CREATE UNIQUE INDEX "idx_active_email" ON "public"."users" ("email") WHERE active = true;', + ); + + const missingPred = generateIndexMigration({ + dialect: "postgresql", + version: "20261129000010", + dropIndexes: [ + { + schema: "public", + tableOrCollection: "users", + indexName: "idx_active_email", + columns: ["email"], + unique: true, + isPartial: true, + }, + ], + }); + expect(missingPred.downSql).toContain("MANUAL ROLLBACK REQUIRED"); + expect(missingPred.warnings.some((w) => w.includes("partial predicate unavailable"))).toBe( + true, + ); + }); +}); diff --git a/bridge/__tests__/migrationHandlers.test.ts b/bridge/__tests__/migrationHandlers.test.ts new file mode 100644 index 00000000..f3dcb824 --- /dev/null +++ b/bridge/__tests__/migrationHandlers.test.ts @@ -0,0 +1,899 @@ +import { afterEach, beforeEach, describe, expect, jest, test } from "@jest/globals"; +import crypto from "crypto"; +import fs from "fs"; +import path from "path"; + +jest.mock("../src/utils/config", () => { + const original = jest.requireActual("../src/utils/config") as any; + const _path = require("path"); + const _os = require("os"); + const baseDir = _path.join( + _os.tmpdir(), + `migration-handlers-test-${Date.now()}-${Math.random().toString(36).slice(2)}`, + ); + const testProjects = _path.join(baseDir, "projects"); + return { + ...original, + CONFIG_FOLDER: baseDir, + PROJECTS_FOLDER: testProjects, + PROJECTS_INDEX_FILE: _path.join(testProjects, "index.json"), + getProjectDir: (id: string) => _path.join(testProjects, id), + }; +}); + +const mockGetDB = jest.fn<() => Promise>(); +jest.mock("../src/services/dbStore", () => ({ + dbStoreInstance: { + getDB: mockGetDB, + }, + DBMeta: {}, +})); + +const mockIntrospectLiveCanonicalAST = jest.fn<(...args: any[]) => Promise>(); +jest.mock("../src/services/liveSchemaIntrospector", () => ({ + introspectLiveCanonicalAST: (...args: any[]) => mockIntrospectLiveCanonicalAST(...args), +})); + +const mockGetConnector = jest.fn<(...args: any[]) => any>(); +jest.mock("../src/services/connectorRegistry", () => ({ + getConnector: (...args: any[]) => mockGetConnector(...args), +})); + +import { CONFIG_FOLDER, PROJECTS_FOLDER, PROJECTS_INDEX_FILE } from "../src/utils/config"; +import { ProjectStore, projectStoreInstance } from "../src/services/projectStore"; +import { MigrationHandlers } from "../src/handlers/migrationHandlers"; +import type { CanonicalSchemaAST } from "../src/types/schemaDiff"; + +function createMockRpc() { + const responses: Array<{ id: number | string; payload: any }> = []; + const errors: Array<{ id: number | string; err: any }> = []; + const notifications: Array<{ method: string; params: any }> = []; + return { + responses, + errors, + notifications, + rpc: { + sendResponse: jest.fn((id: number | string, payload: any) => { + responses.push({ id, payload }); + }), + sendError: jest.fn((id: number | string, err: any) => { + errors.push({ id, err }); + }), + sendNotification: jest.fn((method: string, params: any) => { + notifications.push({ method, params }); + }), + } as any, + }; +} + +const silentLogger = { + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), + debug: jest.fn(), +} as any; + +describe("MigrationHandlers & ProjectStore fixes", () => { + beforeEach(async () => { + jest.clearAllMocks(); + if (fs.existsSync(CONFIG_FOLDER)) { + fs.rmSync(CONFIG_FOLDER, { recursive: true, force: true }); + } + fs.mkdirSync(PROJECTS_FOLDER, { recursive: true }); + // Reset singleton internal sourcePathCache if needed by clearing index + (projectStoreInstance as any).sourcePathCache.clear(); + (projectStoreInstance as any).cacheLoaded = false; + }); + + afterEach(() => { + if (fs.existsSync(CONFIG_FOLDER)) { + fs.rmSync(CONFIG_FOLDER, { recursive: true, force: true }); + } + }); + + test("Inline 2b: ProjectStore.saveSchema stores non-SQLite dialects and repairs stale dialect on same-content return", async () => { + mockGetDB.mockResolvedValue({ id: "db-duck", type: "duckdb" }); + const store = new ProjectStore(PROJECTS_FOLDER, PROJECTS_INDEX_FILE); + const project = await store.createProject({ + databaseId: "db-duck", + name: "DuckProject", + }); + + const schemas = [ + { + name: "main", + tables: [ + { + name: "metrics", + type: "BASE TABLE", + columns: [ + { + name: "id", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ], + enums: [], + views: [], + }, + ]; + + // Saving without explicit dialect derives "duckdb" from project engine instead of "sqlite" + const saved = await store.saveSchema(project.id, schemas, "hash-1"); + expect(saved.dialect).toBe("duckdb"); + + // Simulate an existing snapshot with a stale "sqlite" dialect label + const schemaPath = path.join(PROJECTS_FOLDER, project.id, "schema", "schema.json"); + const staleFile = JSON.parse(fs.readFileSync(schemaPath, "utf8")); + staleFile.dialect = "sqlite"; + fs.writeFileSync(schemaPath, JSON.stringify(staleFile, null, 2), "utf8"); + + // Same-content saveSchema repairs the stale dialect while preserving cachedAt + const repaired = await store.saveSchema(project.id, schemas, "hash-1", "duckdb"); + expect(repaired.dialect).toBe("duckdb"); + expect(repaired.cachedAt).toBe(staleFile.cachedAt); + const onDisk = JSON.parse(fs.readFileSync(schemaPath, "utf8")); + expect(onDisk.dialect).toBe("duckdb"); + }); + + test("Inline 2b: resolveSchemaDiff repairs stale sqlite dialect on DuckDB snapshot in live-vs-snapshot mode", async () => { + mockGetDB.mockResolvedValue({ id: "db-duck", type: "duckdb" }); + const project = await projectStoreInstance.createProject({ + databaseId: "db-duck", + name: "DuckLiveDiff", + }); + + const schemas = [ + { + name: "main", + tables: [ + { + name: "metrics", + type: "BASE TABLE", + columns: [ + { + name: "id", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ], + enums: [], + views: [], + }, + ]; + await projectStoreInstance.saveSchema(project.id, schemas, "h1", "duckdb"); + // Force stale "sqlite" label onto disk + const schemaPath = path.join(PROJECTS_FOLDER, project.id, "schema", "schema.json"); + const raw = JSON.parse(fs.readFileSync(schemaPath, "utf8")); + raw.dialect = "sqlite"; + fs.writeFileSync(schemaPath, JSON.stringify(raw, null, 2), "utf8"); + + const liveAst: CanonicalSchemaAST = { + dialect: "duckdb", + schemas: [ + { + name: "main", + tables: [ + { + name: "metrics", + type: "BASE TABLE", + columns: [ + { + name: "id", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + comment: null, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + comment: null, + }, + ], + enums: [], + views: [], + }, + ], + }; + mockIntrospectLiveCanonicalAST.mockResolvedValue(liveAst); + + const { rpc, responses, errors } = createMockRpc(); + const handlers = new MigrationHandlers(rpc, silentLogger, {} as any, {} as any); + await handlers.handleDiffSchema({ projectId: project.id, mode: "live-vs-snapshot" }, 1); + + expect(errors).toEqual([]); + expect(responses[0].payload.ok).toBe(true); + expect(responses[0].payload.data.dialect).toBe("duckdb"); + expect(responses[0].payload.data.hasChanges).toBe(false); + const repairedOnDisk = JSON.parse(fs.readFileSync(schemaPath, "utf8")); + expect(repairedOnDisk.dialect).toBe("duckdb"); + }); + + test("Inline 2a: incomplete legacy snapshot omitting views does not emit false VIEW_ADDED, and applyMigration saves views", async () => { + mockGetDB.mockResolvedValue({ id: "db-pg", type: "postgresql" }); + const project = await projectStoreInstance.createProject({ + databaseId: "db-pg", + name: "PgViews", + }); + + // Older snapshot saved without `views` key on schema + await projectStoreInstance.saveSchema( + project.id, + [ + { + name: "public", + tables: [ + { + name: "users", + type: "BASE TABLE", + columns: [ + { + name: "id", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ], + enums: [], + }, + ], + "h-old", + "postgresql", + ); + + const liveAstWithView: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + { + name: "users", + type: "BASE TABLE", + columns: [ + { + name: "id", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + comment: null, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + comment: null, + }, + ], + enums: [], + views: [{ name: "active_users", definition: "SELECT id FROM public.users" }], + }, + ], + }; + mockIntrospectLiveCanonicalAST.mockResolvedValue(liveAstWithView); + + const { rpc, responses, errors } = createMockRpc(); + const dbService = { + getDatabaseConnection: jest.fn(async () => ({ conn: {}, dbType: "postgresql" })), + withConnection: jest.fn(), + } as any; + const handlers = new MigrationHandlers(rpc, silentLogger, dbService, {} as any); + + await handlers.handleDiffSchema({ projectId: project.id, mode: "live-vs-snapshot" }, 1); + expect(errors).toEqual([]); + expect(responses[0].payload.data.items).toEqual([]); + expect(responses[0].payload.data.hasChanges).toBe(false); + expect(responses[0].payload.data.coverageWarnings?.length).toBeGreaterThan(0); + + // Apply a migration and verify refreshed snapshot persists `views` + const migrationsDir = await projectStoreInstance.resolveProjectMigrationsDir(project.id); + fs.writeFileSync( + path.join(migrationsDir, "20261128120000_init.sql"), + "-- +up\nSELECT 1;\n-- +down\nSELECT 1;\n", + "utf8", + ); + mockGetConnector.mockReturnValue({ + applyMigration: jest.fn(async () => true), + listAppliedMigrations: jest.fn(async () => [{ version: "20261128120000" }]), + }); + + await handlers.handleApplyMigration({ dbId: "db-pg", version: "20261128120000" }, 2); + const updatedSchema = await projectStoreInstance.getSchema(project.id); + expect(updatedSchema?.schemas[0].views).toEqual([ + { name: "active_users", definition: "SELECT id FROM public.users" }, + ]); + }); + + test("Inline 3: handleGenerateFromDiff rejects save when expectedContentHash mismatches live regeneration", async () => { + mockGetDB.mockResolvedValue({ id: "db-pg-hash", type: "postgresql" }); + const project = await projectStoreInstance.createProject({ + databaseId: "db-pg-hash", + name: "HashCheck", + }); + + await projectStoreInstance.saveSchema( + project.id, + [ + { + name: "public", + tables: [ + { + name: "users", + type: "BASE TABLE", + columns: [ + { + name: "id", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ], + enums: [], + views: [], + }, + ], + "h1", + "postgresql", + ); + + const previewLiveAst: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + { + name: "users", + type: "BASE TABLE", + columns: [ + { + name: "id", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + { + name: "email", + type: "text", + nullable: true, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 2, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ], + enums: [], + views: [], + }, + ], + }; + mockIntrospectLiveCanonicalAST.mockResolvedValueOnce(previewLiveAst); + + const { rpc, responses, errors } = createMockRpc(); + const handlers = new MigrationHandlers(rpc, silentLogger, {} as any, {} as any); + + await handlers.handleGenerateFromDiff( + { + projectId: project.id, + name: "add_email", + version: "20261128120000", + save: false, + }, + 1, + ); + expect(errors).toEqual([]); + const previewContent: string = responses[0].payload.data.content; + const expectedContentHash = crypto + .createHash("sha256") + .update(previewContent.replace(/\r\n/g, "\n")) + .digest("hex"); + + // Simulate live DB changing (non-destructive addition of another column) before Save + const driftedLiveAst: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + { + ...previewLiveAst.schemas[0].tables[0], + columns: [ + ...previewLiveAst.schemas[0].tables[0].columns, + { + name: "bio", + type: "text", + nullable: true, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 3, + }, + ], + }, + ], + enums: [], + views: [], + }, + ], + }; + mockIntrospectLiveCanonicalAST.mockResolvedValueOnce(driftedLiveAst); + + await handlers.handleGenerateFromDiff( + { + projectId: project.id, + name: "add_email", + version: "20261128120000", + save: true, + expectedContentHash, + }, + 2, + ); + + expect(errors).toHaveLength(1); + expect(errors[0].err.code).toBe("STALE_PREVIEW_ERROR"); + + const migrationsDir = await projectStoreInstance.resolveProjectMigrationsDir(project.id); + expect(fs.readdirSync(migrationsDir)).toEqual([]); + + // Matching hash saves successfully + mockIntrospectLiveCanonicalAST.mockResolvedValueOnce(previewLiveAst); + await handlers.handleGenerateFromDiff( + { + projectId: project.id, + name: "add_email", + version: "20261128120000", + save: true, + expectedContentHash, + }, + 3, + ); + expect(responses).toHaveLength(2); + expect(fs.readdirSync(migrationsDir)).toEqual(["20261128120000_add_email.sql"]); + }); + + test("Inline 4 & 5: saves target requesting project's migrations dir and create files exclusively without overwriting on collision", async () => { + mockGetDB.mockResolvedValue({ id: "shared-db", type: "postgresql" }); + const projectA = await projectStoreInstance.createProject({ + databaseId: "shared-db", + name: "ProjectA", + }); + const projectB = await projectStoreInstance.createProject({ + databaseId: "shared-db", + name: "ProjectB", + }); + + const { rpc, responses, errors } = createMockRpc(); + const handlers = new MigrationHandlers(rpc, silentLogger, {} as any, {} as any); + + // Save two index scaffolds with the exact same version & name into ProjectB + await handlers.handleScaffoldIndexMigration( + { + projectId: projectB.id, + name: "idx_copilot", + version: "20261128120000", + save: true, + createIndexes: [ + { + schema: "public", + tableOrCollection: "users", + indexName: "idx_users_email", + columns: ["email"], + }, + ], + }, + 1, + ); + await handlers.handleScaffoldIndexMigration( + { + projectId: projectB.id, + name: "idx_copilot", + version: "20261128120000", + save: true, + createIndexes: [ + { + schema: "public", + tableOrCollection: "users", + indexName: "idx_users_name", + columns: ["name"], + }, + ], + }, + 2, + ); + + expect(errors).toEqual([]); + const dirA = await projectStoreInstance.resolveProjectMigrationsDir(projectA.id); + const dirB = await projectStoreInstance.resolveProjectMigrationsDir(projectB.id); + + // ProjectA's migrations directory was untouched + expect(fs.readdirSync(dirA)).toEqual([]); + + // ProjectB has both files with distinct incremented versions and intact original content + const filesB = fs.readdirSync(dirB).sort(); + expect(filesB).toEqual(["20261128120000_idx_copilot.sql", "20261128120001_idx_copilot.sql"]); + expect(fs.readFileSync(path.join(dirB, filesB[0]), "utf8")).toContain("idx_users_email"); + expect(fs.readFileSync(path.join(dirB, filesB[1]), "utf8")).toContain("idx_users_name"); + expect(responses[1].payload.data.version).toBe("20261128120001"); + }); + + test("V3 Inline 2: explicit views: [] preserves VIEW_ADDED, while omitted views surfaces coverageWarnings in diff and preview", async () => { + mockGetDB.mockResolvedValue({ id: "db-pg-views2", type: "postgresql" }); + const project = await projectStoreInstance.createProject({ + databaseId: "db-pg-views2", + name: "ViewsCoverage", + }); + + const baseTable = { + name: "users", + type: "BASE TABLE", + columns: [ + { + name: "id", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + comment: null, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }; + + const liveAstWithView: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [{ ...baseTable, comment: null }], + enums: [], + views: [{ name: "active_users", definition: "SELECT id FROM public.users" }], + }, + ], + }; + mockIntrospectLiveCanonicalAST.mockResolvedValue(liveAstWithView); + + // 1. Legacy snapshot without `views` omits VIEW_ADDED and adds coverageWarnings in both diff & preview + await projectStoreInstance.saveSchema( + project.id, + [{ name: "public", tables: [baseTable], enums: [] }], + "h-legacy", + "postgresql", + ); + + const { rpc, responses, errors } = createMockRpc(); + const handlers = new MigrationHandlers(rpc, silentLogger, {} as any, {} as any); + await handlers.handleGenerateFromDiff( + { projectId: project.id, mode: "live-vs-snapshot", save: false }, + 1, + ); + expect(errors).toEqual([]); + expect(responses[0].payload.data.diff.hasChanges).toBe(false); + expect(responses[0].payload.data.diff.coverageWarnings?.length).toBeGreaterThan(0); + expect(responses[0].payload.data.warnings.length).toBeGreaterThan(0); + + // 2. Snapshot with explicit `views: []` preserves confirmed VIEW_ADDED and has no coverageWarnings + await projectStoreInstance.saveSchema( + project.id, + [{ name: "public", tables: [baseTable], enums: [], views: [] }], + "h-modern", + "postgresql", + ); + await handlers.handleGenerateFromDiff( + { projectId: project.id, mode: "live-vs-snapshot", save: false }, + 2, + ); + expect(errors).toEqual([]); + expect(responses[1].payload.data.diff.hasChanges).toBe(true); + expect(responses[1].payload.data.diff.items.map((i: any) => i.type)).toEqual(["VIEW_ADDED"]); + expect(responses[1].payload.data.diff.coverageWarnings).toBeUndefined(); + }); + + test("V3 Inline 3: refreshProjectSchemaSnapshot returns new hash only after saveSchema succeeds and survives notification errors", async () => { + mockGetDB.mockResolvedValue({ id: "db-hash-fallback", type: "postgresql" }); + const project = await projectStoreInstance.createProject({ + databaseId: "db-hash-fallback", + name: "RefreshHash", + }); + await projectStoreInstance.saveSchema(project.id, [], "stored-hash-fallback", "postgresql"); + + const migrationsDir = await projectStoreInstance.resolveProjectMigrationsDir(project.id); + fs.writeFileSync( + path.join(migrationsDir, "20261129100000_init.sql"), + "-- +up\nSELECT 1;\n-- +down\nSELECT 1;\n", + "utf8", + ); + + mockGetConnector.mockReturnValue({ + applyMigration: jest.fn(async () => true), + listAppliedMigrations: jest.fn(async () => [{ version: "20261129100000" }]), + }); + mockIntrospectLiveCanonicalAST.mockResolvedValue({ + dialect: "postgresql", + schemas: [{ name: "public", tables: [], enums: [], views: [] }], + }); + + const dbService = { + getDatabaseConnection: jest.fn(async () => ({ conn: {}, dbType: "postgresql" })), + withConnection: jest.fn(), + } as any; + const { rpc, errors } = createMockRpc(); + const handlers = new MigrationHandlers(rpc, silentLogger, dbService, {} as any); + + // 1. saveSchema rejects -> lock must receive stored-hash-fallback, not computed unsaved hash + const saveSpy = jest + .spyOn(projectStoreInstance, "saveSchema") + .mockRejectedValueOnce(new Error("disk full")); + await handlers.handleApplyMigration( + { dbId: "db-hash-fallback", projectId: project.id, version: "20261129100000" }, + 1, + ); + expect(errors).toEqual([]); + const lockAfterSaveFail = JSON.parse( + fs.readFileSync(path.join(migrationsDir, "migration.lock.json"), "utf8"), + ); + expect(lockAfterSaveFail.schemaHash).toBe("stored-hash-fallback"); + saveSpy.mockRestore(); + + // 2. saveSchema succeeds, sendNotification throws -> lock must still receive the newly saved hash + (rpc.sendNotification as jest.Mock).mockImplementationOnce(() => { + throw new Error("notification pipe closed"); + }); + await handlers.handleApplyMigration( + { dbId: "db-hash-fallback", projectId: project.id, version: "20261129100000" }, + 2, + ); + const lockAfterNotifyFail = JSON.parse( + fs.readFileSync(path.join(migrationsDir, "migration.lock.json"), "utf8"), + ); + const expectedNewHash = crypto + .createHash("sha256") + .update(JSON.stringify([{ name: "public", tables: [], enums: [], views: [] }])) + .digest("hex"); + expect(lockAfterNotifyFail.schemaHash).toBe(expectedNewHash); + }); + + test("V3 Inline 4: resolveSchemaDiff does not overwrite a newer snapshot written during live introspection", async () => { + mockGetDB.mockResolvedValue({ id: "db-race", type: "duckdb" }); + const project = await projectStoreInstance.createProject({ + databaseId: "db-race", + name: "DialectRepairRace", + }); + + await projectStoreInstance.saveSchema(project.id, [], "old-hash", "duckdb"); + const schemaPath = path.join(PROJECTS_FOLDER, project.id, "schema", "schema.json"); + const raw = JSON.parse(fs.readFileSync(schemaPath, "utf8")); + raw.dialect = "sqlite"; + fs.writeFileSync(schemaPath, JSON.stringify(raw, null, 2), "utf8"); + + const newerSchemas = [ + { + name: "main", + tables: [ + { + name: "newer_tbl", + type: "BASE TABLE", + columns: [], + indexes: [], + foreignKeys: [], + checks: [], + }, + ], + enums: [], + views: [], + }, + ]; + + mockIntrospectLiveCanonicalAST.mockImplementationOnce(async () => { + // Simulate concurrent snapshot refresh completing before introspection returns + await new Promise((r) => setTimeout(r, 15)); + await projectStoreInstance.saveSchema(project.id, newerSchemas, "newer-hash", "duckdb"); + return { + dialect: "duckdb", + schemas: newerSchemas, + }; + }); + + const { rpc, errors } = createMockRpc(); + const handlers = new MigrationHandlers(rpc, silentLogger, {} as any, {} as any); + await handlers.handleDiffSchema({ projectId: project.id, mode: "live-vs-snapshot" }, 1); + expect(errors).toEqual([]); + + const onDisk = JSON.parse(fs.readFileSync(schemaPath, "utf8")); + expect(onDisk.schemaHash).toBe("newer-hash"); + expect(onDisk.schemas).toHaveLength(1); + expect(onDisk.schemas[0].tables[0].name).toBe("newer_tbl"); + }); + + test("V3 Inline 5: SQL list/getSQL/apply/applyMigrations/rollback/delete use resolveProjectMigrationsDir when projectId is supplied", async () => { + mockGetDB.mockResolvedValue({ id: "shared-db-2", type: "postgresql" }); + const projectA = await projectStoreInstance.createProject({ + databaseId: "shared-db-2", + name: "ProjA", + }); + const projectB = await projectStoreInstance.createProject({ + databaseId: "shared-db-2", + name: "ProjB", + }); + + const dirA = await projectStoreInstance.resolveProjectMigrationsDir(projectA.id); + const dirB = await projectStoreInstance.resolveProjectMigrationsDir(projectB.id); + + fs.writeFileSync( + path.join(dirA, "20261129110000_proj_a.sql"), + "-- +up\nSELECT 'A';\n-- +down\nSELECT 'A_DOWN';\n", + "utf8", + ); + fs.writeFileSync( + path.join(dirB, "20261129110001_proj_b.sql"), + "-- +up\nSELECT 'B';\n-- +down\nSELECT 'B_DOWN';\n", + "utf8", + ); + + const appliedPaths: string[] = []; + const rolledBackPaths: string[] = []; + mockGetConnector.mockReturnValue({ + applyMigration: jest.fn(async (_conn: any, filePath: string) => { + appliedPaths.push(filePath); + return true; + }), + rollbackMigration: jest.fn(async (_conn: any, _ver: string, filePath: string) => { + rolledBackPaths.push(filePath); + return true; + }), + listAppliedMigrations: jest.fn(async () => []), + }); + mockIntrospectLiveCanonicalAST.mockResolvedValue({ + dialect: "postgresql", + schemas: [{ name: "public", tables: [], enums: [], views: [] }], + }); + + const dbService = { + getDatabaseConnection: jest.fn(async () => ({ conn: {}, dbType: "postgresql" })), + withConnection: jest.fn(), + } as any; + const { rpc, responses, errors } = createMockRpc(); + const handlers = new MigrationHandlers(rpc, silentLogger, dbService, {} as any); + + await handlers.handleListMigrations({ dbId: "shared-db-2", projectId: projectB.id }, 1); + expect(responses[0].payload.data.localMigrations.map((m: any) => m.version)).toEqual([ + "20261129110001", + ]); + + await handlers.handleGetMigrationSQL( + { dbId: "shared-db-2", projectId: projectB.id, version: "20261129110001" }, + 2, + ); + expect(responses[1].payload.data.up).toContain("SELECT 'B';"); + + await handlers.handleApplyMigration( + { dbId: "shared-db-2", projectId: projectB.id, version: "20261129110001" }, + 3, + ); + await handlers.handleApplyMigrations({ dbId: "shared-db-2", projectId: projectB.id }, 4); + await handlers.handleRollbackMigration( + { dbId: "shared-db-2", projectId: projectB.id, version: "20261129110001" }, + 5, + ); + await handlers.handleDeleteMigration( + { dbId: "shared-db-2", projectId: projectB.id, version: "20261129110001" }, + 6, + ); + + expect(errors).toEqual([]); + expect(appliedPaths).toHaveLength(2); + expect(appliedPaths[0]).toBe(path.join(dirB, "20261129110001_proj_b.sql")); + expect(appliedPaths[1]).toBe(path.join(dirB, "20261129110001_proj_b.sql")); + expect(rolledBackPaths).toHaveLength(1); + expect(rolledBackPaths[0]).toBe(path.join(dirB, "20261129110001_proj_b.sql")); + expect(fs.readdirSync(dirB).filter((f) => f.endsWith(".sql"))).toEqual([]); + expect(fs.readdirSync(dirB)).toContain("migration.lock.json"); + expect(fs.readdirSync(dirA)).toContain("20261129110000_proj_a.sql"); + }); + + test("rejects destructive migration when confirmDestructive is 'false' or non-boolean true", async () => { + mockGetDB.mockResolvedValue({ id: "db-destructive", type: "postgresql" }); + const project = await projectStoreInstance.createProject({ + databaseId: "db-destructive", + name: "DestructiveTest", + }); + + const { rpc, errors } = createMockRpc(); + const handlers = new MigrationHandlers(rpc, silentLogger, {} as any, {} as any); + + await handlers.handleScaffoldIndexMigration( + { + projectId: project.id, + name: "drop_idx", + version: "20261129120000", + save: true, + confirmDestructive: "false" as any, + dropIndexes: [ + { + schema: "public", + tableOrCollection: "users", + indexName: "idx_old", + columns: ["email"], + }, + ], + }, + 1, + ); + + expect(errors).toHaveLength(1); + expect(errors[0].err.code).toBe("DESTRUCTIVE_CONFIRMATION_REQUIRED"); + }); +}); diff --git a/bridge/__tests__/performanceCopilot.test.ts b/bridge/__tests__/performanceCopilot.test.ts new file mode 100644 index 00000000..cd48e422 --- /dev/null +++ b/bridge/__tests__/performanceCopilot.test.ts @@ -0,0 +1,430 @@ +import { + buildPerformanceCopilotPrompt, + parsePerformanceCopilotResponse, + redactExplainPlanLiterals, + redactQueryLiterals, +} from "../src/ai/prompts/performance-copilot"; +import { hashPerformanceAnalysis } from "../src/services/aiCacheService"; +import { generateIndexMigration } from "../src/services/migrationGenerator"; +import type { AIPerformanceAnalysisInput } from "../src/types/ai"; +import type { IndexHealthReport, NormalizedExplainPlan } from "../src/types/performance"; + +describe("redactQueryLiterals", () => { + it("redacts single-quoted SQL string literals including escaped quotes", () => { + const sql = + "SELECT * FROM users WHERE email = 'alice@example.com' AND note = 'it''s fine' AND alt = 'foo\\'bar'"; + expect(redactQueryLiterals(sql)).toBe( + "SELECT * FROM users WHERE email = '?' AND note = '?' AND alt = '?'", + ); + }); + + it("redacts standalone numeric literals while preserving identifiers with digits", () => { + const sql = + 'SELECT col1, user_2, "table3" FROM orders_2025 WHERE amount > 99.95 AND status_id = 42 LIMIT 10'; + expect(redactQueryLiterals(sql)).toBe( + 'SELECT col1, user_2, "table3" FROM orders_2025 WHERE amount > ? AND status_id = ? LIMIT ?', + ); + }); + + it("redacts double-quoted MQL JSON string values while keeping keys intact", () => { + const mql = 'db.users.find({"email": "a@b.com", "age": 30, "roles": ["admin", "user"]})'; + expect(redactQueryLiterals(mql)).toBe( + 'db.users.find({"email": "?", "age": ?, "roles": ["?", "?"]})', + ); + }); + + it("redacts PostgreSQL untagged and tagged dollar-quoted literals (including non-ASCII tags) while preserving parameters", () => { + const sql = + "SELECT $1, $col, café1 FROM users WHERE email = $$alice@example.com$$ AND bio = $tag$hello 123 'world'$tag$ AND secret = $é$bob@example.com$é$"; + expect(redactQueryLiterals(sql)).toBe( + "SELECT $1, $col, café1 FROM users WHERE email = '?' AND bio = '?' AND secret = '?'", + ); + }); + + it("redacts non-ASCII PostgreSQL dollar-quoted literals in explain plan filters and bottlenecks", () => { + const plan: NormalizedExplainPlan = { + dialect: "postgresql", + query: "SELECT * FROM users WHERE email = $é$alice@example.com$é$", + analyzed: true, + bottlenecks: [ + { + type: "FULL_SCAN", + target: "users", + details: "Filter email = $é$alice@example.com$é$ matched 1 row", + severity: "warning", + }, + ], + planTree: { + nodeType: "Seq Scan", + relation: "users", + filter: "(email = $é$alice@example.com$é$)", + children: [], + }, + rawPlan: {}, + }; + + const redacted = redactExplainPlanLiterals(plan); + expect(redacted.planTree.filter).toBe("(email = '?')"); + expect(redacted.bottlenecks[0].details).toBe("Filter email = '?' matched ? row"); + }); + + it("redacts planTree filters recursively and bottleneck details", () => { + const plan: NormalizedExplainPlan = { + dialect: "postgresql", + query: "SELECT * FROM users WHERE email = 'alice@example.com'", + analyzed: true, + bottlenecks: [ + { + type: "FULL_SCAN", + target: "users", + details: "Filter email = 'alice@example.com' matched 1 row", + severity: "warning", + }, + ], + planTree: { + nodeType: "Nested Loop", + filter: "(status = 'active')", + children: [ + { + nodeType: "Seq Scan", + relation: "users", + filter: "(email = 'alice@example.com' AND age > 21)", + children: [], + }, + ], + }, + rawPlan: {}, + }; + + const redacted = redactExplainPlanLiterals(plan); + expect(redacted.planTree.filter).toBe("(status = '?')"); + expect(redacted.planTree.children[0].filter).toBe("(email = '?' AND age > ?)"); + expect(redacted.bottlenecks[0].details).toBe("Filter email = '?' matched ? row"); + // Original plan must not be mutated + expect(plan.planTree.children[0].filter).toBe("(email = 'alice@example.com' AND age > 21)"); + }); +}); + +describe("hashPerformanceAnalysis", () => { + it("includes executionTimeMs and planningTimeMs in cache key", () => { + const baseInput: AIPerformanceAnalysisInput = { + dialect: "postgresql", + query: "SELECT * FROM orders WHERE customer_id = ?", + plan: { + dialect: "postgresql", + query: "SELECT * FROM orders WHERE customer_id = ?", + analyzed: true, + executionTimeMs: 10, + planningTimeMs: 1, + bottlenecks: [], + planTree: { nodeType: "Seq Scan", relation: "orders", children: [] }, + rawPlan: {}, + }, + }; + + const hashA = hashPerformanceAnalysis(baseInput, "ds1"); + const hashSame = hashPerformanceAnalysis({ ...baseInput }, "ds1"); + const hashDiffExec = hashPerformanceAnalysis( + { ...baseInput, plan: { ...baseInput.plan, executionTimeMs: 10000 } }, + "ds1", + ); + const hashDiffPlan = hashPerformanceAnalysis( + { ...baseInput, plan: { ...baseInput.plan, planningTimeMs: 25 } }, + "ds1", + ); + + expect(hashA).toBe(hashSame); + expect(hashA).not.toBe(hashDiffExec); + expect(hashA).not.toBe(hashDiffPlan); + }); +}); + +describe("buildPerformanceCopilotPrompt & parsePerformanceCopilotResponse", () => { + const samplePlan: NormalizedExplainPlan = { + dialect: "postgresql", + query: "SELECT * FROM orders WHERE customer_id = 42", + analyzed: true, + totalCost: 1250.5, + rowsExamined: 50000, + rowsReturned: 12, + executionTimeMs: 48.2, + bottlenecks: [ + { + type: "FULL_SCAN", + target: "orders", + details: "Sequential scan on orders examining 50,000 rows", + severity: "critical", + }, + ], + planTree: { + nodeType: "Seq Scan", + relation: "orders", + cost: 1250.5, + rows: 50000, + actualRows: 12, + filter: "(customer_id = 42)", + children: [], + }, + rawPlan: {}, + }; + + const sampleHealth: IndexHealthReport = { + dialect: "postgresql", + indexes: [], + unusedIndexes: [ + { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_legacy", + columns: ["legacy_code"], + isUnique: false, + isPrimary: false, + scans: 0, + sizeBytes: 1048576, + status: "unused", + }, + ], + duplicateIndexes: [ + { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_status_dup", + redundantWith: "idx_orders_status_created", + reason: "Leading column prefix covered", + }, + ], + summary: { + total: 4, + unusedCount: 1, + duplicateCount: 1, + totalSizeBytes: 4194304, + }, + }; + + it("builds a prompt with plan metrics, bottlenecks, tree, and index health", () => { + const input: AIPerformanceAnalysisInput = { + dialect: "postgresql", + query: "SELECT * FROM orders WHERE customer_id = ?", + plan: samplePlan, + indexHealth: sampleHealth, + }; + + const { system, user } = buildPerformanceCopilotPrompt(input); + expect(system).toContain("Performance & Index Copilot"); + expect(user).toContain("postgresql"); + expect(user).toContain("totalCost: 1250.5"); + expect(user).toContain("FULL_SCAN"); + expect(user).toContain("Seq Scan on orders"); + expect(user).toContain("idx_orders_legacy"); + expect(user).toContain("idx_orders_status_dup"); + }); + + it("parses bare JSON responses", () => { + const raw = JSON.stringify({ + summary: "Add an index on orders(customer_id).", + estimatedImpact: "high", + rewrittenQuery: "SELECT id, total FROM orders WHERE customer_id = ?", + recommendedIndexes: [ + { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_customer_id", + columns: ["customer_id"], + unique: false, + reason: "Eliminates sequential scan", + ddlPreview: "CREATE INDEX idx_orders_customer_id ON public.orders (customer_id);", + }, + ], + dropCandidates: [ + { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_legacy", + reason: "Zero scans", + }, + ], + warnings: ["Verify write throughput impact"], + }); + + const parsed = parsePerformanceCopilotResponse(raw); + expect(parsed.estimatedImpact).toBe("high"); + expect(parsed.rewrittenQuery).toBe("SELECT id, total FROM orders WHERE customer_id = ?"); + expect(parsed.recommendedIndexes).toHaveLength(1); + expect(parsed.recommendedIndexes[0].indexName).toBe("idx_orders_customer_id"); + expect(parsed.dropCandidates).toHaveLength(1); + expect(parsed.warnings).toEqual(["Verify write throughput impact"]); + }); + + it("parses ```json fenced responses", () => { + const raw = [ + "Here is the analysis:", + "```json", + JSON.stringify({ + summary: "Fenced JSON summary", + estimatedImpact: "LOW", + recommendedIndexes: [], + dropCandidates: [], + warnings: [], + }), + "```", + ].join("\n"); + + const parsed = parsePerformanceCopilotResponse(raw); + expect(parsed.summary).toBe("Fenced JSON summary"); + expect(parsed.estimatedImpact).toBe("low"); + }); + + it("falls back gracefully on non-JSON responses", () => { + const raw = "Consider adding a composite index on (customer_id, created_at)."; + const parsed = parsePerformanceCopilotResponse(raw); + expect(parsed).toEqual({ + summary: raw, + estimatedImpact: "medium", + recommendedIndexes: [], + dropCandidates: [], + warnings: [], + }); + }); +}); + +describe("generateIndexMigration", () => { + it("generates PostgreSQL index migration with CONCURRENTLY and marks drops destructive", () => { + const res = generateIndexMigration({ + dialect: "postgresql", + name: "orders_perf", + version: "20261128120000", + concurrentIndexes: true, + createIndexes: [ + { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_customer_id", + columns: ["customer_id", "created_at"], + unique: false, + }, + ], + dropIndexes: [ + { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_legacy", + columns: ["legacy_code"], + unique: false, + }, + ], + }); + + expect(res.format).toBe("sql"); + expect(res.filename).toBe("20261128120000_orders_perf.sql"); + expect(res.hasDestructive).toBe(true); + expect(res.warnings.length).toBeGreaterThan(0); + expect(res.upSql).toContain( + 'CREATE INDEX CONCURRENTLY "idx_orders_customer_id" ON "public"."orders" ("customer_id", "created_at");', + ); + expect(res.upSql).toContain('DROP INDEX CONCURRENTLY IF EXISTS "public"."idx_orders_legacy";'); + expect(res.downSql).toContain( + 'CREATE INDEX CONCURRENTLY "idx_orders_legacy" ON "public"."orders" ("legacy_code");', + ); + expect(res.downSql).toContain( + 'DROP INDEX CONCURRENTLY IF EXISTS "public"."idx_orders_customer_id";', + ); + }); + + it("generates MySQL index migration with backticks and ON table drop syntax", () => { + const res = generateIndexMigration({ + dialect: "mysql", + name: "mysql_idx", + version: "20261128120001", + createIndexes: [ + { + schema: "app", + tableOrCollection: "users", + indexName: "uq_users_email", + columns: ["email"], + unique: true, + }, + ], + dropIndexes: [ + { + schema: "app", + tableOrCollection: "users", + indexName: "idx_users_old", + }, + ], + }); + + expect(res.format).toBe("sql"); + expect(res.hasDestructive).toBe(true); + expect(res.upSql).toContain("CREATE UNIQUE INDEX `uq_users_email` ON `app`.`users` (`email`);"); + expect(res.upSql).toContain("DROP INDEX `idx_users_old` ON `app`.`users`;"); + expect(res.downSql).toContain("DROP INDEX `uq_users_email` ON `app`.`users`;"); + }); + + it("generates SQLite index migration without schema qualification", () => { + const res = generateIndexMigration({ + dialect: "sqlite", + name: "sqlite_idx", + version: "20261128120002", + createIndexes: [ + { + schema: "main", + tableOrCollection: "items", + indexName: "idx_items_sku", + columns: ["sku"], + }, + ], + }); + + expect(res.format).toBe("sql"); + expect(res.hasDestructive).toBe(false); + expect(res.upSql).toContain('CREATE INDEX "idx_items_sku" ON "items" ("sku");'); + expect(res.downSql).toContain('DROP INDEX IF EXISTS "idx_items_sku";'); + }); + + it("generates MongoDB .mql.json manifest for createIndex and dropIndex", () => { + const res = generateIndexMigration({ + dialect: "mongodb", + name: "mongo_idx", + version: "20261128120003", + createIndexes: [ + { + tableOrCollection: "orders", + indexName: "idx_orders_customer", + columns: ["customerId", "createdAt"], + unique: false, + }, + ], + dropIndexes: [ + { + tableOrCollection: "orders", + indexName: "idx_orders_unused", + }, + ], + }); + + expect(res.format).toBe("mql"); + expect(res.filename).toBe("20261128120003_mongo_idx.mql.json"); + expect(res.hasDestructive).toBe(true); + expect(res.manifest?.allowIrreversible).toBe(true); + expect(res.manifest?.up).toEqual([ + { + type: "createIndex", + collection: "orders", + key: { customerId: 1, createdAt: 1 }, + options: { name: "idx_orders_customer", unique: false }, + }, + { + type: "dropIndex", + collection: "orders", + indexName: "idx_orders_unused", + }, + ]); + expect(res.manifest?.down).toEqual([ + { + type: "dropIndex", + collection: "orders", + indexName: "idx_orders_customer", + }, + ]); + }); +}); diff --git a/bridge/__tests__/projectStore.test.ts b/bridge/__tests__/projectStore.test.ts index 1f48806a..dfb347ab 100644 --- a/bridge/__tests__/projectStore.test.ts +++ b/bridge/__tests__/projectStore.test.ts @@ -14,9 +14,11 @@ jest.mock("../src/utils/config", () => { const original = jest.requireActual("../src/utils/config") as any; const _path = require("path"); const _os = require("os"); - const testProjects = _path.join(_os.tmpdir(), "projectstore-test-" + Date.now(), "projects"); + const baseDir = _path.join(_os.tmpdir(), "projectstore-test-" + Date.now()); + const testProjects = _path.join(baseDir, "projects"); return { ...original, + CONFIG_FOLDER: baseDir, PROJECTS_FOLDER: testProjects, PROJECTS_INDEX_FILE: _path.join(testProjects, "index.json"), getProjectDir: (id: string) => _path.join(testProjects, id), @@ -40,7 +42,13 @@ jest.mock("../src/services/dbStore", () => ({ })); // After mocking, get the actual folder being used -import { PROJECTS_FOLDER, PROJECTS_INDEX_FILE, getProjectDir } from "../src/utils/config"; +import { + CONFIG_FOLDER, + PROJECTS_FOLDER, + PROJECTS_INDEX_FILE, + getProjectDir, +} from "../src/utils/config"; +import { dbStoreInstance } from "../src/services/dbStore"; describe("ProjectStore", () => { let store: ProjectStore; @@ -678,4 +686,198 @@ describe("ProjectStore", () => { expect(content).toBe("# Custom README\n"); }); }); + + // ========================================== + // V3 Hardening Fixes + // ========================================== + + describe("V3 Hardening Fixes", () => { + const getDBMock = dbStoreInstance.getDB as jest.MockedFunction; + + afterEach(async () => { + jest.restoreAllMocks(); + getDBMock.mockResolvedValue({ + id: "test-db-id", + name: "TestDB", + type: "POSTGRES", + host: "localhost", + port: 5432, + } as any); + if (fsSync.existsSync(CONFIG_FOLDER)) { + await fs.rm(CONFIG_FOLDER, { recursive: true, force: true }); + } + }); + + test("V3 Inline 13: linkDatabase preserves non-empty schema dialect on cross-dialect relink and updates empty schema dialect", async () => { + getDBMock.mockResolvedValueOnce({ id: "db-pg", name: "PG", type: "postgresql" } as any); + const project = await store.createProject({ databaseId: "db-pg", name: "CrossDialect" }); + + // Empty schema -> relinking to sqlite updates dialect to sqlite + getDBMock.mockResolvedValueOnce({ id: "db-sq", name: "SQ", type: "sqlite" } as any); + await store.linkDatabase(project.id, "db-sq"); + let schemaFile = await store.getSchema(project.id); + expect(schemaFile?.dialect).toBe("sqlite"); + + // Non-empty schema saved as postgresql -> relinking to sqlite must NOT relabel dialect + await store.saveSchema( + project.id, + [ + { + name: "public", + tables: [ + { + name: "users", + type: "BASE TABLE", + columns: [], + indexes: [], + foreignKeys: [], + checks: [], + }, + ], + }, + ], + "pg-hash", + "postgresql", + ); + getDBMock.mockResolvedValueOnce({ id: "db-sq-2", name: "SQ2", type: "sqlite" } as any); + await store.linkDatabase(project.id, "db-sq-2"); + schemaFile = await store.getSchema(project.id); + expect(schemaFile?.databaseId).toBe("db-sq-2"); + expect(schemaFile?.dialect).toBe("postgresql"); + }); + + test("V3 Minor (L936): saveSchema falls through unknown meta.engine to linked database engine", async () => { + getDBMock.mockResolvedValue({ id: "db-duck", name: "Duck", type: "duckdb" } as any); + const project = await store.createProject({ databaseId: "db-duck", name: "UnknownEngine" }); + + // Force project relwave.json engine to "unknown" + const metaPath = path.join(getProjectDir(project.id), "relwave.json"); + const meta = JSON.parse(fsSync.readFileSync(metaPath, "utf8")); + meta.engine = "unknown"; + fsSync.writeFileSync(metaPath, JSON.stringify(meta, null, 2), "utf8"); + + const saved = await store.saveSchema( + project.id, + [{ name: "main", tables: [], enums: [], views: [] }], + "h-duck", + ); + expect(saved.dialect).toBe("duckdb"); + }); + + test("V3 Inline 4: repairSchemaDialect updates dialect only when schemaHash and cachedAt match", async () => { + getDBMock.mockResolvedValue({ id: "db-duck-rep", name: "Duck", type: "duckdb" } as any); + const project = await store.createProject({ databaseId: "db-duck-rep", name: "RepairTest" }); + const saved = await store.saveSchema(project.id, [], "h1", "sqlite"); + expect(saved.dialect).toBe("sqlite"); + + // Mismatched hash or cachedAt skips cleanly + await expect( + store.repairSchemaDialect(project.id, "wrong-hash", saved.cachedAt, "duckdb"), + ).resolves.toBe(false); + await expect( + store.repairSchemaDialect(project.id, "h1", "2000-01-01T00:00:00.000Z", "duckdb"), + ).resolves.toBe(false); + expect((await store.getSchema(project.id))?.dialect).toBe("sqlite"); + + // Matching hash and cachedAt repairs only dialect + await expect( + store.repairSchemaDialect(project.id, "h1", saved.cachedAt, "duckdb"), + ).resolves.toBe(true); + const repaired = await store.getSchema(project.id); + expect(repaired?.dialect).toBe("duckdb"); + expect(repaired?.cachedAt).toBe(saved.cachedAt); + }); + + test("V3 Inline 14 & 15: resolveProjectMigrationsDir handles EXDEV cross-FS copy, preserves fallback on failure, and serializes sole-link check against importProject", async () => { + // 1. EXDEV copy path succeeds and removes fallbackDir + const p1 = await store.createProject({ databaseId: "db-exdev", name: "ExdevProj" }); + const fallbackExdev = path.join(CONFIG_FOLDER, "migrations", "db-exdev"); + await fs.mkdir(fallbackExdev, { recursive: true }); + await fs.writeFile(path.join(fallbackExdev, "001_init.sql"), "-- +up\nSELECT 1;\n", "utf8"); + + const origRename = fs.rename.bind(fs); + const renameSpy = jest.spyOn(fs, "rename").mockImplementation(async (oldP, newP) => { + if (String(oldP) === fallbackExdev) { + const err: any = new Error("EXDEV: cross-device link not permitted"); + err.code = "EXDEV"; + throw err; + } + return origRename(oldP, newP); + }); + + const resolvedExdev = await store.resolveProjectMigrationsDir(p1.id); + renameSpy.mockRestore(); + expect(fsSync.existsSync(path.join(resolvedExdev, "001_init.sql"))).toBe(true); + expect(fsSync.existsSync(fallbackExdev)).toBe(false); + + // 2. Move failure leaves fallbackDir intact and does NOT create an empty targetDir + const p2 = await store.createProject({ databaseId: "db-fail", name: "FailProj" }); + const fallbackFail = path.join(CONFIG_FOLDER, "migrations", "db-fail"); + await fs.mkdir(fallbackFail, { recursive: true }); + await fs.writeFile(path.join(fallbackFail, "001_keep.sql"), "-- +up\nSELECT 1;\n", "utf8"); + + const failSpy = jest.spyOn(fs, "rename").mockImplementation(async (oldP, newP) => { + if (String(oldP) === fallbackFail) { + const err: any = new Error("EACCES: permission denied"); + err.code = "EACCES"; + throw err; + } + return origRename(oldP, newP); + }); + await expect(store.resolveProjectMigrationsDir(p2.id)).rejects.toThrow(/EACCES/); + failSpy.mockRestore(); + expect(fsSync.existsSync(path.join(fallbackFail, "001_keep.sql"))).toBe(true); + expect(fsSync.existsSync(path.join(getProjectDir(p2.id), "migrations"))).toBe(false); + + // 3. Concurrent importProject holding lock prevents resolveProjectMigrationsDir from moving shared legacy dir + const pShared1 = await store.createProject({ databaseId: "db-shared-race", name: "Shared1" }); + const fallbackShared = path.join(CONFIG_FOLDER, "migrations", "db-shared-race"); + await fs.mkdir(fallbackShared, { recursive: true }); + await fs.writeFile( + path.join(fallbackShared, "001_shared.sql"), + "-- +up\nSELECT 1;\n", + "utf8", + ); + + const repo2 = path.join(CONFIG_FOLDER, "imported-repo-2"); + await fs.mkdir(repo2, { recursive: true }); + await fs.writeFile( + path.join(repo2, "relwave.json"), + JSON.stringify({ + version: 1, + id: "imported-shared-2", + databaseId: null, + name: "Shared2", + engine: "postgresql", + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }), + "utf8", + ); + + let releaseImportDbLookup!: () => void; + const importDbLookupStarted = new Promise((res) => { + getDBMock.mockImplementationOnce( + () => + new Promise((resolve) => { + res(); + releaseImportDbLookup = () => + resolve({ id: "db-shared-race", name: "SharedDB", type: "postgresql" } as any); + }), + ); + }); + + const importPromise = store.importProject({ + sourcePath: repo2, + databaseId: "db-shared-race", + }); + await importDbLookupStarted; + const resolvePromise = store.resolveProjectMigrationsDir(pShared1.id); + releaseImportDbLookup(); + + const [, resolvedSharedDir] = await Promise.all([importPromise, resolvePromise]); + expect(fsSync.existsSync(path.join(fallbackShared, "001_shared.sql"))).toBe(true); + expect(fsSync.existsSync(path.join(resolvedSharedDir, "001_shared.sql"))).toBe(false); + }); + }); }); diff --git a/bridge/__tests__/schemaDiffEngine.test.ts b/bridge/__tests__/schemaDiffEngine.test.ts new file mode 100644 index 00000000..646949b6 --- /dev/null +++ b/bridge/__tests__/schemaDiffEngine.test.ts @@ -0,0 +1,1010 @@ +import { describe, expect, test } from "@jest/globals"; +import { diffSchemas, isTypeNarrowing } from "../src/services/schemaDiffEngine"; +import { + normalizeLiveSqlSchemas, + normalizeSchemaFile, +} from "../src/services/schemaSnapshotNormalizer"; +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", + ]); + }); + + test("checks integer digit count, omitted scale, and negative scale for numeric/decimal narrowing", () => { + expect(isTypeNarrowing("numeric(10, 2)", "numeric(10, 4)")).toBe(true); + expect(isTypeNarrowing("decimal(10, 2)", "decimal(8, 4)")).toBe(true); + expect(isTypeNarrowing("numeric(10, 4)", "numeric(10, 2)")).toBe(true); + expect(isTypeNarrowing("numeric(10)", "numeric(10, 2)")).toBe(true); + expect(isTypeNarrowing("numeric(10)", "numeric(8)")).toBe(true); + expect(isTypeNarrowing("numeric(10, -2)", "numeric(10, 0)")).toBe(true); + expect(isTypeNarrowing("numeric(10, 0)", "numeric(10, -2)")).toBe(true); + + expect(isTypeNarrowing("numeric(10, 2)", "numeric(12, 2)")).toBe(false); + expect(isTypeNarrowing("numeric(10, 2)", "numeric(12, 4)")).toBe(false); + expect(isTypeNarrowing("numeric(10)", "numeric(10, 0)")).toBe(false); + expect(isTypeNarrowing("numeric(10)", "numeric(12, 2)")).toBe(false); + expect(isTypeNarrowing("numeric(10, -2)", "numeric(12, 0)")).toBe(false); + }); + + test("classifies numeric(10) -> numeric(10, 2) as destructive and numeric(10, 2) -> numeric(12, 4) as warning", () => { + const source = makePgAst([ + { + name: "ledger", + type: "BASE TABLE", + columns: [ + { + name: "amount", + type: "numeric(10)", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + { + name: "rate", + type: "numeric(10, 2)", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 2, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ]); + + const target = makePgAst([ + { + name: "ledger", + type: "BASE TABLE", + columns: [ + { + name: "amount", + type: "numeric(10, 2)", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + { + name: "rate", + type: "numeric(12, 4)", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 2, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ]); + + const res = diffSchemas(source, target); + const byCol = new Map(res.items.map((i) => [i.objectName, i])); + expect(byCol.get("amount")?.severity).toBe("destructive"); + expect(byCol.get("rate")?.severity).toBe("warning"); + }); + + test("classifies nullable -> NOT NULL as destructive even when a default is set", () => { + const source = makePgAst([ + { + name: "users", + type: "BASE TABLE", + columns: [ + { + name: "score", + type: "integer", + nullable: true, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ]); + const target = makePgAst([ + { + name: "users", + type: "BASE TABLE", + columns: [ + { + name: "score", + type: "integer", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: "0", + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ]); + + const res = diffSchemas(source, target); + expect(res.items).toHaveLength(1); + expect(res.items[0].severity).toBe("destructive"); + expect(res.items[0].details).toContain("backfill"); + }); + + test("generates collision-free diff IDs when names contain colons", () => { + const source = makePgAst([ + { + name: "a", + type: "BASE TABLE", + columns: [ + { + name: "b:c", + type: "text", + nullable: true, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + { + name: "a:b", + type: "BASE TABLE", + columns: [ + { + name: "c", + type: "text", + nullable: true, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ]); + const target = makePgAst([ + { name: "a", type: "BASE TABLE", columns: [], indexes: [], foreignKeys: [], checks: [] }, + { name: "a:b", type: "BASE TABLE", columns: [], indexes: [], foreignKeys: [], checks: [] }, + ]); + + const res = diffSchemas(source, target, { detectRenames: false }); + expect(res.items).toHaveLength(2); + expect(res.items[0].id).not.toBe(res.items[1].id); + }); + + test("detects MongoDB compound index key reordering and collection/view type changes", () => { + const source: CanonicalSchemaAST = { + dialect: "mongodb", + schemas: [], + collections: [ + { + name: "events", + type: "collection", + indexes: [{ name: "idx_ab", key: { a: 1, b: 1 }, unique: false, sparse: false }], + validator: null, + }, + { + name: "reports", + type: "view", + indexes: [], + validator: null, + }, + ], + }; + const target: CanonicalSchemaAST = { + dialect: "mongodb", + schemas: [], + collections: [ + { + name: "events", + type: "collection", + indexes: [{ name: "idx_ab", key: { b: 1, a: 1 }, unique: false, sparse: false }], + validator: null, + }, + { + name: "reports", + type: "collection", + indexes: [], + validator: null, + }, + ], + }; + + const res = diffSchemas(source, target); + expect(res.hasChanges).toBe(true); + const idxChange = res.items.find((i) => i.tableOrCollection === "events"); + expect(idxChange?.type).toBe("MONGO_INDEX_MODIFIED"); + const typeChange = res.items.find((i) => i.tableOrCollection === "reports"); + expect(typeChange).toBeDefined(); + expect(typeChange?.severity).toBe("destructive"); + expect(typeChange?.details).toContain("view -> collection"); + }); + + test("equates quoted and unquoted simple identifiers in diff without mutating AST SQL", () => { + const source: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + { + name: "users", + type: "BASE TABLE", + columns: [ + { + name: "age", + type: "integer", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: '"abs"(-1)', + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + ], + indexes: [], + foreignKeys: [], + checks: [{ name: "chk_age", expression: '("age" > 0)' }], + }, + ], + enums: [], + views: [{ name: "v_users", definition: 'SELECT "age" FROM "users"' }], + }, + ], + }; + + const target: CanonicalSchemaAST = { + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + { + name: "users", + type: "BASE TABLE", + columns: [ + { + name: "age", + type: "integer", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: "abs(-1)", + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + ], + indexes: [], + foreignKeys: [], + checks: [{ name: "chk_age", expression: "(age > 0)" }], + }, + ], + enums: [], + views: [{ name: "v_users", definition: "SELECT age FROM users" }], + }, + ], + }; + + const res = diffSchemas(source, target); + expect(res.hasChanges).toBe(false); + expect(source.schemas[0].views[0].definition).toBe('SELECT "age" FROM "users"'); + expect(source.schemas[0].tables[0].checks[0].expression).toBe('("age" > 0)'); + expect(source.schemas[0].tables[0].columns[0].defaultValue).toBe('"abs"(-1)'); + }); + + test("treats unconstrained PostgreSQL numeric/decimal -> sized numeric as destructive narrowing", () => { + expect(isTypeNarrowing("numeric", "numeric(10, 2)")).toBe(true); + expect(isTypeNarrowing("decimal", "numeric(10, 2)")).toBe(true); + expect(isTypeNarrowing("numeric", "numeric(10)")).toBe(true); + expect(isTypeNarrowing("numeric(10, 2)", "numeric")).toBe(false); + expect(isTypeNarrowing("numeric", "decimal")).toBe(false); + + const source = makePgAst([ + { + name: "ledger", + type: "BASE TABLE", + columns: [ + { + name: "amount", + type: "numeric", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + { + name: "rate", + type: "numeric(10, 2)", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 2, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ]); + const target = makePgAst([ + { + name: "ledger", + type: "BASE TABLE", + columns: [ + { + name: "amount", + type: "numeric(10, 2)", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + { + name: "rate", + type: "numeric(12, 4)", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 2, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ]); + + const res = diffSchemas(source, target); + const byCol = new Map(res.items.map((i) => [i.objectName, i])); + expect(byCol.get("amount")?.severity).toBe("destructive"); + expect(byCol.get("rate")?.severity).toBe("warning"); + }); + + test("reports TABLE_MODIFIED when ordered primaryKeyColumns change on a retained table", () => { + const cols = [ + { + name: "tenant_id", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + { + name: "user_id", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 2, + }, + ]; + const source = makePgAst([ + { + name: "memberships", + type: "BASE TABLE", + columns: cols, + primaryKeyColumns: ["tenant_id", "user_id"], + indexes: [], + foreignKeys: [], + checks: [], + }, + ]); + const target = makePgAst([ + { + name: "memberships", + type: "BASE TABLE", + columns: cols, + primaryKeyColumns: ["user_id", "tenant_id"], + indexes: [], + foreignKeys: [], + checks: [], + }, + ]); + + const res = diffSchemas(source, target); + expect(res.hasChanges).toBe(true); + expect(res.items).toHaveLength(1); + expect(res.items[0]).toMatchObject({ + type: "TABLE_MODIFIED", + severity: "destructive", + tableOrCollection: "memberships", + objectName: "primaryKey", + before: ["tenant_id", "user_id"], + after: ["user_id", "tenant_id"], + }); + }); + + test("reports VIEW_MODIFIED when explicit view columns change even if body is identical", () => { + const source: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [], + enums: [], + views: [{ name: "v", definition: "SELECT 1", columns: ["x"] }], + }, + ], + }; + const target: CanonicalSchemaAST = { + dialect: "sqlite", + schemas: [ + { + name: "main", + tables: [], + enums: [], + views: [{ name: "v", definition: "SELECT 1", columns: ["y"] }], + }, + ], + }; + + const res = diffSchemas(source, target); + expect(res.hasChanges).toBe(true); + expect(res.items).toHaveLength(1); + expect(res.items[0]).toMatchObject({ + type: "VIEW_MODIFIED", + objectName: "v", + before: { name: "v", definition: "SELECT 1", columns: ["x"] }, + after: { name: "v", definition: "SELECT 1", columns: ["y"] }, + }); + }); + + test("compares PK sets when either side lacks ordered primaryKeyColumns and detects genuine changes", () => { + const legacySnapshotCols = [ + { + name: "a", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + { + name: "b", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 2, + }, + ]; + const legacySource = makePgAst([ + { + name: "pairs", + type: "BASE TABLE", + columns: legacySnapshotCols, + indexes: [], + foreignKeys: [], + checks: [], + }, + ]); + const liveTarget = makePgAst([ + { + name: "pairs", + type: "BASE TABLE", + columns: legacySnapshotCols, + primaryKeyColumns: ["b", "a"], + indexes: [], + foreignKeys: [], + checks: [], + }, + ]); + + const noDiffForward = diffSchemas(legacySource, liveTarget); + expect(noDiffForward.hasChanges).toBe(false); + expect(noDiffForward.items).toEqual([]); + + const noDiffReverse = diffSchemas(liveTarget, legacySource); + expect(noDiffReverse.hasChanges).toBe(false); + expect(noDiffReverse.items).toEqual([]); + + // Genuine PK removal still detected when legacy snapshot lacks primaryKeyColumns + const removedPkTarget = makePgAst([ + { + name: "pairs", + type: "BASE TABLE", + columns: [legacySnapshotCols[0], { ...legacySnapshotCols[1], isPrimaryKey: false }], + primaryKeyColumns: ["a"], + indexes: [], + foreignKeys: [], + checks: [], + }, + ]); + const removedRes = diffSchemas(legacySource, removedPkTarget); + expect(removedRes.hasChanges).toBe(true); + const removedPkItem = removedRes.items.find( + (i) => i.type === "TABLE_MODIFIED" && i.objectName === "primaryKey", + ); + expect(removedPkItem).toMatchObject({ + type: "TABLE_MODIFIED", + severity: "destructive", + objectName: "primaryKey", + before: ["a", "b"], + after: ["a"], + }); + + // Genuine PK column swap (different column set) still detected + const addedColTarget = makePgAst([ + { + name: "pairs", + type: "BASE TABLE", + columns: [ + ...legacySnapshotCols, + { + name: "c", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 3, + }, + ], + primaryKeyColumns: ["b", "a", "c"], + indexes: [], + foreignKeys: [], + checks: [], + }, + ]); + const addedRes = diffSchemas(legacySource, addedColTarget); + const addedPkItem = addedRes.items.find( + (i) => i.type === "TABLE_MODIFIED" && i.objectName === "primaryKey", + ); + expect(addedPkItem).toMatchObject({ + type: "TABLE_MODIFIED", + severity: "destructive", + objectName: "primaryKey", + before: ["a", "b"], + after: ["b", "a", "c"], + }); + + // End-to-end: normalizeSchemaFile (column-flag-only snapshot) vs normalizeLiveSqlSchemas (explicit PK order) + const normalizedLegacy = normalizeSchemaFile({ + dialect: "postgresql", + schemas: [ + { + name: "public", + tables: [ + { + name: "pairs", + type: "BASE TABLE", + columns: [ + { + name: "a", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + { + name: "b", + type: "integer", + nullable: false, + isPrimaryKey: true, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 2, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ], + enums: [], + views: [], + }, + ], + }); + const normalizedLive = normalizeLiveSqlSchemas( + { + schemas: [ + { + name: "public", + tables: [ + { + name: "pairs", + type: "BASE TABLE", + columns: [ + { + name: "a", + type: "int4", + not_nullable: true, + is_primary_key: true, + ordinal_position: 1, + }, + { + name: "b", + type: "int4", + not_nullable: true, + is_primary_key: true, + ordinal_position: 2, + }, + ], + primaryKeys: [{ column_name: "b" }, { column_name: "a" }], + }, + ], + }, + ], + }, + "postgresql", + ); + expect(normalizedLegacy.schemas[0].tables[0].primaryKeyColumns).toBeUndefined(); + expect(normalizedLive.schemas[0].tables[0].primaryKeyColumns).toEqual(["b", "a"]); + expect(diffSchemas(normalizedLegacy, normalizedLive).hasChanges).toBe(false); + }); + + test("rejects mixed-engine schema pairs", () => { + const pg = makePgAst([]); + const mysql: CanonicalSchemaAST = { dialect: "mysql", schemas: [] }; + expect(() => diffSchemas(pg, mysql)).toThrow(/mismatched dialects/i); + }); +}); diff --git a/bridge/__tests__/schemaSnapshotNormalizer.test.ts b/bridge/__tests__/schemaSnapshotNormalizer.test.ts new file mode 100644 index 00000000..f6956327 --- /dev/null +++ b/bridge/__tests__/schemaSnapshotNormalizer.test.ts @@ -0,0 +1,821 @@ +import { describe, expect, jest, test } from "@jest/globals"; +import { + canonicalizeType, + INTERNAL_MIGRATION_TABLES, + normalizeExpression, + normalizeExpressionForComparison, + normalizeLiveSqlSchemas, + normalizeMongoIntrospection, + normalizeSchemaFile, +} from "../src/services/schemaSnapshotNormalizer"; +import { + extractViewBody, + extractViewMetadata, + introspectLiveCanonicalAST, +} from "../src/services/liveSchemaIntrospector"; +import * as connectorRegistry from "../src/services/connectorRegistry"; +import * as mongoModule from "../src/connectors/mongo"; +import { DBType } from "../src/types"; +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 while preserving identifier quoting in expressions", () => { + expect(normalizeExpression(' ( "age" > 0 ) ')).toBe('("age" > 0)'); + expect(normalizeExpression("`status` IN ('active', 'pending')")).toBe( + "`status` IN ('active', 'pending')", + ); + expect(normalizeExpression('SELECT "select" FROM "t"')).toBe('SELECT "select" FROM "t"'); + expect(normalizeExpression(" ")).toBeNull(); + expect(normalizeExpression(null)).toBeNull(); + }); + + test("preserves PostgreSQL dollar-quoted strings and avoids false matches inside identifiers", () => { + expect(normalizeExpression("SELECT $$A B$$")).toBe("SELECT $$A B$$"); + expect(normalizeExpression("SELECT $tag$hello world$tag$")).toBe( + "SELECT $tag$hello world$tag$", + ); + expect(normalizeExpression("SELECT $é$alice bob$é$")).toBe("SELECT $é$alice bob$é$"); + expect(normalizeExpression("SELECT foo$tag$ + 1")).toBe("SELECT foo$tag$ + 1"); + expect(normalizeExpression("SELECT foo$$a b$$")).toBe("SELECT foo$$a b$$"); + expect(normalizeExpression("SELECT $1 + $2")).toBe("SELECT $1 + $2"); + }); + + test("computes dialect-aware comparison form without mutating quoted SQL", () => { + expect(normalizeExpressionForComparison('("age" > 0)', "postgresql")).toBe("(age > 0)"); + expect(normalizeExpressionForComparison('SELECT "select" FROM "t"', "postgresql")).toBe( + 'SELECT "select" FROM t', + ); + expect(normalizeExpressionForComparison('("Age" > 0)', "postgresql")).toBe('("Age" > 0)'); + expect(normalizeExpressionForComparison("`status` IN ('active', 'pending')", "mysql")).toBe( + "status IN ('active', 'pending')", + ); + expect(normalizeExpressionForComparison('"status" = 1', "mysql")).toBe('"status" = 1'); + }); + + 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"]); + }); + + test("preserves quoted values in SQL types and skips prototype keys", () => { + expect(canonicalizeType("ENUM('Open','Closed')", "mysql")).toBe("enum('Open', 'Closed')"); + expect(canonicalizeType("enum( 'Active' , 'In Progress' )", "mysql")).toBe( + "enum('Active', 'In Progress')", + ); + expect(canonicalizeType("constructor", "postgresql")).toBe("constructor"); + expect(canonicalizeType("toString", "postgresql")).toBe("tostring"); + }); + + test("preserves SQL string literal contents and significant identifier quotes in expressions", () => { + expect(normalizeExpression("'A B'")).toBe("'A B'"); + expect(normalizeExpression(`"Status" = 'Active User'`)).toBe(`"Status" = 'Active User'`); + expect(normalizeExpression(`'hello "age" world'`)).toBe(`'hello "age" world'`); + }); + + test("respects dialect override and engine metadata for saved DuckDB snapshots labeled sqlite", () => { + const saved = { + version: 2, + projectId: "proj-1", + databaseId: "db-1", + dialect: "sqlite", + cachedAt: "2026-01-01T00:00:00Z", + relwaveVersion: "1.3.5", + schemaHash: "abc", + schemas: [ + { + name: "main", + tables: [ + { + name: "metrics", + type: "BASE TABLE", + columns: [ + { + name: "amount", + type: "DECIMAL(10,2)", + nullable: false, + isPrimaryKey: false, + isForeignKey: false, + defaultValue: null, + isUnique: false, + isSerial: false, + ordinalPosition: 1, + }, + ], + indexes: [], + foreignKeys: [], + checks: [], + }, + ], + enums: [], + views: [], + }, + ], + } as SchemaFile; + + const overridden = normalizeSchemaFile(saved, "duckdb"); + expect(overridden.dialect).toBe("duckdb"); + expect(overridden.schemas[0].tables[0].columns[0].type).toBe("numeric(10, 2)"); + + const withEngine = normalizeSchemaFile({ ...saved, engine: "duckdb" }); + expect(withEngine.dialect).toBe("duckdb"); + expect(withEngine.schemas[0].tables[0].columns[0].type).toBe("numeric(10, 2)"); + }); + + test("preserves explicit composite primary key order and leaves column-flag-only PK order undefined", () => { + const live = { + schemas: [ + { + name: "public", + tables: [ + { + name: "memberships", + type: "BASE TABLE", + columns: [ + { + name: "tenant_id", + type: "int4", + not_nullable: true, + is_primary_key: true, + ordinalPosition: 2, + }, + { + name: "user_id", + type: "int4", + not_nullable: true, + is_primary_key: true, + ordinalPosition: 1, + }, + ], + primaryKeys: [{ column_name: "user_id" }, { column_name: "tenant_id" }], + }, + { + name: "audit_keys", + type: "BASE TABLE", + columns: [ + { + name: "z_col", + type: "text", + not_nullable: true, + isPrimaryKey: true, + ordinalPosition: 1, + }, + { + name: "a_col", + type: "text", + not_nullable: true, + isPrimaryKey: true, + ordinalPosition: 2, + }, + ], + }, + ], + }, + ], + }; + + const ast = normalizeLiveSqlSchemas(live, "postgresql"); + const audit = ast.schemas[0].tables.find((t) => t.name === "audit_keys")!; + const memberships = ast.schemas[0].tables.find((t) => t.name === "memberships")!; + + expect(memberships.columns.map((c) => c.name)).toEqual(["tenant_id", "user_id"]); + expect(memberships.primaryKeyColumns).toEqual(["user_id", "tenant_id"]); + expect(audit.columns.map((c) => c.name)).toEqual(["a_col", "z_col"]); + expect(audit.columns.filter((c) => c.isPrimaryKey).map((c) => c.name)).toEqual([ + "a_col", + "z_col", + ]); + expect(audit.primaryKeyColumns).toBeUndefined(); + }); + + test("extractViewBody normalizes SQLite and DuckDB DDL while preserving PostgreSQL/MySQL bodies", () => { + expect(extractViewBody('CREATE VIEW "v_as" ("as_col") AS SELECT 1 AS x', DBType.SQLITE)).toBe( + "SELECT 1 AS x", + ); + expect( + extractViewBody( + "CREATE OR REPLACE VIEW main.v_cte AS WITH cte AS (SELECT 1) SELECT * FROM cte;", + DBType.DUCKDB, + ), + ).toBe("WITH cte AS (SELECT 1) SELECT * FROM cte"); + expect(extractViewBody(" SELECT users.id FROM users;", DBType.POSTGRES)).toBe( + " SELECT users.id FROM users;", + ); + expect(extractViewBody("select `id` from `users`", DBType.MYSQL)).toBe( + "select `id` from `users`", + ); + }); + + test("attaches original driver error as cause when MongoDB index introspection fails", async () => { + const driverErr = Object.assign(new Error("topology closed"), { + name: "MongoTopologyClosedError", + }); + const selectDbSpy = jest.spyOn(mongoModule, "selectDb").mockReturnValue({ + listCollections: () => ({ + toArray: async () => [{ name: "users", type: "collection", options: {} }], + }), + } as any); + const listIndexesSpy = jest + .spyOn(mongoModule.mongoConnector, "listIndexes") + .mockRejectedValue(driverErr); + + const mockDbService = { + withConnection: async ( + _id: string, + fn: (conn: any, db: any, dbType: DBType) => Promise, + ) => fn({}, {}, DBType.MONGODB), + } as any; + + try { + let caught: any; + try { + await introspectLiveCanonicalAST(mockDbService, {} as any, "db-mongo"); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(Error); + expect(caught.message).toContain( + "Failed to introspect indexes for MongoDB collection 'users'", + ); + expect(caught.cause).toBe(driverErr); + } finally { + selectDbSpy.mockRestore(); + listIndexesSpy.mockRestore(); + } + }); + + test("waits for all schema reads to settle before rejecting inside withConnection", async () => { + let secondFinished = false; + let leaseReleased = false; + let secondSettledBeforeLeaseReleased = false; + + const fakeConnector = { + listSchemas: async () => [{ name: "s_fail" }, { name: "s_slow" }], + listTables: async (_conn: unknown, schema: string) => { + if (schema === "s_fail") { + throw new Error("boom in s_fail"); + } + return []; + }, + getSchemaMetadataBatch: async (_conn: unknown, schema: string) => { + if (schema === "s_slow") { + await new Promise((resolve) => setTimeout(resolve, 25)); + secondFinished = true; + } + return { tables: new Map() }; + }, + }; + + const getConnSpy = jest + .spyOn(connectorRegistry, "getConnector") + .mockReturnValue(fakeConnector as any); + + const mockDbService = { + withConnection: async ( + _id: string, + fn: (conn: any, db: any, dbType: DBType) => Promise, + ) => { + try { + return await fn({}, {}, DBType.POSTGRES); + } finally { + secondSettledBeforeLeaseReleased = secondFinished; + leaseReleased = true; + } + }, + } as any; + + try { + await expect(introspectLiveCanonicalAST(mockDbService, {} as any, "db-pg")).rejects.toThrow( + "boom in s_fail", + ); + expect(leaseReleased).toBe(true); + expect(secondSettledBeforeLeaseReleased).toBe(true); + } finally { + getConnSpy.mockRestore(); + } + }); + + test("rejects ClickHouse live batch when listed base table has empty columns", async () => { + const fakeConnector = { + listSchemas: async () => [{ name: "analytics" }], + listTables: async () => [{ name: "events", type: "BASE TABLE" }], + getSchemaMetadataBatch: async () => ({ + tables: new Map([ + [ + "events", + { + columns: [], + primaryKeys: [], + foreignKeys: [], + indexes: [], + uniqueConstraints: [], + checkConstraints: [], + }, + ], + ]), + }), + }; + + const getConnSpy = jest + .spyOn(connectorRegistry, "getConnector") + .mockReturnValue(fakeConnector as any); + + const mockDbService = { + withConnection: async ( + _id: string, + fn: (conn: any, db: any, dbType: DBType) => Promise, + ) => fn({}, {}, DBType.CLICKHOUSE), + } as any; + + try { + await expect(introspectLiveCanonicalAST(mockDbService, {} as any, "db-ch")).rejects.toThrow( + /Incomplete ClickHouse metadata/, + ); + } finally { + getConnSpy.mockRestore(); + } + }); + + test("preserves newline terminators after SQL line comments in normalizeExpression", () => { + expect(normalizeExpression("SELECT 1 -- note\n UNION ALL SELECT 2")).toBe( + "SELECT 1 -- note\nUNION ALL SELECT 2", + ); + expect(normalizeExpression("SELECT 1 -- note\r\n UNION ALL SELECT 2")).toBe( + "SELECT 1 -- note\nUNION ALL SELECT 2", + ); + expect(normalizeExpression("( SELECT 1 -- note\n )")).toBe("(SELECT 1 -- note\n)"); + expect(normalizeExpression('SELECT 1 -- "age"\nUNION ALL SELECT "age" FROM t')).toBe( + 'SELECT 1 -- "age"\nUNION ALL SELECT "age" FROM t', + ); + expect( + normalizeExpressionForComparison( + 'SELECT 1 -- "age"\nUNION ALL SELECT "age" FROM t', + "postgresql", + ), + ).toBe('SELECT 1 -- "age"\nUNION ALL SELECT age FROM t'); + }); + + test("keeps quoted non-unquotable dialect keywords distinct while equating ordinary identifiers", () => { + for (const kw of [ + "localtimestamp", + "localtime", + "current_timestamp", + "current_date", + "current_time", + "current_user", + "session_user", + "user", + "current_catalog", + "current_role", + "current_schema", + "system_user", + ]) { + expect(normalizeExpressionForComparison(`SELECT "${kw}" FROM t`, "postgresql")).toBe( + `SELECT "${kw}" FROM t`, + ); + expect(normalizeExpressionForComparison(`SELECT ${kw} FROM t`, "postgresql")).toBe( + `SELECT ${kw} FROM t`, + ); + } + expect(normalizeExpressionForComparison('SELECT "age" FROM t', "postgresql")).toBe( + "SELECT age FROM t", + ); + expect(normalizeExpressionForComparison('SELECT "pragma" FROM t', "sqlite")).toBe( + 'SELECT "pragma" FROM t', + ); + expect(normalizeExpressionForComparison("SELECT `utc_timestamp` FROM t", "mysql")).toBe( + "SELECT `utc_timestamp` FROM t", + ); + }); + + test("extractViewMetadata captures explicit view columns and handles SQLite backslash view names", () => { + expect(extractViewMetadata('CREATE VIEW "v\\"' + " AS SELECT 1", DBType.SQLITE)).toEqual({ + body: "SELECT 1", + }); + expect(extractViewBody('CREATE VIEW "v\\"' + " AS SELECT 1", DBType.SQLITE)).toBe("SELECT 1"); + expect( + extractViewMetadata('CREATE VIEW "v""q" ("x", "y""z") AS SELECT 1, 2;', DBType.SQLITE), + ).toEqual({ + body: "SELECT 1, 2", + columns: ["x", 'y"z'], + }); + expect(extractViewMetadata("CREATE VIEW v(x) AS SELECT 1", DBType.SQLITE)).toEqual({ + body: "SELECT 1", + columns: ["x"], + }); + expect(extractViewMetadata("CREATE VIEW v AS SELECT 1", DBType.DUCKDB)).toEqual({ + body: "SELECT 1", + }); + + const ast = normalizeLiveSqlSchemas( + { + schemas: [ + { + name: "main", + tables: [], + views: [ + { name: "v_cols", definition: "SELECT 1, 2", columns: ["a", "b"] }, + { name: "v_plain", definition: "SELECT 1" }, + ], + }, + ], + }, + "sqlite", + ); + expect(ast.schemas[0].views).toEqual([ + { name: "v_cols", definition: "SELECT 1, 2", columns: ["a", "b"] }, + { name: "v_plain", definition: "SELECT 1" }, + ]); + }); + + test("ClickHouse uses reportedPrimaryKeys instead of fallback and rejects batch metadata errors", async () => { + const fakeConnector = { + listSchemas: async () => [{ name: "analytics" }], + listTables: async () => [{ name: "events", type: "BASE TABLE" }], + getSchemaMetadataBatch: async () => ({ + tables: new Map([ + [ + "events", + { + columns: [{ name: "id", type: "UInt64", not_nullable: true, is_primary_key: false }], + primaryKeys: [{ column_name: "id" }], + reportedPrimaryKeys: [], + foreignKeys: [], + indexes: [], + uniqueConstraints: [], + checkConstraints: [], + }, + ], + ]), + }), + }; + + const getConnSpy = jest + .spyOn(connectorRegistry, "getConnector") + .mockReturnValue(fakeConnector as any); + + const mockDbService = { + withConnection: async ( + _id: string, + fn: (conn: any, db: any, dbType: DBType) => Promise, + ) => fn({}, {}, DBType.CLICKHOUSE), + } as any; + + try { + const ast = await introspectLiveCanonicalAST(mockDbService, {} as any, "db-ch"); + expect(ast.schemas[0].tables[0].primaryKeyColumns).toBeUndefined(); + + fakeConnector.getSchemaMetadataBatch = async () => + ({ + tables: new Map(), + indexMetadataError: new Error("system.data_skipping_indices failed"), + }) as any; + await expect(introspectLiveCanonicalAST(mockDbService, {} as any, "db-ch")).rejects.toThrow( + /Incomplete ClickHouse index metadata/, + ); + + fakeConnector.getSchemaMetadataBatch = async () => + ({ + tables: new Map(), + columnMetadataErrors: new Map([["events", new Error("DESCRIBE failed")]]), + }) as any; + await expect(introspectLiveCanonicalAST(mockDbService, {} as any, "db-ch")).rejects.toThrow( + /Incomplete ClickHouse column metadata/, + ); + } finally { + getConnSpy.mockRestore(); + } + }); + + test("prefers throwing fatal connection rejection over earlier non-fatal schema rejection", async () => { + const nonFatal = new Error("permission denied on schema s1"); + const fatal = new Error("ECONNRESET"); + + const fakeConnector = { + listSchemas: async () => [{ name: "s1" }, { name: "s2" }], + listTables: async (_conn: unknown, schema: string) => { + if (schema === "s1") throw nonFatal; + throw fatal; + }, + getSchemaMetadataBatch: async () => ({ tables: new Map() }), + }; + + const getConnSpy = jest + .spyOn(connectorRegistry, "getConnector") + .mockReturnValue(fakeConnector as any); + + const mockDbService = { + isFatalConnectionError: (err: unknown) => err === fatal, + withConnection: async ( + _id: string, + fn: (conn: any, db: any, dbType: DBType) => Promise, + ) => fn({}, {}, DBType.POSTGRES), + } as any; + + try { + await expect(introspectLiveCanonicalAST(mockDbService, {} as any, "db-pg")).rejects.toBe( + fatal, + ); + } finally { + getConnSpy.mockRestore(); + } + }); + + test("applies MySQL/MariaDB whitespace rule for -- comments while keeping -- comments in other dialects", () => { + const arithWithCrlf = "SELECT 1--LENGTH('a\r\n b')"; + expect(normalizeExpression(arithWithCrlf, "mysql")).toBe("SELECT 1--LENGTH('a\r\n b')"); + expect(normalizeExpression(arithWithCrlf, "mariadb")).toBe("SELECT 1--LENGTH('a\r\n b')"); + expect(normalizeExpression("SELECT 1--LENGTH(x)", "mysql")).toBe("SELECT 1--LENGTH(x)"); + expect(normalizeExpression("SELECT 1--LENGTH(x)", "mariadb")).toBe("SELECT 1--LENGTH(x)"); + + // Actual MySQL/MariaDB line comments (space, tab, newline, control char, EOF) + expect(normalizeExpression("SELECT 1 -- comment\r\n FROM t", "mysql")).toBe( + "SELECT 1 -- comment\nFROM t", + ); + expect(normalizeExpression("SELECT 1 --\tcomment\r\n FROM t", "mariadb")).toBe( + "SELECT 1 --\tcomment\nFROM t", + ); + expect(normalizeExpression("SELECT 1 --\n FROM t", "mysql")).toBe("SELECT 1 --\nFROM t"); + expect(normalizeExpression("SELECT 1 --\x01ctrl\r\n FROM t", "mysql")).toBe( + "SELECT 1 --\x01ctrl\nFROM t", + ); + expect(normalizeExpression("SELECT 1 --", "mysql")).toBe("SELECT 1 --"); + + // Non-MySQL dialects still treat -- without space as a line comment + for (const d of ["postgresql", "sqlite", "duckdb", "clickhouse"] as const) { + expect(normalizeExpression("SELECT 1--note\r\n FROM t", d)).toBe("SELECT 1--note\nFROM t"); + } + + // Full view/check/default normalization via normalizeSchemaFile passes dialect + const mysqlAst = normalizeSchemaFile({ + dialect: "mysql", + schemas: [ + { + name: "app", + tables: [], + enums: [], + views: [{ name: "v_arith", definition: arithWithCrlf }], + }, + ], + }); + expect(mysqlAst.schemas[0].views[0].definition).toBe("SELECT 1--LENGTH('a\r\n b')"); + }); + + test("extractViewMetadata handles non-ASCII unicode identifier prefix followed by 'as'", () => { + const result = extractViewMetadata("CREATE VIEW 🚀as(x) AS SELECT 1", DBType.SQLITE); + expect(result).toEqual({ + body: "SELECT 1", + columns: ["x"], + }); + + const result2 = extractViewMetadata("CREATE VIEW aſ(x) AS SELECT 1", DBType.SQLITE); + expect(result2).toEqual({ + body: "SELECT 1", + columns: ["x"], + }); + }); + + test("normalizeExpression preserves trailing newline for MySQL '#' comment and adjacent PG strings", () => { + expect(normalizeExpression("SELECT 1 # comment\n+ 2", "mysql")).toBe("SELECT 1 # comment\n+ 2"); + expect(normalizeExpression("SELECT 'hello'\n'world'", "postgresql")).toBe( + "SELECT 'hello'\n'world'", + ); + }); +}); diff --git a/bridge/src/ai/prompts/performance-copilot.ts b/bridge/src/ai/prompts/performance-copilot.ts new file mode 100644 index 00000000..5c3774d4 --- /dev/null +++ b/bridge/src/ai/prompts/performance-copilot.ts @@ -0,0 +1,425 @@ +import type { + AIDropIndexCandidate, + AIPerformanceAnalysisInput, + AIPerformanceResult, + AIRecommendedIndex, +} from "../../types/ai"; +import type { ExplainPlanNode, NormalizedExplainPlan } from "../../types/performance"; +import { SYSTEM_CONTEXT } from "./shared"; + +function isIdentChar(ch: string): boolean { + return /[\p{L}\p{N}_$]/u.test(ch); +} + +/** + * Redact sensitive literal values in SQL and MQL queries before sending to cloud LLMs. + * - Single-quoted strings `'...'` (with `''` / `\'` escapes) -> `'?'` + * - Double-quoted JSON string values inside MQL filters (`{"email": "a@b.com"}` -> `{"email": "?"}`), + * while preserving JSON keys and SQL double-quoted identifiers + * - Standalone numeric literals (`\b\d+(?:\.\d+)?\b` outside identifiers) -> `?` + */ +export function redactQueryLiterals(query: string): string { + if (!query) return query; + + let out = ""; + let i = 0; + let braceDepth = 0; + const len = query.length; + + while (i < len) { + const ch = query[i]; + + // Track JSON/MQL object or array depth so we only redact double-quoted values inside filters + if (ch === "{" || ch === "[") { + braceDepth++; + out += ch; + i++; + continue; + } + if (ch === "}" || ch === "]") { + braceDepth = Math.max(0, braceDepth - 1); + out += ch; + i++; + continue; + } + + // Single-quoted string literal: '...' with '' or \' escapes + if (ch === "'") { + i++; + while (i < len) { + if (query[i] === "\\" && i + 1 < len) { + i += 2; + continue; + } + if (query[i] === "'") { + if (i + 1 < len && query[i + 1] === "'") { + i += 2; + continue; + } + i++; + break; + } + i++; + } + out += "'?'"; + continue; + } + + // Double-quoted string: JSON key, JSON string value, or SQL quoted identifier + if (ch === '"') { + const start = i; + i++; + while (i < len) { + if (query[i] === "\\" && i + 1 < len) { + i += 2; + continue; + } + if (query[i] === '"') { + if (i + 1 < len && query[i + 1] === '"') { + i += 2; + continue; + } + i++; + break; + } + i++; + } + const literal = query.slice(start, i); + + // Look ahead past whitespace: if followed by ':', this is a JSON object key + let lookahead = i; + while (lookahead < len && /\s/.test(query[lookahead])) { + lookahead++; + } + const isJsonKey = query[lookahead] === ":"; + + if (braceDepth > 0 && !isJsonKey) { + out += '"?"'; + } else { + out += literal; + } + continue; + } + + // PostgreSQL dollar-quoted string literals: $$...$$ or $tag$...$tag$ + if (ch === "$") { + const dollarMatch = query.slice(i).match(/^\$(?:[\p{L}_][\p{L}\p{N}_]*)?\$/u); + if (dollarMatch) { + const delim = dollarMatch[0]; + const closeIdx = query.indexOf(delim, i + delim.length); + if (closeIdx !== -1) { + out += "'?'"; + i = closeIdx + delim.length; + continue; + } + } + } + + // Identifier starting with letter, underscore, or $: consume whole token without touching digits + if (/[\p{L}_$]/u.test(ch)) { + const start = i; + i++; + while (i < len && isIdentChar(query[i])) { + i++; + } + out += query.slice(start, i); + continue; + } + + // Standalone numeric literal (not preceded by identifier char) + if (/[0-9]/.test(ch) && (i === 0 || !isIdentChar(query[i - 1]))) { + let j = i; + while (j < len && /[0-9]/.test(query[j])) { + j++; + } + if (j < len && query[j] === "." && j + 1 < len && /[0-9]/.test(query[j + 1])) { + j++; + while (j < len && /[0-9]/.test(query[j])) { + j++; + } + } + // Only redact if not immediately followed by an identifier character (e.g. 123abc) + if (j === len || !isIdentChar(query[j])) { + out += "?"; + i = j; + continue; + } + } + + out += ch; + i++; + } + + return out; +} + +function redactPlanNodeLiterals(node: ExplainPlanNode): ExplainPlanNode { + return { + ...node, + ...(node.filter !== undefined ? { filter: redactQueryLiterals(node.filter) } : {}), + children: (node.children ?? []).map(redactPlanNodeLiterals), + }; +} + +/** + * Redact sensitive literal values inside an explain plan's tree filters and bottleneck details. + */ +export function redactExplainPlanLiterals(plan: NormalizedExplainPlan): NormalizedExplainPlan { + return { + ...plan, + bottlenecks: (plan.bottlenecks ?? []).map((b) => ({ + ...b, + details: redactQueryLiterals(b.details), + })), + ...(plan.planTree ? { planTree: redactPlanNodeLiterals(plan.planTree) } : {}), + }; +} + +function serializePlanNode(node: ExplainPlanNode, depth = 0): string { + const indent = " ".repeat(depth); + const parts: string[] = [node.nodeType]; + if (node.relation) parts.push(`on ${node.relation}`); + if (node.indexName) parts.push(`using ${node.indexName}`); + const metrics: string[] = []; + if (node.cost !== undefined) metrics.push(`cost=${node.cost}`); + if (node.rows !== undefined) metrics.push(`rows=${node.rows}`); + if (node.actualRows !== undefined) metrics.push(`actualRows=${node.actualRows}`); + if (node.actualTimeMs !== undefined) metrics.push(`timeMs=${node.actualTimeMs}`); + if (node.filter) metrics.push(`filter=${node.filter}`); + + const line = `${indent}- ${parts.join(" ")}${metrics.length ? ` (${metrics.join(", ")})` : ""}`; + const children = (node.children ?? []).map((child) => serializePlanNode(child, depth + 1)); + return [line, ...children].join("\n"); +} + +/** + * Build the system and user prompts for AI Performance & Index Copilot analysis. + */ +export function buildPerformanceCopilotPrompt(input: AIPerformanceAnalysisInput): { + system: string; + user: string; +} { + const system = `${SYSTEM_CONTEXT} +You are acting as a database Performance & Index Copilot. +Analyze the query, normalized EXPLAIN plan, and optional index health report, then respond ONLY with a valid JSON object matching the requested schema.`; + + const { plan, indexHealth } = input; + const planStats: string[] = []; + if (plan.totalCost !== undefined) planStats.push(`totalCost: ${plan.totalCost}`); + if (plan.rowsExamined !== undefined) planStats.push(`rowsExamined: ${plan.rowsExamined}`); + if (plan.rowsReturned !== undefined) planStats.push(`rowsReturned: ${plan.rowsReturned}`); + if (plan.executionTimeMs !== undefined) + planStats.push(`executionTimeMs: ${plan.executionTimeMs}`); + if (plan.planningTimeMs !== undefined) planStats.push(`planningTimeMs: ${plan.planningTimeMs}`); + + const bottlenecksText = + plan.bottlenecks && plan.bottlenecks.length > 0 + ? plan.bottlenecks + .map( + (b) => + `- [${b.severity.toUpperCase()}] ${b.type}${b.target ? ` (${b.target})` : ""}: ${b.details}`, + ) + .join("\n") + : "None detected."; + + const planTreeText = plan.planTree ? serializePlanNode(plan.planTree) : "No plan tree available."; + + let indexHealthSection = ""; + if (indexHealth) { + const unusedLines = (indexHealth.unusedIndexes ?? []) + .slice(0, 20) + .map( + (idx) => + `- ${idx.schema ? `${idx.schema}.` : ""}${idx.tableOrCollection}.${idx.indexName} (${idx.columns.join(", ")}) scans=${idx.scans ?? "unknown"} sizeBytes=${idx.sizeBytes ?? "unknown"}`, + ); + const dupLines = (indexHealth.duplicateIndexes ?? []) + .slice(0, 20) + .map( + (dup) => + `- ${dup.schema ? `${dup.schema}.` : ""}${dup.tableOrCollection}.${dup.indexName} redundantWith=${dup.redundantWith} (${dup.reason})`, + ); + + indexHealthSection = ` +## Index Health Summary +Total indexes: ${indexHealth.summary.total}, Unused: ${indexHealth.summary.unusedCount}, Duplicate: ${indexHealth.summary.duplicateCount}, Total size (bytes): ${indexHealth.summary.totalSizeBytes} + +### Unused Indexes +${unusedLines.length ? unusedLines.join("\n") : "None."} + +### Duplicate Indexes +${dupLines.length ? dupLines.join("\n") : "None."} +`; + } + + const user = `Analyze this ${input.dialect} query and execution plan. + +## Dialect +${input.dialect} + +## Query +\`\`\` +${input.query} +\`\`\` + +## Execution Plan Metrics +${planStats.length ? planStats.join(" | ") : "No aggregate metrics reported."} + +## Detected Bottlenecks +${bottlenecksText} + +## Plan Tree +${planTreeText} +${indexHealthSection} +## Output Format +Respond ONLY with a valid JSON object (no markdown fences, no extra prose) matching this exact shape: +{ + "summary": "", + "estimatedImpact": "high" | "medium" | "low", + "rewrittenQuery": "", + "recommendedIndexes": [ + { + "schema": "", + "tableOrCollection": "", + "indexName": "", + "columns": ["", ""], + "unique": false, + "reason": "", + "ddlPreview": "" + } + ], + "dropCandidates": [ + { + "schema": "", + "tableOrCollection": "
", + "indexName": "", + "reason": "" + } + ], + "warnings": [""] +}`; + + return { system, user }; +} + +function normalizeEstimatedImpact(value: unknown): "high" | "medium" | "low" { + if (typeof value === "string") { + const lower = value.toLowerCase().trim(); + if (lower === "high" || lower === "medium" || lower === "low") { + return lower; + } + } + return "medium"; +} + +function normalizeRecommendedIndexes(items: unknown): AIRecommendedIndex[] { + if (!Array.isArray(items)) return []; + const result: AIRecommendedIndex[] = []; + for (const item of items) { + if (!item || typeof item !== "object") continue; + const rec = item as Record; + const tableOrCollection = String(rec.tableOrCollection ?? "").trim(); + const indexName = String(rec.indexName ?? "").trim(); + const columns = Array.isArray(rec.columns) + ? rec.columns.map((c) => String(c).trim()).filter(Boolean) + : []; + if (!tableOrCollection || !indexName) continue; + result.push({ + ...(typeof rec.schema === "string" && rec.schema.trim() ? { schema: rec.schema.trim() } : {}), + tableOrCollection, + indexName, + columns, + ...(typeof rec.unique === "boolean" ? { unique: rec.unique } : {}), + reason: String(rec.reason ?? ""), + ddlPreview: String(rec.ddlPreview ?? ""), + }); + } + return result; +} + +function normalizeDropCandidates(items: unknown): AIDropIndexCandidate[] { + if (!Array.isArray(items)) return []; + const result: AIDropIndexCandidate[] = []; + for (const item of items) { + if (!item || typeof item !== "object") continue; + const rec = item as Record; + const tableOrCollection = String(rec.tableOrCollection ?? "").trim(); + const indexName = String(rec.indexName ?? "").trim(); + if (!tableOrCollection || !indexName) continue; + result.push({ + ...(typeof rec.schema === "string" && rec.schema.trim() ? { schema: rec.schema.trim() } : {}), + tableOrCollection, + indexName, + reason: String(rec.reason ?? ""), + }); + } + return result; +} + +function extractJsonCandidate(rawText: string): string { + const stripped = rawText + .replace(/```json\s*/gi, "") + .replace(/```\s*/g, "") + .trim(); + + if (stripped.startsWith("{") && stripped.endsWith("}")) { + return stripped; + } + + const firstBrace = stripped.indexOf("{"); + const lastBrace = stripped.lastIndexOf("}"); + if (firstBrace !== -1 && lastBrace > firstBrace) { + return stripped.slice(firstBrace, lastBrace + 1); + } + return stripped; +} + +/** + * Parse and normalize the LLM response into an `AIPerformanceResult`. + * Strips markdown code fences if present and gracefully falls back on non-JSON responses. + */ +export function parsePerformanceCopilotResponse(rawText: string): AIPerformanceResult { + const fallback: AIPerformanceResult = { + summary: rawText, + estimatedImpact: "medium", + recommendedIndexes: [], + dropCandidates: [], + warnings: [], + }; + + if (!rawText || !rawText.trim()) { + return fallback; + } + + try { + const candidate = extractJsonCandidate(rawText); + const parsed = JSON.parse(candidate) as Record; + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + return fallback; + } + + const summary = + typeof parsed.summary === "string" && parsed.summary.trim() + ? parsed.summary.trim() + : rawText.trim(); + + const rewrittenQuery = + typeof parsed.rewrittenQuery === "string" && parsed.rewrittenQuery.trim() + ? parsed.rewrittenQuery.trim() + : undefined; + + const warnings = Array.isArray(parsed.warnings) + ? parsed.warnings.map((w) => String(w).trim()).filter(Boolean) + : []; + + return { + summary, + estimatedImpact: normalizeEstimatedImpact(parsed.estimatedImpact), + ...(rewrittenQuery ? { rewrittenQuery } : {}), + recommendedIndexes: normalizeRecommendedIndexes(parsed.recommendedIndexes), + dropCandidates: normalizeDropCandidates(parsed.dropCandidates), + warnings, + }; + } catch { + return fallback; + } +} diff --git a/bridge/src/connectors/clickhouse.ts b/bridge/src/connectors/clickhouse.ts index 3cf10f39..448e36fb 100644 --- a/bridge/src/connectors/clickhouse.ts +++ b/bridge/src/connectors/clickhouse.ts @@ -1,6 +1,6 @@ import { createClient, type ClickHouseClient } from "@clickhouse/client"; -import { ClickHouseConfig, ClickHouseSchemaMetadataBatch } from "../types/clickhouse"; -export type { ClickHouseConfig, ClickHouseSchemaMetadataBatch }; +import { ClickHouseConfig } from "../types/clickhouse"; +export type { ClickHouseConfig }; import { TableInfo, PrimaryKeyInfo, @@ -533,6 +533,149 @@ export async function getTableDetails( return columns; } +export type ClickHouseSchemaMetadataBatch = { + tables: Map< + string, + { + columns: ColumnDetail[]; + primaryKeys: PrimaryKeyInfo[]; + reportedPrimaryKeys?: string[]; + foreignKeys: ForeignKeyInfo[]; + indexes: IndexInfo[]; + uniqueConstraints: UniqueConstraintInfo[]; + checkConstraints: CheckConstraintInfo[]; + } + >; + indexMetadataError?: unknown; + primaryKeyMetadataError?: string; + columnMetadataErrors?: Record; + columnMetadataError?: string; +}; + +function parseClickHouseKeyColumns(sortingKey: unknown, primaryKey: unknown): string[] | null { + if (typeof sortingKey !== "string" && typeof primaryKey !== "string") { + return null; + } + const rawSorting = typeof sortingKey === "string" ? sortingKey.trim() : ""; + const rawPrimary = typeof primaryKey === "string" ? primaryKey.trim() : ""; + const raw = rawSorting || rawPrimary; + if (!raw || /^tuple\s*\(\s*\)$/i.test(raw)) { + return []; + } + + let expr = raw; + while (expr.startsWith("(") && expr.endsWith(")")) { + let depth = 0; + let quote: string | null = null; + let wrapsAll = true; + for (let i = 0; i < expr.length; i++) { + const ch = expr[i]; + if (quote) { + if (ch === "\\" && i + 1 < expr.length) { + i++; + } else if (ch === quote) { + if (expr[i + 1] === quote) { + i++; + } else { + quote = null; + } + } + continue; + } + if (ch === "'" || ch === '"' || ch === "`") { + quote = ch; + } else if (ch === "(") { + depth++; + } else if (ch === ")") { + depth--; + if (depth === 0 && i < expr.length - 1) { + wrapsAll = false; + break; + } + } + } + if (!wrapsAll || depth !== 0) break; + expr = expr.slice(1, -1).trim(); + } + if (!expr || /^tuple\s*\(\s*\)$/i.test(expr)) { + return []; + } + + const parts: string[] = []; + let start = 0; + let depth = 0; + let quote: string | null = null; + for (let i = 0; i < expr.length; i++) { + const ch = expr[i]; + if (quote) { + if (ch === "\\" && i + 1 < expr.length) { + i++; + } else if (ch === quote) { + if (expr[i + 1] === quote) { + i++; + } else { + quote = null; + } + } + continue; + } + if (ch === "'" || ch === '"' || ch === "`") { + quote = ch; + } else if (ch === "(") { + depth++; + } else if (ch === ")") { + if (depth > 0) depth--; + } else if (ch === "," && depth === 0) { + parts.push(expr.slice(start, i).trim()); + start = i + 1; + } + } + parts.push(expr.slice(start).trim()); + + const cols: string[] = []; + for (const rawPart of parts) { + if (!rawPart) return null; + const part = rawPart.replace(/\s+(?:ASC|DESC)$/i, "").trim(); + let colName: string | null = null; + if ( + part.length >= 2 && + ((part.startsWith("`") && part.endsWith("`")) || (part.startsWith('"') && part.endsWith('"'))) + ) { + const q = part[0]; + const inner = part.slice(1, -1); + let valid = true; + let unescaped = ""; + for (let i = 0; i < inner.length; i++) { + const ch = inner[i]; + if (ch === "\\" && i + 1 < inner.length) { + unescaped += inner[i + 1]; + i++; + } else if (ch === q) { + if (inner[i + 1] === q) { + unescaped += q; + i++; + } else { + valid = false; + break; + } + } else { + unescaped += ch; + } + } + if (valid && unescaped) { + colName = unescaped; + } + } else if (/^[\p{L}_][\p{L}\p{N}_$]*$/u.test(part)) { + colName = part; + } + if (!colName) return null; + if (!cols.includes(colName)) { + cols.push(colName); + } + } + return cols; +} + export async function getSchemaMetadataBatch( cfg: ClickHouseConfig, schemaNameOrTables?: string | string[], @@ -555,6 +698,7 @@ export async function getSchemaMetadataBatch( { columns: ColumnDetail[]; primaryKeys: PrimaryKeyInfo[]; + reportedPrimaryKeys?: string[]; foreignKeys: ForeignKeyInfo[]; indexes: IndexInfo[]; uniqueConstraints: UniqueConstraintInfo[]; @@ -568,6 +712,7 @@ export async function getSchemaMetadataBatch( entry = { columns: [], primaryKeys: [], + reportedPrimaryKeys: undefined, foreignKeys: [], indexes: [], uniqueConstraints: [], @@ -618,6 +763,7 @@ export async function getSchemaMetadataBatch( } // 2. Batch fetch columns + let batchColumnsError: unknown = null; try { const colRes = await client.query({ query: CLICKHOUSE_BATCH_LIST_COLUMNS, @@ -641,10 +787,12 @@ export async function getSchemaMetadataBatch( }); } } catch (err: any) { + batchColumnsError = err; logger.warn({ err: err?.message, schema }, "ClickHouse CLICKHOUSE_BATCH_LIST_COLUMNS failed"); } // 3. Batch fetch primary keys + let batchPrimaryKeysError: unknown = null; try { const pkRes = await client.query({ query: CLICKHOUSE_BATCH_GET_PRIMARY_KEYS, @@ -658,8 +806,15 @@ export async function getSchemaMetadataBatch( if (!tbl || (filterTables && !filterTables.has(tbl))) continue; const entry = getOrCreateTable(tbl); entry.primaryKeys.push({ column_name: r.column_name }); + if (!entry.reportedPrimaryKeys) { + entry.reportedPrimaryKeys = []; + } + if (r.column_name && !entry.reportedPrimaryKeys.includes(r.column_name)) { + entry.reportedPrimaryKeys.push(r.column_name); + } } } catch (err: any) { + batchPrimaryKeysError = err; logger.warn( { err: err?.message, schema }, "ClickHouse CLICKHOUSE_BATCH_GET_PRIMARY_KEYS failed", @@ -667,6 +822,7 @@ export async function getSchemaMetadataBatch( } // 4. Batch fetch secondary indexes + let indexMetadataError: unknown; try { const idxRes = await client.query({ query: CLICKHOUSE_BATCH_GET_INDEXES, @@ -689,10 +845,9 @@ export async function getSchemaMetadataBatch( }); } } catch (err: any) { - logger.debug( - { err: err?.message, schema }, - "ClickHouse CLICKHOUSE_BATCH_GET_INDEXES skipped/failed", - ); + indexMetadataError = err ?? new Error("Unknown error"); + const warnMsg = err instanceof Error ? err.message : String(err || "Unknown error"); + logger.warn({ err: warnMsg, schema }, "ClickHouse CLICKHOUSE_BATCH_GET_INDEXES failed"); } // 5. Direct fallback: If tablesMap is still empty after batch queries, query system.tables directly @@ -714,18 +869,94 @@ export async function getSchemaMetadataBatch( } } + // 5b. Recover authoritative key order from system.tables when batch primary keys query failed + let primaryKeyMetadataError: string | undefined; + if (batchPrimaryKeysError) { + if (tablesMap.size > 0) { + try { + const pkOrderRes = await client.query({ + query: `SELECT name, primary_key, sorting_key FROM system.tables WHERE database = {target_schema: String} ORDER BY name`, + query_params: { target_schema: schema, schema }, + format: "JSONEachRow", + }); + const pkOrderRows = (await pkOrderRes.json()) as any[]; + const byTable = new Map(); + for (const row of pkOrderRows) { + if (row?.name) { + byTable.set(String(row.name), row); + } + } + for (const [tableName, entry] of tablesMap.entries()) { + const row = byTable.get(tableName); + if ( + !row || + (typeof row.sorting_key !== "string" && typeof row.primary_key !== "string") + ) { + primaryKeyMetadataError = + primaryKeyMetadataError ?? + (batchPrimaryKeysError instanceof Error + ? batchPrimaryKeysError.message + : String(batchPrimaryKeysError || "Missing ClickHouse key metadata")); + continue; + } + const parsedKeys = parseClickHouseKeyColumns(row.sorting_key, row.primary_key); + if (parsedKeys === null) { + primaryKeyMetadataError = + primaryKeyMetadataError ?? + `Unable to determine authoritative ClickHouse key order for '${schema}.${tableName}'`; + continue; + } + entry.reportedPrimaryKeys = parsedKeys; + if (entry.primaryKeys.length === 0 && parsedKeys.length > 0) { + entry.primaryKeys = parsedKeys.map((column_name) => ({ column_name })); + } + } + } catch (err: any) { + primaryKeyMetadataError = + err instanceof Error ? err.message : String(err || "Unknown error"); + logger.warn( + { err: primaryKeyMetadataError, schema }, + "ClickHouse fallback system.tables primary/sorting key query failed", + ); + } + } else { + primaryKeyMetadataError = + batchPrimaryKeysError instanceof Error + ? batchPrimaryKeysError.message + : String(batchPrimaryKeysError || "Unknown error"); + } + } + // 6. Guaranteed population: Ensure every table in tablesMap has columns and primary keys populated + const columnMetadataErrors: Record = {}; + let columnFallbackError: unknown = null; + let hasLoadedColumns = false; for (const [tableName, entry] of tablesMap.entries()) { if (entry.columns.length === 0) { try { const fallbackCols = await getTableDetails(cfg, schema, tableName); if (fallbackCols && fallbackCols.length > 0) { entry.columns = fallbackCols; + } else if (batchColumnsError) { + const msg = + batchColumnsError instanceof Error + ? batchColumnsError.message + : String(batchColumnsError || "unknown error"); + columnMetadataErrors[tableName] = msg; } } catch (err: any) { - logger.warn({ err: err?.message, schema, tableName }, "Fallback getTableDetails failed"); + columnFallbackError = err; + const msg = err instanceof Error ? err.message : String(err || "unknown error"); + logger.warn({ err: msg, schema, tableName }, "Fallback getTableDetails failed"); + columnMetadataErrors[tableName] = msg; } } + if (entry.columns.length > 0) { + hasLoadedColumns = true; + } + if (!batchPrimaryKeysError && entry.reportedPrimaryKeys === undefined) { + entry.reportedPrimaryKeys = []; + } if (entry.primaryKeys.length === 0) { try { const fallbackPks = await listPrimaryKeys(cfg, schema, tableName); @@ -738,7 +969,53 @@ export async function getSchemaMetadataBatch( } } - return { tables: tablesMap }; + if (batchPrimaryKeysError) { + let unrecoveredKeyTable: string | null = null; + for (const [tableName, entry] of tablesMap.entries()) { + if (entry.reportedPrimaryKeys === undefined) { + unrecoveredKeyTable = tableName; + break; + } + } + if (unrecoveredKeyTable) { + primaryKeyMetadataError = + primaryKeyMetadataError ?? + `Unable to determine authoritative ClickHouse key order for '${schema}.${unrecoveredKeyTable}'`; + } else { + primaryKeyMetadataError = undefined; + } + } + + const failedColumnTables = Object.keys(columnMetadataErrors); + if (batchColumnsError && (tablesMap.size === 0 || !hasLoadedColumns)) { + const rootCause = columnFallbackError ?? batchColumnsError; + const causeMsg = + rootCause instanceof Error + ? rootCause.message + : rootCause + ? String(rootCause) + : "unknown error"; + const tableSuffix = + failedColumnTables.length > 0 ? ` (tables: ${failedColumnTables.join(", ")})` : ""; + throw Object.assign( + new Error( + `Failed to retrieve ClickHouse column metadata for schema '${schema}'${tableSuffix}: ${causeMsg}`, + ), + { cause: rootCause }, + ); + } + + const columnMetadataError = + failedColumnTables.length > 0 + ? `Failed to retrieve ClickHouse column metadata for table(s) in schema '${schema}' (${failedColumnTables.join(", ")}): ${failedColumnTables.map((t) => `${t}: ${columnMetadataErrors[t]}`).join("; ")}` + : undefined; + + return { + tables: tablesMap, + ...(indexMetadataError !== undefined ? { indexMetadataError } : {}), + ...(primaryKeyMetadataError !== undefined ? { primaryKeyMetadataError } : {}), + ...(failedColumnTables.length > 0 ? { columnMetadataErrors, columnMetadataError } : {}), + }; } export function streamQueryCancelable( diff --git a/bridge/src/connectors/duckdb.ts b/bridge/src/connectors/duckdb.ts index 9d0aba0f..8d012231 100644 --- a/bridge/src/connectors/duckdb.ts +++ b/bridge/src/connectors/duckdb.ts @@ -225,7 +225,11 @@ export async function closeDB(filePath: string): Promise { openingPromises.delete(normalizedPath); } -async function runQuery(cfg: DuckDBConfig, sql: string, ...args: any[]): Promise { +export async function runQuery( + cfg: DuckDBConfig, + sql: string, + ...args: any[] +): Promise { const { conn } = await openDB(cfg); try { const stmt = await conn.prepare(sql); diff --git a/bridge/src/connectors/sqlite.ts b/bridge/src/connectors/sqlite.ts index 190c43f9..2631da96 100644 --- a/bridge/src/connectors/sqlite.ts +++ b/bridge/src/connectors/sqlite.ts @@ -458,6 +458,13 @@ export function resolvePkgNativeBindingPath(): string | undefined { return undefined; } +export function openSQLiteDB( + cfg: SQLiteConfig, + extraOptions: Database.Options = {}, +): Database.Database { + return openDB(cfg, extraOptions); +} + function openDB(cfg: SQLiteConfig, extraOptions: Database.Options = {}): Database.Database { const nativeBinding = resolvePkgNativeBindingPath(); const dbPath = validateSQLitePath(cfg.path, { @@ -1273,61 +1280,182 @@ export async function connectToDatabase( }; } -/** Apply a pending migration */ -export async function applyMigration( +/** + * Detects an explicit `-- @relwave-sqlite-rebuild` line-comment directive at the start + * of a line outside string literals, quoted identifiers, and block comments. + */ +export function hasSqliteRebuildDirective(sql: string): boolean { + let i = 0; + let atLineStart = true; + + while (i < sql.length) { + const ch = sql[i]; + + if (ch === "\n") { + atLineStart = true; + i++; + continue; + } + if (ch === "\r" || ch === " " || ch === "\t") { + i++; + continue; + } + + // Line comment + if (ch === "-" && sql[i + 1] === "-") { + const lineEnd = sql.indexOf("\n", i + 2); + const commentLine = lineEnd === -1 ? sql.slice(i) : sql.slice(i, lineEnd); + if (atLineStart && /^--\s*@relwave-sqlite-rebuild(?:\s|$)/.test(commentLine)) { + return true; + } + if (lineEnd === -1) break; + i = lineEnd + 1; + atLineStart = true; + continue; + } + + // Block comment + if (ch === "/" && sql[i + 1] === "*") { + const end = sql.indexOf("*/", i + 2); + if (end === -1) break; + i = end + 2; + atLineStart = false; + continue; + } + + // Single-quoted string literal, double-quoted or backtick-quoted identifier + if (ch === "'" || ch === '"' || ch === "`") { + const quote = ch; + i++; + while (i < sql.length) { + if (sql[i] === quote) { + if (sql[i + 1] === quote) { + i += 2; + continue; + } + i++; + break; + } + i++; + } + atLineStart = false; + continue; + } + + // Bracketed identifier [...] + if (ch === "[") { + const end = sql.indexOf("]", i + 1); + if (end === -1) break; + i = end + 1; + atLineStart = false; + continue; + } + + atLineStart = false; + i++; + } + + return false; +} + +/** + * Executes a SQLite migration or rollback inside a transaction. Foreign-key + * enforcement remains active for ordinary migrations and is disabled only when + * the executed SQL contains the explicit `-- @relwave-sqlite-rebuild` directive, + * validating referential integrity via `PRAGMA foreign_key_check` before commit + * and restoring the prior `foreign_keys` pragma state afterwards. + */ +async function executeMigrationInTransaction( cfg: SQLiteConfig, migrationFilePath: string, + operationLabel: "applying" | "rolling back", + getStepSql: ( + migration: Awaited>, + ) => string, + runStep: ( + db: Database.Database, + migration: Awaited>, + ) => void, ): Promise { const db = openDB(cfg); + let prevForeignKeys = 0; + let foreignKeysModified = false; try { const { readMigrationFile } = await import("../utils/migrationFileReader"); const migration = readMigrationFile(migrationFilePath); + const stepSql = getStepSql(migration); + + if (hasSqliteRebuildDirective(stepSql)) { + prevForeignKeys = Number(db.pragma("foreign_keys", { simple: true }) ?? 0); + db.pragma("foreign_keys = OFF"); + foreignKeysModified = true; + } const transaction = db.transaction(() => { - db.exec(migration.upSQL); - db.prepare(SQLITE_INSERT_MIGRATION).run( - migration.version, - migration.name, - migration.checksum, - ); + runStep(db, migration); + const fkViolations = db.pragma("foreign_key_check") as unknown[]; + if (Array.isArray(fkViolations) && fkViolations.length > 0) { + throw new Error( + `SQLite PRAGMA foreign_key_check failed with ${fkViolations.length} violation(s).`, + ); + } }); transaction(); sqliteCache.clearForConnection(cfg); return true; } catch (error) { - console.log("[SQLite] Error applying migration:", error); + console.error(`[SQLite] Error ${operationLabel} migration:`, error); throw error; } finally { + if (foreignKeysModified) { + try { + db.pragma(`foreign_keys = ${prevForeignKeys ? "ON" : "OFF"}`); + } catch { + // Ignore pragma restore errors during connection teardown + } + } db.close(); } } +/** Apply a pending migration */ +export async function applyMigration( + cfg: SQLiteConfig, + migrationFilePath: string, +): Promise { + return executeMigrationInTransaction( + cfg, + migrationFilePath, + "applying", + (migration) => migration.upSQL, + (db, migration) => { + db.exec(migration.upSQL); + db.prepare(SQLITE_INSERT_MIGRATION).run( + migration.version, + migration.name, + migration.checksum, + ); + }, + ); +} + /** Rollback an applied migration */ export async function rollbackMigration( cfg: SQLiteConfig, version: string, migrationFilePath: string, ): Promise { - const db = openDB(cfg); - try { - const { readMigrationFile } = await import("../utils/migrationFileReader"); - const migration = readMigrationFile(migrationFilePath); - - const transaction = db.transaction(() => { + return executeMigrationInTransaction( + cfg, + migrationFilePath, + "rolling back", + (migration) => migration.downSQL, + (db, migration) => { db.exec(migration.downSQL); db.prepare(SQLITE_DELETE_MIGRATION).run(version); - }); - - transaction(); - sqliteCache.clearForConnection(cfg); - return true; - } catch (error) { - console.log("[SQLite] Error rolling back migration:", error); - throw error; - } finally { - db.close(); - } + }, + ); } /** Insert a row into a table */ diff --git a/bridge/src/handlers/aiHandlers.ts b/bridge/src/handlers/aiHandlers.ts index 219b1deb..3a69da3f 100644 --- a/bridge/src/handlers/aiHandlers.ts +++ b/bridge/src/handlers/aiHandlers.ts @@ -4,6 +4,7 @@ import { AIService } from "../services/aiService"; import { AIError } from "../ai/providers/types"; import { AIAnalyzeSchemaParams, + AIAnalyzePerformanceParams, AIExplainQueryParams, AIRecommendChartParams, AITestConnectionParams, @@ -14,12 +15,19 @@ import { hashSchemaAnalysis, hashQueryExplanation, hashChartRecommendation, + hashPerformanceAnalysis, } from "../services/aiCacheService"; import { aiHistoryStore } from "../services/aiHistoryStore"; import { buildSchemaAnalysisPrompt } from "../ai/prompts/schema-analysis"; import { buildQueryExplanationPrompt } from "../ai/prompts/query-explanation"; import { buildChartRecommendationPrompt } from "../ai/prompts/chart-recommendation"; import { parseChartRecommendation } from "../ai/prompts/chart-recommendation"; +import { + buildPerformanceCopilotPrompt, + parsePerformanceCopilotResponse, + redactExplainPlanLiterals, + redactQueryLiterals, +} from "../ai/prompts/performance-copilot"; import fsSync from "fs"; import { AI_SETTINGS_FILE, CONFIG_FOLDER, ensureDir } from "../utils/config"; @@ -204,6 +212,68 @@ export class AIHandlers { } } + /** + * Analyze a query + normalized EXPLAIN plan (+ optional index health) via AI Performance Copilot. + */ + async handleAnalyzePerformance(params: AIAnalyzePerformanceParams, id: number | string) { + try { + if (!params?.input?.query?.trim() || !params?.input?.plan) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Missing query or explain plan.", + }); + } + + const redacted = + params.settings?.defaultProvider !== "ollama" && params.input.redactLiterals !== false; + const effectiveQuery = redacted + ? redactQueryLiterals(params.input.query) + : params.input.query; + const effectivePlan = redacted + ? redactExplainPlanLiterals(params.input.plan) + : params.input.plan; + const effectiveInput = { + ...params.input, + query: effectiveQuery, + plan: effectivePlan, + }; + + const hash = hashPerformanceAnalysis(effectiveInput, params.datasourceName); + const { system, user } = buildPerformanceCopilotPrompt(effectiveInput); + const prompt = `${system}\n\n${user}`; + + const result = await getOrCall({ + feature: "performance-copilot", + hash, + settings: params.settings, + prompt, + callFn: async () => { + const provider = this.aiService.resolveProvider(params.settings); + return provider.generateText(system, user); + }, + meta: { datasource_id: params.datasourceName, table_name: params.tableName }, + skipCache: params.skipCache, + }); + + const parsed = parsePerformanceCopilotResponse(result.response); + + this.rpc.sendResponse(id, { + ok: true, + data: { + ...parsed, + redacted, + cached: result.cached, + createdAt: result.createdAt, + }, + }); + } catch (err) { + this.logger?.error({ err }, "ai.analyzePerformance failed"); + const msg = err instanceof AIError ? err.originalMessage : String(err); + const code = err instanceof AIError ? err.code : "UNKNOWN"; + this.rpc.sendError(id, { code, message: msg }); + } + } + // ── History CRUD handlers ───────────────────────────────────────────── async handleGetHistory( diff --git a/bridge/src/handlers/indexHandlers.ts b/bridge/src/handlers/indexHandlers.ts index 2a996c0c..b0150f5c 100644 --- a/bridge/src/handlers/indexHandlers.ts +++ b/bridge/src/handlers/indexHandlers.ts @@ -1,7 +1,8 @@ import { Logger } from "pino"; import { Rpc } from "../types"; -import { DatabaseService } from "../services/databaseService"; +import { DatabaseService, isOfflineError } from "../services/databaseService"; import { QueryExecutor } from "../services/queryExecutor"; +import { collectIndexHealth } from "../services/indexStatsService"; import { MongoApiError, mapMongoError } from "../connectors/mongo"; export class IndexHandlers { @@ -137,4 +138,42 @@ export class IndexHandlers { this.sendMongoError(id, e); } } + + /** Handle index.getHealth — collect index usage, unused, and duplicate diagnostics. */ + async handleGetIndexHealth(params: any, id: number | string): Promise { + try { + const { dbId, tableOrCollection } = params || {}; + if (!dbId) { + return this.rpc.sendError(id, { + code: "VALIDATION_ERROR", + message: "Missing dbId", + }); + } + + const data = await this.dbService.withConnection(dbId, (conn, _db, dbType) => + collectIndexHealth(conn, dbType, { tableOrCollection }), + ); + this.rpc.sendResponse(id, { ok: true, data }); + } catch (e: any) { + if (isOfflineError(e)) { + this.logger.warn({ e, dbId: params?.dbId }, "index.getHealth skipped: database is offline"); + return this.rpc.sendResponse(id, { + ok: true, + data: { + dialect: "unknown", + indexes: [], + unusedIndexes: [], + duplicateIndexes: [], + summary: { total: 0, unusedCount: 0, duplicateCount: 0, totalSizeBytes: 0 }, + }, + isOffline: true, + }); + } + this.logger.error({ err: e }, "index.getHealth failed"); + this.rpc.sendError(id, { + code: e?.code || "IO_ERROR", + message: e?.message || String(e), + }); + } + } } diff --git a/bridge/src/handlers/migrationHandlers.ts b/bridge/src/handlers/migrationHandlers.ts index ba04cc0a..c45595ba 100644 --- a/bridge/src/handlers/migrationHandlers.ts +++ b/bridge/src/handlers/migrationHandlers.ts @@ -1,13 +1,121 @@ -import { Rpc } from "../types"; +import { Rpc, DBType } from "../types"; import { DatabaseService } from "../services/databaseService"; import { QueryExecutor } from "../services/queryExecutor"; import { getConnector } from "../services/connectorRegistry"; import { Logger } from "pino"; +import crypto from "crypto"; import path from "path"; import fs from "fs"; -import { projectStoreInstance } from "../services/projectStore"; -import { mongoMigrationEngine } from "../services/mongoMigrationEngine"; +import { projectStoreInstance, type SchemaSnapshot } from "../services/projectStore"; +import { + mongoMigrationEngine, + resolveMongoMigrationsDir, + validateSafeFilePath, +} from "../services/mongoMigrationEngine"; import { selectDb, MongoApiError } from "../connectors/mongo"; +import { gitServiceInstance } from "../services/gitService"; +import { normalizeSchemaFile, normalizeDialect } from "../services/schemaSnapshotNormalizer"; +import { diffSchemas } from "../services/schemaDiffEngine"; +import { introspectLiveCanonicalAST } from "../services/liveSchemaIntrospector"; +import { + generateMigrationFromDiff, + generateIndexMigration, + type GeneratedMigrationResult, +} from "../services/migrationGenerator"; +import type { CanonicalSchemaAST, SchemaDiffResult } from "../types/schemaDiff"; + +function incrementMigrationVersion(version: string): string { + const m = version.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/); + if (m) { + const [, y, mo, d, h, mi, s] = m; + const next = new Date( + Date.UTC(Number(y), Number(mo) - 1, Number(d), Number(h), Number(mi), Number(s) + 1), + ); + const pad = (n: number) => String(n).padStart(2, "0"); + return `${next.getUTCFullYear()}${pad(next.getUTCMonth() + 1)}${pad(next.getUTCDate())}${pad(next.getUTCHours())}${pad(next.getUTCMinutes())}${pad(next.getUTCSeconds())}`; + } + if (/^\d+$/.test(version)) { + return (BigInt(version) + 1n).toString(); + } + return `${version}_1`; +} + +type SchemaDiffResultWithCoverage = SchemaDiffResult & { + coverageWarnings?: string[]; +}; + +function filterIncompleteViewDiffs( + diff: SchemaDiffResult, + rawSourceSchemas?: Array<{ name?: string; views?: unknown }>, + rawTargetSchemas?: Array<{ name?: string; views?: unknown }>, +): SchemaDiffResultWithCoverage { + const sourceMissingViews = new Set(); + for (const s of rawSourceSchemas || []) { + if (s && typeof s.name === "string" && !Array.isArray(s.views)) { + sourceMissingViews.add(s.name); + } + } + const targetMissingViews = new Set(); + for (const s of rawTargetSchemas || []) { + if (s && typeof s.name === "string" && !Array.isArray(s.views)) { + targetMissingViews.add(s.name); + } + } + if (sourceMissingViews.size === 0 && targetMissingViews.size === 0) { + return diff; + } + + const coverageWarnings: string[] = []; + if (sourceMissingViews.size > 0) { + coverageWarnings.push( + `Source schema snapshot omitted view definitions for schema(s): ${[...sourceMissingViews].sort().join(", ")}; unverified view additions could not be compared.`, + ); + } + if (targetMissingViews.size > 0) { + coverageWarnings.push( + `Target schema snapshot omitted view definitions for schema(s): ${[...targetMissingViews].sort().join(", ")}; unverified view drops could not be compared.`, + ); + } + + const items = diff.items.filter((item) => { + const schemaName = item.schema || ""; + if (item.type === "VIEW_ADDED" && sourceMissingViews.has(schemaName)) { + return false; + } + if (item.type === "VIEW_DROPPED" && targetMissingViews.has(schemaName)) { + return false; + } + return true; + }); + + if (items.length === diff.items.length) { + return { + ...diff, + coverageWarnings, + }; + } + + const summary = { total: items.length, safe: 0, warning: 0, destructive: 0 }; + for (const item of items) { + summary[item.severity]++; + } + return { + ...diff, + hasChanges: items.length > 0, + summary, + items, + coverageWarnings, + }; +} + +class RpcInputError extends Error { + constructor( + public readonly code: string, + message: string, + ) { + super(message); + } +} export class MigrationHandlers { constructor( @@ -19,7 +127,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, { @@ -29,8 +137,16 @@ export class MigrationHandlers { } } - private async resolveProjectRoot(dbId: string, customRoot?: string): Promise { + private async resolveProjectRoot( + dbId: string, + customRoot?: string, + projectId?: string, + ): Promise { if (customRoot) return customRoot; + // Prefer explicit projectId so shared-database projects get the right directory + if (projectId) { + return projectStoreInstance.resolveProjectDir(projectId); + } const project = await projectStoreInstance.getProjectByDatabaseId(dbId); if (project) { return projectStoreInstance.resolveProjectDir(project.id); @@ -39,9 +155,132 @@ export class MigrationHandlers { return path.join(CONFIG_FOLDER, "projects", dbId); } + private async resolveSqlMigrationsDir(dbId?: string, projectId?: string): Promise { + if (projectId) { + // When both projectId and dbId are supplied, verify they match to prevent + // executing project A's migrations against database B. + if (dbId) { + const project = await projectStoreInstance.getProject(projectId); + if (project && project.databaseId && project.databaseId !== dbId) { + throw new RpcInputError( + "PROJECT_DB_MISMATCH", + `Project '${projectId}' is linked to database '${project.databaseId}', not '${dbId}'.`, + ); + } + } + return projectStoreInstance.resolveProjectMigrationsDir(projectId); + } + if (dbId) { + return projectStoreInstance.resolveMigrationsDir(dbId); + } + throw new RpcInputError("BAD_REQUEST", "Missing dbId or projectId"); + } + + private async refreshProjectSchemaSnapshot( + projectId: string, + dbId: string, + conn: unknown, + dbType: DBType, + contextLabel: string, + ): Promise { + let schemaHash = ""; + try { + let liveSchemas: SchemaSnapshot[] = []; + if (typeof this.dbService.withConnection === "function") { + const liveAst = await introspectLiveCanonicalAST(this.dbService, this.queryExecutor, dbId); + liveSchemas = liveAst.schemas as SchemaSnapshot[]; + } else { + const dbSchema = (await this.queryExecutor.listSchemas(conn, dbType)) as any; + if ( + dbSchema?.hasIncompleteMetadata || + dbSchema?.schemas?.some((s: any) => s?.isMetadataIncomplete) + ) { + this.logger?.warn( + { dbId, projectId }, + "Skipping schema snapshot refresh due to incomplete metadata from failed getSchemaMetadataBatch", + ); + return ""; + } + liveSchemas = dbSchema?.schemas || []; + } + const computedHash = crypto + .createHash("sha256") + .update(JSON.stringify(liveSchemas)) + .digest("hex"); + await projectStoreInstance.saveSchema(projectId, liveSchemas, computedHash, dbType); + schemaHash = computedHash; + try { + this.rpc?.sendNotification?.("project.schema_changed", { + projectId, + newHash: schemaHash, + }); + } catch (notifyErr) { + this.logger?.warn( + { err: notifyErr }, + `Failed to send project.schema_changed notification after ${contextLabel}`, + ); + } + } catch (schemaErr) { + this.logger?.warn( + { err: schemaErr }, + `Failed to auto-refresh project schema after ${contextLabel}`, + ); + } + return schemaHash; + } + + private writeMigrationFileExclusive( + migrationsDir: string, + initialGenerated: GeneratedMigrationResult, + regenerateWithVersion: (version: string) => GeneratedMigrationResult, + ): { filepath: string; generated: GeneratedMigrationResult } { + if (!fs.existsSync(migrationsDir)) { + fs.mkdirSync(migrationsDir, { recursive: true }); + } + + let candidate = initialGenerated; + for (let attempt = 0; attempt < 100; attempt++) { + const existingFiles = fs.readdirSync(migrationsDir); + if (existingFiles.some((f) => f.startsWith(`${candidate.version}_`))) { + candidate = regenerateWithVersion(incrementMigrationVersion(candidate.version)); + continue; + } + + const filepath = path.join(migrationsDir, candidate.filename); + validateSafeFilePath(filepath, migrationsDir); + + try { + fs.writeFileSync(filepath, candidate.content, { encoding: "utf8", flag: "wx" }); + return { filepath, generated: candidate }; + } catch (err: any) { + if (err?.code === "EEXIST") { + candidate = regenerateWithVersion(incrementMigrationVersion(candidate.version)); + continue; + } + throw err; + } + } + + throw new RpcInputError( + "CONFLICT", + "Could not allocate a unique migration version after multiple collisions.", + ); + } + async handleListMigrations(params: any, id: number | string) { try { - const { dbId, projectRoot: customRoot } = params || {}; + const { projectId, projectRoot: customRoot } = params || {}; + let { dbId } = params || {}; + if (!dbId && projectId) { + const project = await projectStoreInstance.getProject(projectId); + if (!project?.databaseId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Project has no linked database", + }); + } + dbId = project.databaseId; + } if (!dbId) { return this.rpc.sendError(id, { code: "BAD_REQUEST", @@ -52,13 +291,13 @@ export class MigrationHandlers { const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); if (dbType === "mongodb") { const db = selectDb(conn); - const projectRoot = await this.resolveProjectRoot(dbId, customRoot); + const projectRoot = await this.resolveProjectRoot(dbId, customRoot, projectId); const data = await mongoMigrationEngine.listMigrations(db, projectRoot); return this.rpc.sendResponse(id, { ok: true, data }); } // SQL fallback - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + const migrationsDir = await this.resolveSqlMigrationsDir(dbId, projectId); const { loadLocalMigrations } = await import("../utils/baselineMigration"); const localMigrations = await loadLocalMigrations(migrationsDir); const connector = getConnector(dbType) as any; @@ -128,7 +367,7 @@ export class MigrationHandlers { async handleGenerateCreateMigration(params: any, id: number | string) { try { - const { dbId, schemaName, tableName, columns, foreignKeys = [] } = params || {}; + const { dbId, projectId, schemaName, tableName, columns, foreignKeys = [] } = params || {}; if (!dbId || !schemaName || !tableName || !columns) { return this.rpc.sendError(id, { @@ -144,7 +383,7 @@ export class MigrationHandlers { message: "Migrations are not supported for MongoDB databases", }); } - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + const migrationsDir = await this.resolveSqlMigrationsDir(dbId, projectId); // Generate migration file const { generateCreateTableMigration, writeMigrationFile } = @@ -175,7 +414,7 @@ export class MigrationHandlers { async handleGenerateAlterMigration(params: any, id: number | string) { try { - const { dbId, schemaName, tableName, operations } = params || {}; + const { dbId, projectId, schemaName, tableName, operations } = params || {}; if (!dbId || !schemaName || !tableName || !operations) { return this.rpc.sendError(id, { @@ -191,7 +430,7 @@ export class MigrationHandlers { message: "Migrations are not supported for MongoDB databases", }); } - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + const migrationsDir = await this.resolveSqlMigrationsDir(dbId, projectId); // Generate migration file const { generateAlterTableMigration, writeMigrationFile } = @@ -223,6 +462,7 @@ export class MigrationHandlers { try { const { dbId, + projectId, schemaName, tableName, mode = "RESTRICT", @@ -244,7 +484,7 @@ export class MigrationHandlers { message: "Migrations are not supported for MongoDB databases", }); } - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + const migrationsDir = await this.resolveSqlMigrationsDir(dbId, projectId); let columns = passedColumns; let foreignKeys = passedForeignKeys; @@ -282,7 +522,9 @@ export class MigrationHandlers { // 2. If table was already dropped or live inspection failed, fall back to project schema snapshot if (!columns || columns.length === 0) { try { - const project = await projectStoreInstance.getProjectByDatabaseId(dbId); + const project = projectId + ? await projectStoreInstance.getProject(projectId) + : await projectStoreInstance.getProjectByDatabaseId(dbId); if (project) { const schemaFile = await projectStoreInstance.getSchema(project.id); const schemaGroup = schemaFile?.schemas?.find((s: any) => s.name === schemaName); @@ -335,7 +577,19 @@ export class MigrationHandlers { async handleApplyMigration(params: any, id: number | string) { try { - const { dbId, version, dryRun, projectRoot: customRoot, ownerId } = params || {}; + const { projectId, version, dryRun, projectRoot: customRoot, ownerId } = params || {}; + let { dbId } = params || {}; + + if (!dbId && projectId) { + const project = await projectStoreInstance.getProject(projectId); + if (!project?.databaseId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Project has no linked database", + }); + } + dbId = project.databaseId; + } if (!dbId) { return this.rpc.sendError(id, { @@ -360,7 +614,7 @@ export class MigrationHandlers { } const db = selectDb(dbConn.conn); - const projectRoot = await this.resolveProjectRoot(dbId, customRoot); + const projectRoot = await this.resolveProjectRoot(dbId, customRoot, projectId); const data = await mongoMigrationEngine.applyMigration(db, projectRoot, version, { dryRun, readOnly, @@ -377,7 +631,7 @@ export class MigrationHandlers { } const { conn, dbType } = dbConn; - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + const migrationsDir = await this.resolveSqlMigrationsDir(dbId, projectId); // Find migration file const { listMigrationFiles } = await import("../utils/migrationFileReader"); @@ -402,29 +656,18 @@ export class MigrationHandlers { const { gitServiceInstance } = await import("../services/gitService"); const { writeMigrationLock } = await import("../services/migrationLock"); - const project = await projectStoreInstance.getProjectByDatabaseId(dbId); + const project = projectId + ? await projectStoreInstance.getProject(projectId) + : await projectStoreInstance.getProjectByDatabaseId(dbId); if (project) { - // Refresh schema from DB so project schema.json stays up-to-date with newly created tables/columns - let schemaHash = ""; - try { - const dbSchema = (await this.queryExecutor.listSchemas(conn, dbType)) as any; - const liveSchemas = dbSchema?.schemas || []; - const crypto = await import("crypto"); - schemaHash = crypto - .createHash("sha256") - .update(JSON.stringify(liveSchemas)) - .digest("hex"); - await projectStoreInstance.saveSchema(project.id, liveSchemas, schemaHash, dbType); - this.rpc?.sendNotification?.("project.schema_changed", { - projectId: project.id, - newHash: schemaHash, - }); - } catch (schemaErr) { - this.logger?.warn( - { err: schemaErr }, - "Failed to auto-refresh project schema after migration apply", - ); - } + // Refresh schema from DB so project schema.json stays up-to-date with newly created tables/columns/views + let schemaHash = await this.refreshProjectSchemaSnapshot( + project.id, + dbId, + conn, + dbType, + "migration apply", + ); // Update Migration Lock first so it gets included in the git sync commit const appliedMigrations = await connector.listAppliedMigrations(conn); @@ -435,7 +678,7 @@ export class MigrationHandlers { } const appliedVersions = appliedMigrations.map((m: any) => m.version); - await writeMigrationLock(dbId, schemaHash, appliedVersions); + await writeMigrationLock(dbId, schemaHash, appliedVersions, migrationsDir); const projectDir = await projectStoreInstance.resolveProjectDir(project.id); if (projectDir) { @@ -484,7 +727,7 @@ export class MigrationHandlers { }); const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + const migrationsDir = await this.resolveSqlMigrationsDir(dbId, projectId); const { loadLocalMigrations } = await import("../utils/baselineMigration"); const localMigrations = await loadLocalMigrations(migrationsDir); @@ -511,28 +754,17 @@ export class MigrationHandlers { try { const { projectStoreInstance } = await import("../services/projectStore"); const { writeMigrationLock } = await import("../services/migrationLock"); - const project = await projectStoreInstance.getProjectByDatabaseId(dbId); + const project = projectId + ? await projectStoreInstance.getProject(projectId) + : await projectStoreInstance.getProjectByDatabaseId(dbId); if (project) { - let schemaHash = ""; - try { - const dbSchema = (await this.queryExecutor.listSchemas(conn, dbType)) as any; - const liveSchemas = dbSchema?.schemas || []; - const crypto = await import("crypto"); - schemaHash = crypto - .createHash("sha256") - .update(JSON.stringify(liveSchemas)) - .digest("hex"); - await projectStoreInstance.saveSchema(project.id, liveSchemas, schemaHash, dbType); - this.rpc?.sendNotification?.("project.schema_changed", { - projectId: project.id, - newHash: schemaHash, - }); - } catch (schemaErr) { - this.logger?.warn( - { err: schemaErr }, - "Failed to auto-refresh project schema after applyMigrations", - ); - } + let schemaHash = await this.refreshProjectSchemaSnapshot( + project.id, + dbId, + conn, + dbType, + "applyMigrations", + ); if (!schemaHash) { const schemaFile = await projectStoreInstance.getSchema(project.id); @@ -543,6 +775,7 @@ export class MigrationHandlers { dbId, schemaHash, updatedApplied.map((m: any) => m.version), + migrationsDir, ); const projectDir = await projectStoreInstance.resolveProjectDir(project.id); @@ -590,7 +823,9 @@ export class MigrationHandlers { const { conn, dbType } = await this.dbService.getDatabaseConnection(dbId); - const project = await projectStoreInstance.getProjectByDatabaseId(dbId); + const project = projectId + ? await projectStoreInstance.getProject(projectId) + : await projectStoreInstance.getProjectByDatabaseId(dbId); if (!project) throw new Error("Project not found for database"); const snapshot = await projectStoreInstance.getSchema(project.id); if (!snapshot) throw new Error("Schema snapshot not found"); @@ -604,7 +839,7 @@ export class MigrationHandlers { // A full implementation would drop tables here. // For now, we write the SQL and apply it. - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + const migrationsDir = await this.resolveSqlMigrationsDir(dbId, projectId); const versionStr = Date.now().toString(); const baselinePath = path.join(migrationsDir, `${versionStr}_apply_snapshot.sql`); fs.writeFileSync(baselinePath, baselineSQL, "utf8"); @@ -621,6 +856,7 @@ export class MigrationHandlers { dbId, schemaHash, updatedApplied.map((m: any) => m.version), + migrationsDir, ); } catch (syncErr) { this.logger?.error({ err: syncErr }, "Lock hook failed"); @@ -635,7 +871,19 @@ export class MigrationHandlers { async handleRollbackMigration(params: any, id: number | string) { try { - const { dbId, version, force, projectRoot: customRoot, ownerId } = params || {}; + const { projectId, version, force, projectRoot: customRoot, ownerId } = params || {}; + let { dbId } = params || {}; + + if (!dbId && projectId) { + const project = await projectStoreInstance.getProject(projectId); + if (!project?.databaseId) { + return this.rpc.sendError(id, { + code: "BAD_REQUEST", + message: "Project has no linked database", + }); + } + dbId = project.databaseId; + } if (!dbId || !version) { return this.rpc.sendError(id, { @@ -660,7 +908,7 @@ export class MigrationHandlers { } const db = selectDb(dbConn.conn); - const projectRoot = await this.resolveProjectRoot(dbId, customRoot); + const projectRoot = await this.resolveProjectRoot(dbId, customRoot, projectId); const data = await mongoMigrationEngine.rollbackMigration(db, version, projectRoot, { readOnly, force, @@ -670,7 +918,7 @@ export class MigrationHandlers { } const { conn, dbType } = dbConn; - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + const migrationsDir = await this.resolveSqlMigrationsDir(dbId, projectId); // Find migration file const { listMigrationFiles } = await import("../utils/migrationFileReader"); @@ -695,28 +943,17 @@ export class MigrationHandlers { const { gitServiceInstance } = await import("../services/gitService"); const { writeMigrationLock } = await import("../services/migrationLock"); - const project = await projectStoreInstance.getProjectByDatabaseId(dbId); + const project = projectId + ? await projectStoreInstance.getProject(projectId) + : await projectStoreInstance.getProjectByDatabaseId(dbId); if (project) { - let schemaHash = ""; - try { - const dbSchema = (await this.queryExecutor.listSchemas(conn, dbType)) as any; - const liveSchemas = dbSchema?.schemas || []; - const crypto = await import("crypto"); - schemaHash = crypto - .createHash("sha256") - .update(JSON.stringify(liveSchemas)) - .digest("hex"); - await projectStoreInstance.saveSchema(project.id, liveSchemas, schemaHash, dbType); - this.rpc?.sendNotification?.("project.schema_changed", { - projectId: project.id, - newHash: schemaHash, - }); - } catch (schemaErr) { - this.logger?.warn( - { err: schemaErr }, - "Failed to auto-refresh project schema after migration rollback", - ); - } + let schemaHash = await this.refreshProjectSchemaSnapshot( + project.id, + dbId, + conn, + dbType, + "migration rollback", + ); // Update Migration Lock first so it gets included in the git sync commit const appliedMigrations = await connector.listAppliedMigrations(conn); @@ -727,7 +964,7 @@ export class MigrationHandlers { } const appliedVersions = appliedMigrations.map((m) => m.version); - await writeMigrationLock(dbId, schemaHash, appliedVersions); + await writeMigrationLock(dbId, schemaHash, appliedVersions, migrationsDir); const projectDir = await projectStoreInstance.resolveProjectDir(project.id); if (projectDir) { @@ -755,16 +992,16 @@ export class MigrationHandlers { async handleDeleteMigration(params: any, id: number | string) { try { - const { dbId, version } = params || {}; + const { dbId, projectId, version } = params || {}; - if (!dbId || !version) { + if ((!dbId && !projectId) || !version) { return this.rpc.sendError(id, { code: "BAD_REQUEST", - message: "Missing dbId or version", + message: "Missing dbId/projectId or version", }); } - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + const migrationsDir = await this.resolveSqlMigrationsDir(dbId, projectId); // Find and delete migration file const { listMigrationFiles } = await import("../utils/migrationFileReader"); @@ -790,16 +1027,16 @@ export class MigrationHandlers { async handleGetMigrationSQL(params: any, id: number | string) { try { - const { dbId, version } = params || {}; + const { dbId, projectId, version } = params || {}; - if (!dbId || !version) { + if ((!dbId && !projectId) || !version) { return this.rpc.sendError(id, { code: "BAD_REQUEST", - message: "Missing dbId or version", + message: "Missing dbId/projectId or version", }); } - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); + const migrationsDir = await this.resolveSqlMigrationsDir(dbId, projectId); // Find and read migration file const { listMigrationFiles, readMigrationFile } = @@ -829,4 +1066,431 @@ export class MigrationHandlers { this.rpc.sendError(id, { code: "IO_ERROR", message: String(e) }); } } + + /** + * Resolves source & target CanonicalSchemaASTs and computes their SchemaDiffResult + * for `live-vs-snapshot`, `live-vs-ref`, or `ref-vs-ref` modes. + */ + private async resolveSchemaDiff(params: { + projectId?: string; + mode?: string; + sourceRef?: string; + targetRef?: string; + detectRenames?: boolean; + }): Promise<{ + project: any; + sourceAST: CanonicalSchemaAST; + targetAST: CanonicalSchemaAST; + diff: SchemaDiffResult; + }> { + const { projectId, mode = "live-vs-snapshot", sourceRef, targetRef, detectRenames } = params; + const renameOpt = detectRenames !== undefined ? { detectRenames } : {}; + 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 targetAST = await introspectLiveCanonicalAST( + this.dbService, + this.queryExecutor, + project.databaseId, + ); + + const projectDialect = project.engine ? normalizeDialect(project.engine) : undefined; + const savedDialectRaw = (savedSchema as any).dialect; + + // Known valid engine dialects — a saved snapshot with one of these labels came from + // that engine and must not be treated as stale when it differs from the live dialect + // (the project was relinked to a different engine; the user needs a fresh snapshot). + const knownDialects = new Set([ + "postgres", + "postgresql", + "mysql", + "mariadb", + "sqlite", + "duckdb", + "clickhouse", + "mongodb", + ]); + const savedIsKnownEngine = + typeof savedDialectRaw === "string" && knownDialects.has(savedDialectRaw); + + // Repair only when: (a) dialect is missing/unknown, or (b) the legacy + // sqlite-label bug (snapshot saved as "sqlite" for a non-sqlite engine). + const isStaleDialect = + !savedDialectRaw || + savedDialectRaw === "unknown" || + (savedDialectRaw === "sqlite" && + targetAST.dialect !== "sqlite" && + projectDialect === targetAST.dialect); + + // If the snapshot is from a genuinely different engine (relinked DB), do not + // normalize it under the live dialect — require a fresh snapshot instead. + const isCrossEngineSnapshot = + savedIsKnownEngine && savedDialectRaw !== targetAST.dialect && !isStaleDialect; + + let sourceAST: CanonicalSchemaAST; + if (isCrossEngineSnapshot) { + // The snapshot was captured from a different engine — cannot safely compare. + // Fail early so the user knows they need a fresh snapshot. + throw new RpcInputError( + "SCHEMA_DIALECT_MISMATCH", + `Saved schema snapshot dialect '${savedDialectRaw}' does not match the live database dialect '${targetAST.dialect}'. Capture a new snapshot after relinking the database.`, + ); + } else if (isStaleDialect) { + try { + await projectStoreInstance.repairSchemaDialect( + projectId, + savedSchema.schemaHash, + savedSchema.cachedAt, + targetAST.dialect, + ); + } catch { + // Best-effort repair; normalize with live dialect below either way + } + sourceAST = normalizeSchemaFile(savedSchema, targetAST.dialect); + } else { + sourceAST = normalizeSchemaFile(savedSchema); + } + + const rawDiff = diffSchemas(sourceAST, targetAST, { + sourceLabel: "snapshot", + targetLabel: "live", + ...renameOpt, + }); + const diff = filterIncompleteViewDiffs(rawDiff, savedSchema.schemas, undefined); + 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 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}`); + } + + const parsedRef = JSON.parse(rawRefJson); + const sourceAST = await introspectLiveCanonicalAST( + this.dbService, + this.queryExecutor, + project.databaseId, + ); + const targetAST = normalizeSchemaFile(parsedRef); + const rawDiff = diffSchemas(sourceAST, targetAST, { + sourceLabel: "live", + targetLabel: targetRef, + ...renameOpt, + }); + const diff = filterIncompleteViewDiffs(rawDiff, undefined, parsedRef?.schemas); + return { project, sourceAST, targetAST, diff }; + } + + if (mode === "ref-vs-ref") { + if (!sourceRef || !targetRef) { + throw new RpcInputError("BAD_REQUEST", "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) { + 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 parsedSource = JSON.parse(rawSourceJson); + const parsedTarget = JSON.parse(rawTargetJson); + const sourceAST = normalizeSchemaFile(parsedSource); + const targetAST = normalizeSchemaFile(parsedTarget); + const rawDiff = diffSchemas(sourceAST, targetAST, { + sourceLabel: sourceRef, + targetLabel: targetRef, + ...renameOpt, + }); + const diff = filterIncompleteViewDiffs(rawDiff, parsedSource?.schemas, parsedTarget?.schemas); + 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, + detectRenames, + name, + version, + save = false, + acceptRenameIds, + confirmDestructive = false, + concurrentIndexes = false, + expectedContentHash, + } = params || {}; + + const { sourceAST, targetAST, diff } = await this.resolveSchemaDiff({ + projectId, + mode, + sourceRef, + targetRef, + detectRenames, + }); + + const generated = generateMigrationFromDiff(diff, sourceAST, targetAST, { + name, + version, + acceptRenameIds, + concurrentIndexes, + }); + + const coverageWarnings = diff.coverageWarnings ?? []; + 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: [...coverageWarnings, ...generated.warnings], + hasDestructive: generated.hasDestructive, + diff, + }, + }); + } + + if (expectedContentHash) { + const actualContentHash = crypto + .createHash("sha256") + .update(generated.content.replace(/\r\n/g, "\n")) + .digest("hex"); + if (actualContentHash !== String(expectedContentHash).trim().toLowerCase()) { + return this.rpc.sendError(id, { + code: "STALE_PREVIEW_ERROR", + message: + "Schema or generated migration content changed since preview. Re-preview before saving.", + }); + } + } + + if (generated.hasDestructive && confirmDestructive !== true) { + return this.rpc.sendError(id, { + code: "DESTRUCTIVE_CONFIRMATION_REQUIRED", + message: + "Generated migration contains destructive operations. Pass confirmDestructive: true to save.", + }); + } + + const migrationsDir = + diff.dialect === "mongodb" + ? resolveMongoMigrationsDir(await projectStoreInstance.resolveProjectDir(projectId)) + : await this.resolveSqlMigrationsDir(undefined, projectId); + + const { filepath, generated: saved } = this.writeMigrationFileExclusive( + migrationsDir, + generated, + (nextVersion) => + generateMigrationFromDiff(diff, sourceAST, targetAST, { + name, + version: nextVersion, + acceptRenameIds, + concurrentIndexes, + }), + ); + + return this.rpc.sendResponse(id, { + ok: true, + data: { + version: saved.version, + filename: saved.filename, + filepath, + format: saved.format, + content: saved.content, + upSql: saved.upSql, + downSql: saved.downSql, + manifest: saved.manifest, + warnings: [...coverageWarnings, ...saved.warnings], + hasDestructive: saved.hasDestructive, + diff, + }, + }); + } catch (e: any) { + this.sendMigrationError(id, e, "migration.generateFromDiff failed"); + } + } + + /** + * Scaffold a SQL (.sql) or MongoDB (.mql.json) migration for creating/dropping indexes, + * optionally persisting it to the project's migrations directory. + */ + async handleScaffoldIndexMigration(params: any, id: number | string) { + try { + const { + projectId, + name, + version, + save = false, + confirmDestructive = false, + concurrentIndexes = false, + createIndexes = [], + dropIndexes = [], + } = params || {}; + + if (!projectId) { + throw new RpcInputError("BAD_REQUEST", "Missing projectId"); + } + if ( + (!Array.isArray(createIndexes) || createIndexes.length === 0) && + (!Array.isArray(dropIndexes) || dropIndexes.length === 0) + ) { + throw new RpcInputError( + "BAD_REQUEST", + "At least one createIndexes or dropIndexes entry is required.", + ); + } + + const project = await projectStoreInstance.getProject(projectId); + if (!project) { + throw new RpcInputError("NOT_FOUND", "Project not found"); + } + + let rawEngine = project.engine; + if (!rawEngine && project.databaseId) { + const { dbType } = await this.dbService.getDatabaseConnection(project.databaseId); + rawEngine = dbType; + } + if (!rawEngine) { + throw new RpcInputError( + "BAD_REQUEST", + "Project has no engine or databaseId to determine dialect", + ); + } + + const dialect = normalizeDialect(rawEngine); + const generated = generateIndexMigration({ + dialect, + name, + version, + concurrentIndexes, + createIndexes, + dropIndexes, + }); + + if (!save) { + return this.rpc.sendResponse(id, { + ok: true, + data: { + version: generated.version, + filename: generated.filename, + format: generated.format, + content: generated.content, + upSql: generated.upSql, + downSql: generated.downSql, + manifest: generated.manifest, + warnings: generated.warnings, + hasDestructive: generated.hasDestructive, + }, + }); + } + + if (generated.hasDestructive && confirmDestructive !== true) { + return this.rpc.sendError(id, { + code: "DESTRUCTIVE_CONFIRMATION_REQUIRED", + message: + "Generated index migration contains destructive operations. Pass confirmDestructive: true to save.", + }); + } + + const migrationsDir = + dialect === "mongodb" + ? resolveMongoMigrationsDir(await projectStoreInstance.resolveProjectDir(projectId)) + : await this.resolveSqlMigrationsDir(undefined, projectId); + + const { filepath, generated: saved } = this.writeMigrationFileExclusive( + migrationsDir, + generated, + (nextVersion) => + generateIndexMigration({ + dialect, + name, + version: nextVersion, + concurrentIndexes, + createIndexes, + dropIndexes, + }), + ); + + return this.rpc.sendResponse(id, { + ok: true, + data: { + version: saved.version, + filename: saved.filename, + filepath, + format: saved.format, + content: saved.content, + upSql: saved.upSql, + downSql: saved.downSql, + manifest: saved.manifest, + warnings: saved.warnings, + hasDestructive: saved.hasDestructive, + }, + }); + } catch (e: any) { + this.sendMigrationError(id, e, "migration.scaffoldIndexMigration failed"); + } + } } diff --git a/bridge/src/handlers/projectHandlers.ts b/bridge/src/handlers/projectHandlers.ts index 91a7ce80..1dc537f2 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"; /** @@ -198,6 +201,16 @@ export class ProjectHandlers { // Get DB connection const { conn, dbType } = await this.dbService.getDatabaseConnection(project.databaseId); const dbSchema = (await this.queryExecutor.listSchemas(conn, dbType)) as any; + if ( + dbSchema?.hasIncompleteMetadata || + dbSchema?.schemas?.some((s: any) => s?.isMetadataIncomplete) + ) { + return this.rpc.sendError(id, { + code: "INCOMPLETE_METADATA_ERROR", + message: + "Schema metadata collection failed for one or more schemas. Retaining existing saved schema baseline.", + }); + } const liveSchemas = dbSchema.schemas; // Generate schema hash from live schemas @@ -579,8 +592,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/handlers/queryHandlers.ts b/bridge/src/handlers/queryHandlers.ts index 931849b1..ede852ea 100644 --- a/bridge/src/handlers/queryHandlers.ts +++ b/bridge/src/handlers/queryHandlers.ts @@ -1,6 +1,7 @@ import { Rpc } from "../types"; -import { DatabaseService } from "../services/databaseService"; +import { DatabaseService, isOfflineError } from "../services/databaseService"; import { QueryExecutor } from "../services/queryExecutor"; +import { collectExplainPlan } from "../services/explainCollector"; import { SessionManager } from "../sessionManager"; import { getConnector } from "../services/connectorRegistry"; import { @@ -1332,4 +1333,41 @@ export class QueryHandlers { this.sessions?.remove?.(sid); } } + + /** Handle query.explainPlan — collect normalized EXPLAIN plan across SQL & MongoDB dialects. */ + async handleExplainPlan(params: any, id: number | string) { + try { + const { dbId, sql, collection, filter, pipeline, analyze } = params || {}; + if (!dbId) { + return this.rpc.sendError(id, { + code: "VALIDATION_ERROR", + message: "Missing dbId", + }); + } + + const data = await this.dbService.withConnection(dbId, (conn, _db, dbType) => + collectExplainPlan(conn, dbType, { sql, collection, filter, pipeline, analyze }), + ); + this.rpc.sendResponse(id, { ok: true, data }); + } catch (e: any) { + if (e?.code === "VALIDATION_ERROR") { + return this.rpc.sendError(id, { + code: "VALIDATION_ERROR", + message: e.message || "Invalid explain plan request", + }); + } + if (isOfflineError(e)) { + this.logger?.warn( + { e, dbId: params?.dbId }, + "query.explainPlan skipped: database is offline", + ); + return this.rpc.sendResponse(id, { ok: true, data: null, isOffline: true }); + } + this.logger?.error({ e }, "query.explainPlan failed"); + this.rpc.sendError(id, { + code: e?.code || "IO_ERROR", + message: e?.message || String(e), + }); + } + } } diff --git a/bridge/src/jsonRpcHandler.ts b/bridge/src/jsonRpcHandler.ts index 468de2dc..81860bff 100644 --- a/bridge/src/jsonRpcHandler.ts +++ b/bridge/src/jsonRpcHandler.ts @@ -95,6 +95,7 @@ export function registerDbHandlers(rpc: Rpc, logger: Logger, sessions: SessionMa // M5: MongoDB MQL Workspace & Read-Only Engine (docs/MONGODB_M5_SPEC.md §5) rpcRegister(rpc, "query.executeMql", (p, id) => queryHandlers.handleExecuteMql(p, id)); rpcRegister(rpc, "query.explainMql", (p, id) => queryHandlers.handleExplainMql(p, id)); + rpcRegister(rpc, "query.explainPlan", (p, id) => queryHandlers.handleExplainPlan(p, id)); // ========================================== // DATABASE CRUD HANDLERS @@ -124,6 +125,7 @@ export function registerDbHandlers(rpc: Rpc, logger: Logger, sessions: SessionMa rpcRegister(rpc, "index.create", (p, id) => indexHandlers.handleCreateIndex(p, id)); rpcRegister(rpc, "index.drop", (p, id) => indexHandlers.handleDropIndex(p, id)); rpcRegister(rpc, "index.getStats", (p, id) => indexHandlers.handleGetIndexStats(p, id)); + rpcRegister(rpc, "index.getHealth", (p, id) => indexHandlers.handleGetIndexHealth(p, id)); rpcRegister(rpc, "index.hide", (p, id) => indexHandlers.handleHideIndex(p, id)); // ========================================== @@ -198,6 +200,13 @@ 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), + ); + rpcRegister(rpc, "migration.scaffoldIndexMigration", (p, id) => + migrationHandlers.handleScaffoldIndexMigration(p, id), + ); // ========================================== // STATISTICS HANDLERS @@ -334,6 +343,7 @@ export function registerDbHandlers(rpc: Rpc, logger: Logger, sessions: SessionMa rpcRegister(rpc, "ai.analyzeSchema", (p, id) => aiHandlers.handleAnalyzeSchema(p, id)); rpcRegister(rpc, "ai.explainQuery", (p, id) => aiHandlers.handleExplainQuery(p, id)); rpcRegister(rpc, "ai.recommendChart", (p, id) => aiHandlers.handleRecommendChart(p, id)); + rpcRegister(rpc, "ai.analyzePerformance", (p, id) => aiHandlers.handleAnalyzePerformance(p, id)); rpcRegister(rpc, "ai.naturalLanguageQuery", (p, id) => aiHandlers.handleNaturalLanguageQuery(p, id), ); diff --git a/bridge/src/services/aiCacheService.ts b/bridge/src/services/aiCacheService.ts index 29d82f3c..0c5d6033 100644 --- a/bridge/src/services/aiCacheService.ts +++ b/bridge/src/services/aiCacheService.ts @@ -14,13 +14,18 @@ import { SchemaAnalysisInput, QueryExplanationInput, ChartRecommendationInput, + AIPerformanceAnalysisInput, SchemaColumn, } from "../types/ai"; // ── Types ───────────────────────────────────────────────────────────────── export type AIFeature = - "schema-analysis" | "query-explanation" | "chart-recommendation" | "nl_to_sql"; + | "schema-analysis" + | "query-explanation" + | "chart-recommendation" + | "nl_to_sql" + | "performance-copilot"; export interface CachedResult { response: string; @@ -122,6 +127,35 @@ export function hashChartRecommendation( return generateContentHash("chart-recommendation", normalized); } +/** Hash for performance copilot analysis: uses datasource + dialect + query + plan + indexHealth. */ +export function hashPerformanceAnalysis( + input: AIPerformanceAnalysisInput, + datasourceName?: string, +): string { + const normalized = { + datasource: datasourceName ?? null, + dialect: input.dialect, + query: (input.query ?? "").trim(), + plan: { + totalCost: input.plan?.totalCost ?? null, + rowsExamined: input.plan?.rowsExamined ?? null, + rowsReturned: input.plan?.rowsReturned ?? null, + executionTimeMs: input.plan?.executionTimeMs ?? null, + planningTimeMs: input.plan?.planningTimeMs ?? null, + bottlenecks: input.plan?.bottlenecks ?? [], + planTree: input.plan?.planTree ?? null, + }, + indexHealth: input.indexHealth + ? { + summary: input.indexHealth.summary, + unusedIndexes: input.indexHealth.unusedIndexes, + duplicateIndexes: input.indexHealth.duplicateIndexes, + } + : null, + }; + return generateContentHash("performance-copilot", normalized); +} + // ── Cache-first orchestration ───────────────────────────────────────────── /** diff --git a/bridge/src/services/explainCollector.ts b/bridge/src/services/explainCollector.ts new file mode 100644 index 00000000..ed2bbfcc --- /dev/null +++ b/bridge/src/services/explainCollector.ts @@ -0,0 +1,1275 @@ +import mysql from "mysql2/promise"; +import { DBType } from "../types"; +import { ExplainBottleneck, ExplainPlanNode, NormalizedExplainPlan } from "../types/performance"; +import { getPool as getPgPool } from "../connectors/postgres"; +import { createPoolConfig as createMysqlPoolConfig } from "../connectors/mysql"; +import { createPoolConfig as createMariaPoolConfig } from "../connectors/mariadb"; +import { openSQLiteDB } from "../connectors/sqlite"; +import { runQuery as runDuckDBQuery } from "../connectors/duckdb"; +import { getClient as getClickHouseClient } from "../connectors/clickhouse"; +import { explainMql } from "../connectors/mongo"; +import { PGConfig } from "../types/postgres"; +import { MySQLConfig } from "../types/mysql"; +import { SQLiteConfig } from "../types/sqlite"; +import { DuckDBConfig } from "../types/duckdb"; +import { ClickHouseConfig } from "../types/clickhouse"; +import { MongoConfig } from "../types/mongo"; + +export interface CollectExplainParams { + sql?: string; + collection?: string; + filter?: unknown; + pipeline?: unknown[]; + analyze?: boolean; +} + +const MUTATING_KEYWORDS = new Set([ + "INSERT", + "UPDATE", + "DELETE", + "DROP", + "ALTER", + "TRUNCATE", + "CREATE", + "REPLACE", + "MERGE", + "GRANT", + "REVOKE", +]); + +function createValidationError(message: string): Error & { code: string } { + const err = new Error(message) as Error & { code: string }; + err.code = "VALIDATION_ERROR"; + return err; +} + +/** + * Strip comments and quoted literals from SQL, returning unquoted tokens + * and whether any multi-statement `;` chain is present. + */ +function scanSqlTokens(sql: string): { + strippedSql: string; + hasMultiStatement: boolean; +} { + let i = 0; + const len = sql.length; + const out: string[] = []; + let sawSemicolon = false; + let hasMultiStatement = false; + + while (i < len) { + const ch = sql[i]; + const next = sql[i + 1]; + + // Line comment: -- ... + if (ch === "-" && next === "-") { + i += 2; + while (i < len && sql[i] !== "\n") i++; + out.push(" "); + continue; + } + + // Block comment: /* ... */ + if (ch === "/" && next === "*") { + i += 2; + while (i < len && !(sql[i] === "*" && sql[i + 1] === "/")) i++; + i += 2; + out.push(" "); + continue; + } + + // Single-quoted string literal + if (ch === "'") { + if (sawSemicolon) hasMultiStatement = true; + i++; + while (i < len) { + if (sql[i] === "\\" && i + 1 < len) { + i += 2; + } else if (sql[i] === "'" && sql[i + 1] === "'") { + i += 2; + } else if (sql[i] === "'") { + i++; + break; + } else { + i++; + } + } + out.push(" '' "); + continue; + } + + // PostgreSQL dollar-quoted string literal: $$...$$ or $tag$...$tag$ + if ( + ch === "$" && + (i === 0 || !/[\p{L}\p{N}\p{M}_$]$/u.test(sql.slice(Math.max(0, i - 2), i))) + ) { + const dollarMatch = sql.slice(i).match(/^\$(?:[\p{L}_][\p{L}\p{N}\p{M}_]*)?\$/u); + if (dollarMatch) { + const delim = dollarMatch[0]; + const closeIdx = sql.indexOf(delim, i + delim.length); + if (closeIdx !== -1) { + if (sawSemicolon) hasMultiStatement = true; + out.push(" '' "); + i = closeIdx + delim.length; + continue; + } + } + } + + // Double-quoted or backtick-quoted identifier + if (ch === '"' || ch === "`") { + if (sawSemicolon) hasMultiStatement = true; + const quote = ch; + i++; + while (i < len) { + if (sql[i] === quote && sql[i + 1] === quote) { + i += 2; + } else if (sql[i] === quote) { + i++; + break; + } else { + i++; + } + } + out.push(" IDENT "); + continue; + } + + if (ch === ";") { + sawSemicolon = true; + i++; + continue; + } + + if (!/\s/.test(ch) && sawSemicolon) { + hasMultiStatement = true; + } + + out.push(ch); + i++; + } + + return { strippedSql: out.join("").trim(), hasMultiStatement }; +} + +/** + * Returns true only if `sql` is a single read-only SELECT / WITH / VALUES statement + * with no mutating DML/DDL keywords or multi-statement `;` chains. + */ +export function isReadOnlySelectSql(sql: string): boolean { + if (typeof sql !== "string" || !sql.trim()) { + return false; + } + + const { strippedSql, hasMultiStatement } = scanSqlTokens(sql); + if (!strippedSql || hasMultiStatement) { + return false; + } + + const firstMatch = strippedSql.match(/^([A-Za-z_]+)/); + if (!firstMatch) { + return false; + } + + const firstKeyword = firstMatch[1].toUpperCase(); + if (firstKeyword !== "SELECT" && firstKeyword !== "WITH" && firstKeyword !== "VALUES") { + return false; + } + + // Block writable CTEs or embedded mutating statements outside quotes/comments + const upperSql = strippedSql.toUpperCase(); + const wordRegex = /\b[A-Z_]+\b/g; + let match: RegExpExecArray | null; + while ((match = wordRegex.exec(upperSql)) !== null) { + const w = match[0]; + if (!MUTATING_KEYWORDS.has(w)) continue; + if (w === "REPLACE") { + // Allow read-only REPLACE(...) string function calls + const after = upperSql.slice(match.index + w.length).trimStart(); + if (after.startsWith("(")) { + continue; + } + } + return false; + } + + return true; +} + +/** + * Normalize a PostgreSQL EXPLAIN (FORMAT JSON) payload into a NormalizedExplainPlan. + */ +export function normalizePostgresExplain( + rawPlan: unknown, + query: string, + analyzed: boolean, +): NormalizedExplainPlan { + let rootObj: any = rawPlan; + if (Array.isArray(rawPlan)) { + rootObj = rawPlan[0]; + } + if (rootObj && typeof rootObj === "object" && "QUERY PLAN" in rootObj) { + const qp = rootObj["QUERY PLAN"]; + rootObj = Array.isArray(qp) ? qp[0] : qp; + } + + const bottlenecks: ExplainBottleneck[] = []; + let rowsExamined = 0; + + const mapNode = (node: any): ExplainPlanNode => { + if (!node || typeof node !== "object") { + return { nodeType: "Unknown", children: [] }; + } + + const nodeType = String(node["Node Type"] || "Unknown"); + const relation = node["Relation Name"] ? String(node["Relation Name"]) : undefined; + const indexName = node["Index Name"] ? String(node["Index Name"]) : undefined; + const cost = typeof node["Total Cost"] === "number" ? node["Total Cost"] : undefined; + const rows = typeof node["Plan Rows"] === "number" ? node["Plan Rows"] : undefined; + const actualRows = typeof node["Actual Rows"] === "number" ? node["Actual Rows"] : undefined; + const actualTimeMs = + typeof node["Actual Total Time"] === "number" ? node["Actual Total Time"] : undefined; + const filter = + node["Filter"] || node["Index Cond"] || node["Hash Cond"] || node["Join Cond"] || undefined; + const removedByFilter = + typeof node["Rows Removed by Filter"] === "number" ? node["Rows Removed by Filter"] : 0; + const actualLoops = typeof node["Actual Loops"] === "number" ? node["Actual Loops"] : 1; + + if (nodeType === "Seq Scan") { + const estRows = actualRows ?? rows ?? 0; + bottlenecks.push({ + type: "FULL_SCAN", + target: relation, + details: `Sequential scan on ${relation || "table"} (${estRows} rows)`, + severity: estRows > 1000 ? "critical" : "warning", + }); + } + + if (nodeType === "Sort") { + const sortMethod = String(node["Sort Method"] || ""); + const isDisk = + sortMethod.toLowerCase().includes("external") || + String(node["Sort Space Type"] || "").toLowerCase() === "disk"; + if (isDisk || (actualRows ?? rows ?? 0) > 1000) { + bottlenecks.push({ + type: "FILESORT", + target: relation, + details: isDisk + ? `Disk-based sort (${sortMethod})` + : `In-memory sort on ${actualRows ?? rows ?? 0} rows`, + severity: isDisk ? "critical" : "warning", + }); + } + } + + if ( + nodeType === "Materialize" || + (nodeType === "Hash" && typeof node["Hash Batches"] === "number" && node["Hash Batches"] > 1) + ) { + bottlenecks.push({ + type: "TEMP_TABLE", + target: relation, + details: + nodeType === "Materialize" + ? "Materialize node buffers intermediate rows" + : `Hash spilled to ${node["Hash Batches"]} batches`, + severity: "warning", + }); + } + + if (cost !== undefined && cost > 10000) { + bottlenecks.push({ + type: "HIGH_COST", + target: relation || nodeType, + details: `${nodeType} estimated cost ${cost.toFixed(1)}`, + severity: cost > 100000 ? "critical" : "warning", + }); + } + + if (analyzed && removedByFilter > 100) { + const returned = actualRows ?? 0; + if (returned === 0 || removedByFilter > returned * 10) { + bottlenecks.push({ + type: "LOW_SELECTIVITY", + target: relation || nodeType, + details: `Filter removed ${removedByFilter} rows while returning ${returned}`, + severity: removedByFilter > 10000 ? "critical" : "warning", + }); + } + } + + const childPlans = Array.isArray(node["Plans"]) ? node["Plans"].map(mapNode) : []; + if (childPlans.length === 0) { + if (actualRows !== undefined) { + rowsExamined += (actualRows + removedByFilter) * actualLoops; + } else { + rowsExamined += rows ?? 0; + } + } + + return { + nodeType, + relation, + indexName, + cost, + rows, + actualRows, + actualTimeMs, + filter: filter ? String(filter) : undefined, + children: childPlans, + }; + }; + + const planTree = mapNode(rootObj?.Plan ?? rootObj); + + return { + dialect: DBType.POSTGRES, + query, + analyzed, + executionTimeMs: + typeof rootObj?.["Execution Time"] === "number" ? rootObj["Execution Time"] : undefined, + planningTimeMs: + typeof rootObj?.["Planning Time"] === "number" ? rootObj["Planning Time"] : undefined, + totalCost: planTree.cost, + rowsExamined: rowsExamined || undefined, + rowsReturned: planTree.actualRows ?? planTree.rows, + bottlenecks, + planTree, + rawPlan, + }; +} + +/** + * Normalize a MySQL / MariaDB EXPLAIN (FORMAT=JSON or EXPLAIN ANALYZE text) payload. + */ +export function normalizeMysqlExplain( + rawPlan: unknown, + query: string, + analyzed: boolean, + dialect: string = DBType.MYSQL, +): NormalizedExplainPlan { + let parsed: any = rawPlan; + + if (Array.isArray(rawPlan) && rawPlan.length > 0) { + const first = rawPlan[0]; + if (first && typeof first === "object" && "EXPLAIN" in first) { + parsed = first.EXPLAIN; + } + } else if (rawPlan && typeof rawPlan === "object" && "EXPLAIN" in (rawPlan as any)) { + parsed = (rawPlan as any).EXPLAIN; + } + + if (typeof parsed === "string") { + const trimmed = parsed.trim(); + if (trimmed.startsWith("{") || trimmed.startsWith("[")) { + try { + parsed = JSON.parse(trimmed); + } catch { + // Fall through to text parser + } + } + } + + const bottlenecks: ExplainBottleneck[] = []; + + // Handle MySQL 8 EXPLAIN ANALYZE text output + if (typeof parsed === "string") { + const planTree = parseIndentedTextPlan(parsed, bottlenecks); + return { + dialect, + query, + analyzed, + executionTimeMs: planTree.actualTimeMs, + totalCost: planTree.cost, + rowsReturned: planTree.actualRows ?? planTree.rows, + bottlenecks, + planTree, + rawPlan, + }; + } + + const qb = parsed?.query_block ?? parsed; + const totalCost = + qb?.cost_info?.query_cost !== undefined ? Number(qb.cost_info.query_cost) : undefined; + const executionTimeMs = typeof qb?.r_total_time_ms === "number" ? qb.r_total_time_ms : undefined; + + let rowsExamined = 0; + let hasRowsExamined = false; + + const mapTableNode = (tbl: any): ExplainPlanNode => { + const accessType = String(tbl?.access_type || "UNKNOWN"); + const tableName = tbl?.table_name ? String(tbl.table_name) : undefined; + const key = tbl?.key ? String(tbl.key) : undefined; + const rows = + typeof tbl?.rows_examined_per_scan === "number" + ? tbl.rows_examined_per_scan + : typeof tbl?.rows_produced_per_join === "number" + ? tbl.rows_produced_per_join + : typeof tbl?.rows === "number" + ? tbl.rows + : undefined; + const rLoops = typeof tbl?.r_loops === "number" ? tbl.r_loops : 1; + const rowsRead = + tbl?.r_loops === 0 ? 0 : typeof tbl?.r_rows === "number" ? tbl.r_rows * rLoops : undefined; + const rFiltered = typeof tbl?.r_filtered === "number" ? tbl.r_filtered : undefined; + const actualRows = + rowsRead !== undefined + ? rFiltered !== undefined + ? (rowsRead * rFiltered) / 100 + : rowsRead + : undefined; + const actualTimeMs = typeof tbl?.r_total_time_ms === "number" ? tbl.r_total_time_ms : undefined; + const readCost = + tbl?.cost_info?.read_cost !== undefined ? Number(tbl.cost_info.read_cost) : undefined; + const evalCost = tbl?.cost_info?.eval_cost !== undefined ? Number(tbl.cost_info.eval_cost) : 0; + const cost = readCost !== undefined ? readCost + evalCost : undefined; + const filter = tbl?.attached_condition ? String(tbl.attached_condition) : undefined; + + let nodeType = `Scan (${accessType})`; + if (accessType === "ALL") { + nodeType = "Full Table Scan (ALL)"; + bottlenecks.push({ + type: "FULL_SCAN", + target: tableName, + details: `Full table scan on ${tableName || "table"} (~${rows ?? 0} rows)`, + severity: (rows ?? 0) > 1000 ? "critical" : "warning", + }); + } else if (accessType === "index") { + nodeType = "Full Index Scan (index)"; + } else if (key) { + nodeType = `Index Scan (${accessType})`; + } + + if (tbl?.using_filesort) { + bottlenecks.push({ + type: "FILESORT", + target: tableName, + details: `Using filesort on ${tableName || "table"}`, + severity: "warning", + }); + } + if (tbl?.using_temporary_table) { + bottlenecks.push({ + type: "TEMP_TABLE", + target: tableName, + details: `Using temporary table for ${tableName || "table"}`, + severity: "warning", + }); + } + + const nodeRowsExamined = rowsRead ?? rows; + if (nodeRowsExamined !== undefined) { + rowsExamined += nodeRowsExamined; + hasRowsExamined = true; + } + + return { + nodeType, + relation: tableName, + indexName: key, + cost, + rows, + actualRows, + actualTimeMs, + filter, + children: [], + }; + }; + + const mapBlock = (block: any): ExplainPlanNode => { + if (!block || typeof block !== "object") { + return { nodeType: "Query Block", children: [] }; + } + + const children: ExplainPlanNode[] = []; + + if (block.table) { + children.push(mapTableNode(block.table)); + } + + if (Array.isArray(block.nested_loop)) { + for (const item of block.nested_loop) { + if (item?.table) { + children.push(mapTableNode(item.table)); + } else { + children.push(mapBlock(item)); + } + } + } + + if (block.ordering_operation) { + if (block.ordering_operation.using_filesort) { + bottlenecks.push({ + type: "FILESORT", + details: "Ordering operation requires filesort", + severity: "warning", + }); + } + if (block.ordering_operation.using_temporary_table) { + bottlenecks.push({ + type: "TEMP_TABLE", + details: "Ordering operation uses temporary table", + severity: "warning", + }); + } + const orderedChild = mapBlock(block.ordering_operation); + children.push({ + nodeType: "Sort (ordering_operation)", + ...(orderedChild.actualRows !== undefined ? { actualRows: orderedChild.actualRows } : {}), + children: [orderedChild], + }); + } + + if (block.grouping_operation) { + if (block.grouping_operation.using_temporary_table) { + bottlenecks.push({ + type: "TEMP_TABLE", + details: "Grouping operation uses temporary table", + severity: "warning", + }); + } + if (block.grouping_operation.using_filesort) { + bottlenecks.push({ + type: "FILESORT", + details: "Grouping operation requires filesort", + severity: "warning", + }); + } + children.push({ + nodeType: "Group (grouping_operation)", + children: [mapBlock(block.grouping_operation)], + }); + } + + if (block.materialized_from_subquery) { + bottlenecks.push({ + type: "TEMP_TABLE", + details: "Materialized subquery creates temporary table", + severity: "warning", + }); + children.push({ + nodeType: "Materialized Subquery", + children: [ + mapBlock( + block.materialized_from_subquery.query_block ?? block.materialized_from_subquery, + ), + ], + }); + } + + if (children.length === 1) { + return children[0]; + } + + const directActualRows = typeof block.r_rows === "number" ? block.r_rows : undefined; + + return { + nodeType: "Query Block", + cost: totalCost, + ...(directActualRows !== undefined ? { actualRows: directActualRows } : {}), + children, + }; + }; + + const planTree = mapBlock(qb); + if (totalCost !== undefined && !Number.isNaN(totalCost) && totalCost > 10000) { + bottlenecks.push({ + type: "HIGH_COST", + details: `Query cost estimated at ${totalCost.toFixed(1)}`, + severity: totalCost > 100000 ? "critical" : "warning", + }); + } + + return { + dialect, + query, + analyzed, + executionTimeMs, + totalCost: Number.isNaN(totalCost) ? undefined : totalCost, + rowsExamined: hasRowsExamined ? rowsExamined : undefined, + rowsReturned: planTree.actualRows ?? planTree.rows, + bottlenecks, + planTree, + rawPlan, + }; +} + +/** + * Normalize SQLite EXPLAIN QUERY PLAN rows into a NormalizedExplainPlan. + */ +export function normalizeSqliteExplain( + rows: Array<{ id?: number; parent?: number; notused?: number; detail?: string }>, + query: string, +): NormalizedExplainPlan { + const bottlenecks: ExplainBottleneck[] = []; + const nodeMap = new Map(); + const roots: ExplainPlanNode[] = []; + + for (const row of rows) { + const id = typeof row.id === "number" ? row.id : roots.length + 1; + const detail = String(row.detail || "").trim(); + + let nodeType = detail || "STEP"; + let relation: string | undefined; + let indexName: string | undefined; + + const scanMatch = detail.match(/^SCAN\s+(?:TABLE\s+)?([^\s(]+)/i); + const searchIndexMatch = detail.match( + /^SEARCH\s+(?:TABLE\s+)?([^\s]+)\s+USING\s+(?:COVERING\s+)?INDEX\s+([^\s(]+)/i, + ); + const searchPkMatch = detail.match( + /^SEARCH\s+(?:TABLE\s+)?([^\s]+)\s+USING\s+INTEGER\s+PRIMARY\s+KEY/i, + ); + + if (scanMatch) { + nodeType = "SCAN"; + relation = scanMatch[1]; + bottlenecks.push({ + type: "FULL_SCAN", + target: relation, + details: detail, + severity: "warning", + }); + } else if (searchIndexMatch) { + nodeType = detail.toUpperCase().includes("COVERING INDEX") + ? "SEARCH USING COVERING INDEX" + : "SEARCH USING INDEX"; + relation = searchIndexMatch[1]; + indexName = searchIndexMatch[2]; + } else if (searchPkMatch) { + nodeType = "SEARCH USING PRIMARY KEY"; + relation = searchPkMatch[1]; + } else if (/TEMP B-TREE FOR ORDER BY/i.test(detail)) { + nodeType = "TEMP B-TREE (ORDER BY)"; + bottlenecks.push({ + type: "FILESORT", + details: detail, + severity: "warning", + }); + } else if (/TEMP B-TREE/i.test(detail)) { + nodeType = "TEMP B-TREE"; + bottlenecks.push({ + type: "TEMP_TABLE", + details: detail, + severity: "warning", + }); + } + + const node: ExplainPlanNode = { + nodeType, + relation, + indexName, + filter: detail, + children: [], + }; + nodeMap.set(id, node); + + const parentId = typeof row.parent === "number" ? row.parent : 0; + const parentNode = parentId > 0 ? nodeMap.get(parentId) : undefined; + if (parentNode) { + parentNode.children.push(node); + } else { + roots.push(node); + } + } + + const planTree: ExplainPlanNode = + roots.length === 1 + ? roots[0] + : { + nodeType: "SQLite Query Plan", + children: roots, + }; + + return { + dialect: DBType.SQLITE, + query, + analyzed: false, + bottlenecks, + planTree, + rawPlan: rows, + }; +} + +/** + * Normalize a MongoDB explain() result into a NormalizedExplainPlan. + */ +export function normalizeMongoExplain( + rawExplain: any, + query: string, + _analyzed: boolean, +): NormalizedExplainPlan { + const bottlenecks: ExplainBottleneck[] = []; + const execStats = rawExplain?.executionStats; + const queryPlanner = rawExplain?.queryPlanner; + const pipelineStages: any[] | undefined = Array.isArray(rawExplain?.stages) + ? rawExplain.stages + : Array.isArray(queryPlanner?.winningPlan?.stages) + ? queryPlanner.winningPlan.stages + : undefined; + const cursorStage = pipelineStages?.find((s: any) => s && typeof s === "object" && s.$cursor); + const cursorExecStats = cursorStage?.$cursor?.executionStats; + const effectiveExecStats = execStats ?? cursorExecStats; + + const mapStage = (stageObj: any): ExplainPlanNode => { + if (!stageObj || typeof stageObj !== "object") { + return { nodeType: "Unknown", children: [] }; + } + + // Handle aggregation pipeline $cursor wrapper + if (stageObj.$cursor) { + const cursorExec = stageObj.$cursor.executionStats?.executionStages; + const cursorPlan = stageObj.$cursor.queryPlanner?.winningPlan; + return mapStage(cursorExec || cursorPlan); + } + + const stageName = String(stageObj.stage || stageObj.type || "STAGE"); + const indexName = stageObj.indexName ? String(stageObj.indexName) : undefined; + const nReturned = typeof stageObj.nReturned === "number" ? stageObj.nReturned : undefined; + const actualTimeMs = + typeof stageObj.executionTimeMillisEstimate === "number" + ? stageObj.executionTimeMillisEstimate + : undefined; + const filter = stageObj.filter ? JSON.stringify(stageObj.filter) : undefined; + + if (stageName === "COLLSCAN") { + const docs = + typeof effectiveExecStats?.totalDocsExamined === "number" + ? effectiveExecStats.totalDocsExamined + : (nReturned ?? 0); + bottlenecks.push({ + type: "FULL_SCAN", + details: `Collection scan (COLLSCAN) examined ${docs} documents`, + severity: docs > 1000 ? "critical" : "warning", + }); + } + + if (stageName === "SORT") { + bottlenecks.push({ + type: "FILESORT", + details: "In-memory SORT stage (no supporting index for sort order)", + severity: "warning", + }); + } + + const children: ExplainPlanNode[] = []; + if (stageObj.inputStage) { + children.push(mapStage(stageObj.inputStage)); + } + if (Array.isArray(stageObj.inputStages)) { + for (const s of stageObj.inputStages) { + children.push(mapStage(s)); + } + } + if (Array.isArray(stageObj.shards)) { + for (const shard of stageObj.shards) { + children.push(mapStage(shard.executionStages || shard.winningPlan)); + } + } + + return { + nodeType: stageName, + indexName, + rows: nReturned, + actualRows: nReturned, + actualTimeMs, + filter, + children, + }; + }; + + let planTree: ExplainPlanNode; + if (execStats?.executionStages && Object.keys(execStats.executionStages).length > 0) { + planTree = mapStage(execStats.executionStages); + } else if (pipelineStages) { + const stageNodes = pipelineStages.map((s: any) => { + if (s.$cursor) return mapStage(s); + const opName = Object.keys(s)[0] || "STAGE"; + return { + nodeType: opName, + actualRows: typeof s?.nReturned === "number" ? s.nReturned : undefined, + filter: JSON.stringify(s[opName]), + children: [], + }; + }); + planTree = + stageNodes.length === 1 + ? stageNodes[0] + : { nodeType: "Aggregation Pipeline", children: stageNodes }; + } else { + planTree = mapStage(queryPlanner?.winningPlan || rawExplain); + } + + const rowsExamined = + typeof effectiveExecStats?.totalDocsExamined === "number" + ? effectiveExecStats.totalDocsExamined + : undefined; + let rowsReturned: number | undefined; + if (typeof execStats?.nReturned === "number") { + rowsReturned = execStats.nReturned; + } else if (pipelineStages && pipelineStages.length > 0) { + const lastStage = pipelineStages[pipelineStages.length - 1]; + if (lastStage?.$cursor) { + rowsReturned = + typeof cursorExecStats?.nReturned === "number" ? cursorExecStats.nReturned : undefined; + } else if (typeof lastStage?.nReturned === "number") { + rowsReturned = lastStage.nReturned; + } + } + + if ( + rowsExamined !== undefined && + rowsReturned !== undefined && + rowsExamined > 100 && + (rowsReturned === 0 || rowsExamined > rowsReturned * 10) + ) { + bottlenecks.push({ + type: "LOW_SELECTIVITY", + details: `Examined ${rowsExamined} documents to return ${rowsReturned}`, + severity: rowsExamined > 10000 ? "critical" : "warning", + }); + } + + return { + dialect: DBType.MONGODB, + query, + analyzed: Boolean(effectiveExecStats), + executionTimeMs: + typeof effectiveExecStats?.executionTimeMillis === "number" + ? effectiveExecStats.executionTimeMillis + : undefined, + rowsExamined, + rowsReturned, + bottlenecks, + planTree, + rawPlan: rawExplain, + }; +} + +/** Parse generic indented text EXPLAIN output (MySQL EXPLAIN ANALYZE / DuckDB / ClickHouse). */ +function parseIndentedTextPlan(text: string, bottlenecks: ExplainBottleneck[]): ExplainPlanNode { + const lines = text + .split(/\r?\n/) + .map((l) => l.replace(/\s+$/, "")) + .filter((l) => l.trim().length > 0); + + if (lines.length === 0) { + return { nodeType: "Empty Plan", children: [] }; + } + + const stack: Array<{ indent: number; node: ExplainPlanNode }> = []; + const roots: ExplainPlanNode[] = []; + + for (const line of lines) { + const indent = line.search(/\S/); + const clean = line.trim().replace(/^->\s*/, ""); + + const costMatch = clean.match(/cost=([0-9.]+)/i); + const actualRowsMatch = clean.match(/\(actual\b[^)]*\brows=([0-9.]+)/i); + const withoutActual = clean.replace(/\(actual\b[^)]*\)/gi, ""); + const rowsMatch = withoutActual.match(/\brows=([0-9.]+)/i); + const actualTimeMatch = clean.match(/actual time=[0-9.]+\.\.([0-9.]+)/i); + + if (/table scan|seq_scan|full scan/i.test(clean)) { + bottlenecks.push({ + type: "FULL_SCAN", + details: clean, + severity: "warning", + }); + } + if (/\bsort\b|filesort/i.test(clean)) { + bottlenecks.push({ + type: "FILESORT", + details: clean, + severity: "warning", + }); + } + if (/temporary table|temp_table/i.test(clean)) { + bottlenecks.push({ + type: "TEMP_TABLE", + details: clean, + severity: "warning", + }); + } + + const node: ExplainPlanNode = { + nodeType: clean.split(/\s+\(/)[0] || clean, + cost: costMatch ? Number(costMatch[1]) : undefined, + rows: rowsMatch ? Number(rowsMatch[1]) : undefined, + actualRows: actualRowsMatch ? Number(actualRowsMatch[1]) : undefined, + actualTimeMs: actualTimeMatch ? Number(actualTimeMatch[1]) : undefined, + children: [], + }; + + while (stack.length > 0 && stack[stack.length - 1].indent >= indent) { + stack.pop(); + } + + if (stack.length > 0) { + stack[stack.length - 1].node.children.push(node); + } else { + roots.push(node); + } + stack.push({ indent, node }); + } + + return roots.length === 1 ? roots[0] : { nodeType: "Execution Plan", children: roots }; +} + +export function normalizeDuckdbExplain( + rawPlan: unknown, + query: string, + analyzed: boolean, +): NormalizedExplainPlan { + const bottlenecks: ExplainBottleneck[] = []; + const rows = Array.isArray(rawPlan) ? rawPlan : []; + + const jsonRow = rows.find((r: any) => { + const val = String(r?.explain_value || ""); + return val.trim().startsWith("[") || val.trim().startsWith("{"); + }); + + if (jsonRow) { + try { + const parsed = JSON.parse(String(jsonRow.explain_value)); + const rootRaw = Array.isArray(parsed) ? parsed[0] : parsed; + + const isProfilerPayload = (node: any): boolean => + Boolean( + node && + typeof node === "object" && + ("operator_name" in node || + "operator_type" in node || + "latency" in node || + "cumulative_rows_scanned" in node || + "operator_timing" in node || + "operator_cardinality" in node || + "operator_rows_scanned" in node || + (Array.isArray(node.children) && node.children.some(isProfilerPayload))), + ); + + const parseEstimatedRows = (n: any): number | undefined => { + const rawEst = n?.extra_info?.["Estimated Cardinality"]; + if (rawEst === undefined || rawEst === null) return undefined; + const num = Number(rawEst); + return Number.isFinite(num) ? num : undefined; + }; + + const extractFilter = (n: any): string | undefined => { + const filters = n?.extra_info?.Filters; + if (!filters) return undefined; + return Array.isArray(filters) ? filters.map(String).join(" AND ") : String(filters); + }; + + if (isProfilerPayload(rootRaw)) { + let totalRowsScanned = 0; + let hasScannedCount = false; + const executionTimeMs = + typeof rootRaw?.latency === "number" ? rootRaw.latency * 1000 : undefined; + + let effectiveRoot = rootRaw; + if ( + !effectiveRoot?.operator_name && + !effectiveRoot?.operator_type && + Array.isArray(effectiveRoot?.children) && + effectiveRoot.children.length === 1 + ) { + effectiveRoot = effectiveRoot.children[0]; + } + if ( + effectiveRoot?.operator_name === "EXPLAIN_ANALYZE" && + Array.isArray(effectiveRoot?.children) && + effectiveRoot.children.length === 1 + ) { + effectiveRoot = effectiveRoot.children[0]; + } + + const mapProfilerNode = (n: any): ExplainPlanNode => { + const name = String(n?.operator_name || n?.operator_type || "Operator"); + const relation = n?.extra_info?.Table ? String(n.extra_info.Table) : undefined; + const rowsScanned = + typeof n?.operator_rows_scanned === "number" && Number.isFinite(n.operator_rows_scanned) + ? n.operator_rows_scanned + : undefined; + if (rowsScanned !== undefined) { + totalRowsScanned += rowsScanned; + hasScannedCount = true; + } + const actualRows = + typeof n?.operator_cardinality === "number" + ? n.operator_cardinality + : typeof n?.rows_returned === "number" + ? n.rows_returned + : undefined; + const actualTimeMs = + typeof n?.operator_timing === "number" + ? n.operator_timing * 1000 + : typeof n?.latency === "number" + ? n.latency * 1000 + : undefined; + + if (name === "SEQ_SCAN") { + const scannedCount = rowsScanned ?? actualRows; + bottlenecks.push({ + type: "FULL_SCAN", + target: relation, + details: + scannedCount !== undefined + ? `Sequential scan in DuckDB (${relation || "table"}, ${scannedCount} rows)` + : `Sequential scan in DuckDB (${relation || "table"})`, + severity: scannedCount !== undefined && scannedCount > 1000 ? "critical" : "warning", + }); + } + + return { + nodeType: name, + relation, + rows: parseEstimatedRows(n), + actualRows, + actualTimeMs, + filter: extractFilter(n), + children: Array.isArray(n?.children) ? n.children.map(mapProfilerNode) : [], + }; + }; + + const planTree = mapProfilerNode(effectiveRoot); + const rowsExamined = + typeof rootRaw?.cumulative_rows_scanned === "number" && + Number.isFinite(rootRaw.cumulative_rows_scanned) + ? rootRaw.cumulative_rows_scanned + : hasScannedCount + ? totalRowsScanned + : undefined; + + return { + dialect: DBType.DUCKDB, + query, + analyzed, + executionTimeMs: executionTimeMs ?? planTree.actualTimeMs, + rowsExamined, + rowsReturned: planTree.actualRows, + bottlenecks, + planTree, + rawPlan, + }; + } + + const mapDuckNode = (n: any): ExplainPlanNode => { + const name = String(n?.name || "Operator"); + const relation = n?.extra_info?.Table ? String(n.extra_info.Table) : undefined; + if (name === "SEQ_SCAN") { + bottlenecks.push({ + type: "FULL_SCAN", + target: relation, + details: `Sequential scan in DuckDB (${relation || "table"})`, + severity: "warning", + }); + } + return { + nodeType: name, + relation, + rows: parseEstimatedRows(n), + filter: extractFilter(n), + children: Array.isArray(n?.children) ? n.children.map(mapDuckNode) : [], + }; + }; + const planTree = mapDuckNode(rootRaw); + return { + dialect: DBType.DUCKDB, + query, + analyzed, + rowsReturned: planTree.rows, + bottlenecks, + planTree, + rawPlan, + }; + } catch { + // Fallback to text parsing below + } + } + + const text = rows + .map((r: any) => r?.explain_value ?? r?.explain ?? Object.values(r || {}).join(" ")) + .join("\n"); + const planTree = parseIndentedTextPlan(text, bottlenecks); + + return { + dialect: DBType.DUCKDB, + query, + analyzed, + bottlenecks, + planTree, + rawPlan, + }; +} + +function normalizeClickhouseExplain( + rawPlan: unknown, + query: string, + analyzed: boolean, +): NormalizedExplainPlan { + const bottlenecks: ExplainBottleneck[] = []; + const rows = Array.isArray(rawPlan) ? rawPlan : []; + const text = rows + .map((r: any) => (typeof r === "string" ? r : (r?.explain ?? Object.values(r || {}).join(" ")))) + .join("\n"); + const planTree = parseIndentedTextPlan(text, bottlenecks); + + return { + dialect: DBType.CLICKHOUSE, + query, + analyzed, + bottlenecks, + planTree, + rawPlan, + }; +} + +/** + * Collect and normalize an EXPLAIN plan for the given database connection and dialect. + * Enforces read-only SQL validation when `analyze: true`. + */ +export async function collectExplainPlan( + conn: unknown, + dbType: DBType, + params: CollectExplainParams, +): Promise { + const analyze = Boolean(params.analyze); + + if (dbType === DBType.MONGODB) { + if (!params.collection) { + throw createValidationError("Missing collection for MongoDB explain"); + } + const target = params.pipeline + ? { operation: "aggregate" as const, pipeline: params.pipeline as any[] } + : { operation: "find" as const, filter: (params.filter as any) ?? {} }; + const queryLabel = params.pipeline + ? `db.${params.collection}.aggregate(${JSON.stringify(params.pipeline)})` + : `db.${params.collection}.find(${JSON.stringify(params.filter ?? {})})`; + + const raw = await explainMql(conn as MongoConfig, { + collection: params.collection, + target, + verbosity: analyze ? "executionStats" : "queryPlanner", + }); + return normalizeMongoExplain(raw, queryLabel, analyze); + } + + if (typeof params.sql !== "string" || !params.sql.trim()) { + throw createValidationError("Missing SQL query for explain"); + } + const sql = params.sql.trim(); + const { strippedSql, hasMultiStatement } = scanSqlTokens(sql); + if (!strippedSql) { + throw createValidationError("Missing SQL query for explain"); + } + if (hasMultiStatement) { + throw createValidationError("Multi-statement SQL is not allowed in EXPLAIN"); + } + if (analyze && !isReadOnlySelectSql(sql)) { + throw createValidationError( + "EXPLAIN ANALYZE is only allowed for read-only SELECT, WITH, or VALUES statements", + ); + } + + if (dbType === DBType.POSTGRES) { + const pool = getPgPool(conn as PGConfig); + const client = await pool.connect(); + try { + const cleanSql = sql.replace(/;\s*$/, ""); + if (analyze) { + await client.query("BEGIN READ ONLY"); + try { + const res = await client.query(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${cleanSql}`); + await client.query("ROLLBACK"); + return normalizePostgresExplain(res.rows, sql, true); + } catch (err) { + try { + await client.query("ROLLBACK"); + } catch {} + throw err; + } + } else { + const res = await client.query(`EXPLAIN (FORMAT JSON) ${cleanSql}`); + return normalizePostgresExplain(res.rows, sql, false); + } + } finally { + client.release(); + } + } + + if (dbType === DBType.MYSQL || dbType === DBType.MARIADB) { + const poolConfig = + dbType === DBType.MARIADB + ? createMariaPoolConfig(conn as MySQLConfig) + : createMysqlPoolConfig(conn as MySQLConfig); + const pool = mysql.createPool(poolConfig); + let connection: mysql.PoolConnection | null = null; + try { + connection = await pool.getConnection(); + const cleanSql = sql.replace(/;\s*$/, ""); + const explainSql = analyze + ? dbType === DBType.MARIADB + ? `ANALYZE FORMAT=JSON ${cleanSql}` + : `EXPLAIN ANALYZE ${cleanSql}` + : `EXPLAIN FORMAT=JSON ${cleanSql}`; + const [rows] = await connection.query(explainSql); + return normalizeMysqlExplain(rows, sql, analyze, dbType); + } finally { + if (connection) connection.release(); + await pool.end(); + } + } + + if (dbType === DBType.SQLITE) { + const db = openSQLiteDB(conn as SQLiteConfig, { readonly: true }); + try { + const cleanSql = sql.replace(/;\s*$/, ""); + const rows = db.prepare(`EXPLAIN QUERY PLAN ${cleanSql}`).all() as Array<{ + id?: number; + parent?: number; + notused?: number; + detail?: string; + }>; + return normalizeSqliteExplain(rows, sql); + } finally { + db.close(); + } + } + + if (dbType === DBType.DUCKDB) { + const cleanSql = sql.replace(/;\s*$/, ""); + if (analyze) { + try { + const rows = await runDuckDBQuery( + conn as DuckDBConfig, + `EXPLAIN (ANALYZE, FORMAT JSON) ${cleanSql}`, + ); + return normalizeDuckdbExplain(rows, sql, true); + } catch { + const rows = await runDuckDBQuery(conn as DuckDBConfig, `EXPLAIN ANALYZE ${cleanSql}`); + return normalizeDuckdbExplain(rows, sql, true); + } + } + try { + const rows = await runDuckDBQuery(conn as DuckDBConfig, `EXPLAIN (FORMAT JSON) ${cleanSql}`); + return normalizeDuckdbExplain(rows, sql, false); + } catch { + const rows = await runDuckDBQuery(conn as DuckDBConfig, `EXPLAIN ${cleanSql}`); + return normalizeDuckdbExplain(rows, sql, false); + } + } + + if (dbType === DBType.CLICKHOUSE) { + const client = getClickHouseClient(conn as ClickHouseConfig); + const cleanSql = sql.replace(/;\s*$/, ""); + const res = await client.query({ + query: `EXPLAIN PLAN ${cleanSql}`, + format: "JSONEachRow", + }); + const rows = await res.json(); + return normalizeClickhouseExplain(rows, sql, false); + } + + throw createValidationError(`Explain plan is not supported for dialect '${dbType}'`); +} 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/indexStatsService.ts b/bridge/src/services/indexStatsService.ts new file mode 100644 index 00000000..cd5ce29a --- /dev/null +++ b/bridge/src/services/indexStatsService.ts @@ -0,0 +1,761 @@ +import mysql, { RowDataPacket } from "mysql2/promise"; +import { DBType } from "../types"; +import { DuplicateIndexPair, IndexHealthEntry, IndexHealthReport } from "../types/performance"; +import { getPool as getPgPool } from "../connectors/postgres"; +import { createPoolConfig as createMysqlPoolConfig } from "../connectors/mysql"; +import { createPoolConfig as createMariaPoolConfig } from "../connectors/mariadb"; +import { openSQLiteDB } from "../connectors/sqlite"; +import { runQuery as runDuckDBQuery } from "../connectors/duckdb"; +import { getClient as getClickHouseClient } from "../connectors/clickhouse"; +import { listCollections, mongoConnector } from "../connectors/mongo"; +import { PGConfig } from "../types/postgres"; +import { MySQLConfig } from "../types/mysql"; +import { SQLiteConfig } from "../types/sqlite"; +import { DuckDBConfig } from "../types/duckdb"; +import { ClickHouseConfig } from "../types/clickhouse"; +import { MongoConfig } from "../types/mongo"; + +export interface CollectIndexHealthOptions { + tableOrCollection?: string; +} + +function quoteSqliteIdent(name: string): string { + return `"${name.replace(/"/g, '""')}"`; +} + +function arraysEqual(a: string[], b: string[]): boolean { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } + return true; +} + +function isStrictPrefix(prefix: string[], full: string[]): boolean { + if (prefix.length === 0 || prefix.length >= full.length) return false; + for (let i = 0; i < prefix.length; i++) { + if (prefix[i] !== full[i]) return false; + } + return true; +} + +interface IndexComparisonMeta { + comparisonKeys?: string[]; + signature?: string; + canReplace?: boolean; + allowPrefix?: boolean; + nullsNotDistinct?: boolean; +} + +function indexGroupKey(schema: string | undefined, tableOrCollection: string): string { + return JSON.stringify([schema ?? null, tableOrCollection]); +} + +function indexIdentityKey( + schema: string | undefined, + tableOrCollection: string, + indexName: string, +): string { + return JSON.stringify([schema ?? null, tableOrCollection, indexName]); +} + +/** + * Pure helper that detects exact duplicate and prefix-redundant indexes + * on the same schema + table/collection. + * + * A non-unique, non-primary index A is flagged as redundant with B when: + * - A and B have the exact same ordered columns (canonical preference: primary > unique > first), OR + * - A's columns form a strict prefix of B's columns. + */ +export function detectDuplicateIndexes( + entries: IndexHealthEntry[], + metaByEntry?: WeakMap, +): DuplicateIndexPair[] { + const pairs: DuplicateIndexPair[] = []; + const groups = new Map(); + + for (const entry of entries) { + const keys = metaByEntry?.get(entry)?.comparisonKeys ?? entry.columns; + if (keys.length === 0) continue; + const key = indexGroupKey(entry.schema, entry.tableOrCollection); + const list = groups.get(key); + if (list) { + list.push(entry); + } else { + groups.set(key, [entry]); + } + } + + for (const group of groups.values()) { + // Sort canonical candidates first: replaceable > primary > unique > wider > earlier name + const sorted = [...group].sort((a, b) => { + const aCanReplace = metaByEntry?.get(a)?.canReplace !== false; + const bCanReplace = metaByEntry?.get(b)?.canReplace !== false; + if (aCanReplace !== bCanReplace) return aCanReplace ? -1 : 1; + if (a.isPrimary !== b.isPrimary) return a.isPrimary ? -1 : 1; + if (a.isUnique !== b.isUnique) return a.isUnique ? -1 : 1; + const aLen = (metaByEntry?.get(a)?.comparisonKeys ?? a.columns).length; + const bLen = (metaByEntry?.get(b)?.comparisonKeys ?? b.columns).length; + if (aLen !== bLen) return bLen - aLen; + return a.indexName.localeCompare(b.indexName); + }); + + const flagged = new Set(); + + for (const candidate of group) { + if (candidate.isPrimary) continue; + if (flagged.has(candidate)) continue; + + const candidateMeta = metaByEntry?.get(candidate); + const candidateKeys = candidateMeta?.comparisonKeys ?? candidate.columns; + + for (const other of sorted) { + if (other === candidate || other.indexName === candidate.indexName) continue; + + const otherMeta = metaByEntry?.get(other); + if (otherMeta?.canReplace === false) continue; + + const otherKeys = otherMeta?.comparisonKeys ?? other.columns; + const sameSignature = (candidateMeta?.signature ?? null) === (otherMeta?.signature ?? null); + + if (sameSignature && arraysEqual(candidateKeys, otherKeys)) { + // Only flag candidate if `other` outranks it in canonical order and preserves uniqueness + const candidateIdx = sorted.indexOf(candidate); + const otherIdx = sorted.indexOf(other); + const candidateNullsNotDistinct = candidateMeta?.nullsNotDistinct ?? false; + const otherNullsNotDistinct = otherMeta?.nullsNotDistinct ?? false; + const preservesNullRule = + !candidate.isUnique || candidateNullsNotDistinct === otherNullsNotDistinct; + if ( + otherIdx < candidateIdx && + !candidate.isPrimary && + (!candidate.isUnique || ((other.isUnique || other.isPrimary) && preservesNullRule)) + ) { + pairs.push({ + schema: candidate.schema, + tableOrCollection: candidate.tableOrCollection, + indexName: candidate.indexName, + redundantWith: other.indexName, + reason: `Exact duplicate of index '${other.indexName}' on (${candidate.columns.join(", ")})`, + }); + flagged.add(candidate); + break; + } + } else if ( + (candidateMeta?.allowPrefix ?? true) && + (otherMeta?.allowPrefix ?? true) && + sameSignature && + !candidate.isUnique && + !candidate.isPrimary && + isStrictPrefix(candidateKeys, otherKeys) + ) { + pairs.push({ + schema: candidate.schema, + tableOrCollection: candidate.tableOrCollection, + indexName: candidate.indexName, + redundantWith: other.indexName, + reason: `Columns (${candidate.columns.join(", ")}) are a strict prefix of index '${other.indexName}' (${other.columns.join(", ")})`, + }); + flagged.add(candidate); + break; + } + } + } + } + + return pairs; +} + +function finalizeReport( + dialect: string, + indexes: IndexHealthEntry[], + metaByEntry?: WeakMap, +): IndexHealthReport { + const duplicateIndexes = detectDuplicateIndexes(indexes, metaByEntry); + const dupMap = new Map(); + for (const pair of duplicateIndexes) { + dupMap.set(indexIdentityKey(pair.schema, pair.tableOrCollection, pair.indexName), pair); + } + + const enriched = indexes.map((entry) => { + const pair = dupMap.get( + indexIdentityKey(entry.schema, entry.tableOrCollection, entry.indexName), + ); + if (pair) { + return { + ...entry, + status: "duplicate" as const, + duplicateOf: pair.redundantWith, + }; + } + return entry; + }); + + const unusedIndexes = enriched.filter((e) => e.status === "unused"); + const totalSizeBytes = enriched.reduce((sum, e) => sum + (e.sizeBytes ?? 0), 0); + + return { + dialect, + indexes: enriched, + unusedIndexes, + duplicateIndexes, + summary: { + total: enriched.length, + unusedCount: unusedIndexes.length, + duplicateCount: duplicateIndexes.length, + totalSizeBytes, + }, + }; +} + +async function collectPostgresIndexHealth( + cfg: PGConfig, + options?: CollectIndexHealthOptions, +): Promise { + const pool = getPgPool(cfg); + const client = await pool.connect(); + try { + const res = await client.query( + ` + SELECT + s.schemaname AS schema_name, + s.relname AS table_name, + s.indexrelname AS index_name, + s.idx_scan AS scans, + pg_relation_size(s.indexrelid) AS size_bytes, + i.indisunique AS is_unique, + i.indisprimary AS is_primary, + i.indisvalid AS is_valid, + am.amname AS index_type, + pg_get_indexdef(i.indexrelid) AS sql_definition, + pg_get_expr(i.indpred, i.indrelid) AS predicate, + (i.indpred IS NOT NULL) AS is_partial, + (to_jsonb(i)->>'indnullsnotdistinct') = 'true' AS nulls_not_distinct, + EXISTS ( + SELECT 1 + FROM unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord) + WHERE k.ord <= i.indnkeyatts AND k.attnum = 0 + ) AS has_expression, + ARRAY( + SELECT a.attname + FROM unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord) + JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum + WHERE k.ord <= i.indnkeyatts + ORDER BY k.ord + ) AS columns, + ARRAY( + SELECT COALESCE(cn.nspname || '.' || c.collname, c.collname, col.colloid::text, '0') + FROM unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord) + JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum + LEFT JOIN unnest(i.indcollation) WITH ORDINALITY AS col(colloid, cord) ON col.cord = k.ord + LEFT JOIN pg_collation c ON c.oid = col.colloid + LEFT JOIN pg_namespace cn ON cn.oid = c.colnamespace + WHERE k.ord <= i.indnkeyatts + ORDER BY k.ord + ) AS collations + FROM pg_stat_user_indexes s + JOIN pg_index i ON i.indexrelid = s.indexrelid + JOIN pg_class ic ON ic.oid = i.indexrelid + JOIN pg_am am ON am.oid = ic.relam + WHERE ($1::text IS NULL OR s.relname = $1) + ORDER BY s.schemaname, s.relname, s.indexrelname + `, + [options?.tableOrCollection ?? null], + ); + + const metaByEntry = new WeakMap(); + const entries: IndexHealthEntry[] = res.rows.map((r: any) => { + const scans = r.scans !== null && r.scans !== undefined ? Number(r.scans) : null; + const sizeBytes = + r.size_bytes !== null && r.size_bytes !== undefined ? Number(r.size_bytes) : null; + const isUnique = Boolean(r.is_unique); + const isPrimary = Boolean(r.is_primary); + const isValid = r.is_valid !== false; + const nullsNotDistinct = Boolean(r.nulls_not_distinct); + const hasExpression = Boolean(r.has_expression); + const indexType = + typeof r.index_type === "string" && r.index_type.trim() + ? r.index_type.trim().toLowerCase() + : undefined; + const sqlDefinition = + typeof r.sql_definition === "string" && r.sql_definition.trim() + ? r.sql_definition + : undefined; + const predicate = + r.predicate !== null && r.predicate !== undefined ? String(r.predicate) : null; + const isPartial = r.is_partial !== undefined ? Boolean(r.is_partial) : predicate !== null; + const columns = Array.isArray(r.columns) ? r.columns.map(String) : []; + const rawCollations = Array.isArray(r.collations) + ? r.collations + : Array.isArray(r.indcollation) + ? r.indcollation + : typeof r.indcollation === "string" && r.indcollation.trim() + ? r.indcollation.trim().split(/\s+/) + : null; + const comparisonKeys = hasExpression + ? [] + : rawCollations + ? columns.map((col, idx) => + JSON.stringify([col, rawCollations[idx] != null ? String(rawCollations[idx]) : ""]), + ) + : undefined; + const status = scans === 0 && !isPrimary && !isUnique ? "unused" : "healthy"; + + const entry: IndexHealthEntry = { + schema: r.schema_name ? String(r.schema_name) : undefined, + tableOrCollection: String(r.table_name), + indexName: String(r.index_name), + columns, + ...(indexType !== undefined ? { indexType } : {}), + isUnique, + isPrimary, + ...(sqlDefinition !== undefined ? { sqlDefinition } : {}), + predicate, + isPartial, + scans, + sizeBytes, + status, + }; + const meta: IndexComparisonMeta = {}; + if (isUnique) { + meta.nullsNotDistinct = nullsNotDistinct; + } + if (comparisonKeys !== undefined) { + meta.comparisonKeys = comparisonKeys; + } + if (indexType !== undefined) { + meta.signature = indexType; + if (indexType !== "btree") { + meta.allowPrefix = false; + } + } + if (!isValid || isPartial || hasExpression) { + meta.canReplace = false; + } + if (Object.keys(meta).length > 0) { + metaByEntry.set(entry, meta); + } + return entry; + }); + + return finalizeReport(DBType.POSTGRES, entries, metaByEntry); + } finally { + client.release(); + } +} + +async function collectMysqlIndexHealth( + cfg: MySQLConfig, + dbType: DBType.MYSQL | DBType.MARIADB, + options?: CollectIndexHealthOptions, +): Promise { + const poolConfig = + dbType === DBType.MARIADB ? createMariaPoolConfig(cfg) : createMysqlPoolConfig(cfg); + const pool = mysql.createPool(poolConfig); + let connection: mysql.PoolConnection | null = null; + + try { + connection = await pool.getConnection(); + const tableFilter = options?.tableOrCollection ?? null; + + const [statRows] = await connection.query( + ` + SELECT + TABLE_SCHEMA AS schema_name, + TABLE_NAME AS table_name, + INDEX_NAME AS index_name, + NON_UNIQUE AS non_unique, + COLUMN_NAME AS column_name, + SEQ_IN_INDEX AS seq_in_index, + SUB_PART AS sub_part, + INDEX_TYPE AS index_type + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND (? IS NULL OR TABLE_NAME = ?) + ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX + `, + [tableFilter, tableFilter], + ); + + const scanCounts = new Map(); + let hasPerfSchema = false; + try { + const [perfRows] = await connection.query( + ` + SELECT + OBJECT_NAME AS table_name, + INDEX_NAME AS index_name, + COUNT_STAR AS scans + FROM performance_schema.table_io_waits_summary_by_index_usage + WHERE OBJECT_SCHEMA = DATABASE() + AND INDEX_NAME IS NOT NULL + AND (? IS NULL OR OBJECT_NAME = ?) + `, + [tableFilter, tableFilter], + ); + hasPerfSchema = true; + for (const r of perfRows) { + if (r.scans !== null && r.scans !== undefined) { + scanCounts.set( + JSON.stringify([String(r.table_name), String(r.index_name)]), + Number(r.scans), + ); + } + } + } catch { + // performance_schema may be disabled or inaccessible; fall back to scans: null + hasPerfSchema = false; + } + + const grouped = new Map(); + const metaByEntry = new WeakMap(); + const hasUnrepresentedKeyPart = new Set(); + for (const row of statRows) { + const schemaName = row.schema_name ? String(row.schema_name) : undefined; + const tableName = String(row.table_name); + const indexName = String(row.index_name); + const key = indexIdentityKey(schemaName, tableName, indexName); + + let entry = grouped.get(key); + if (!entry) { + const isPrimary = indexName === "PRIMARY"; + const isUnique = Number(row.non_unique) === 0; + const indexType = + typeof row.index_type === "string" && row.index_type.trim() + ? row.index_type.trim().toLowerCase() + : undefined; + const measuredScans = hasPerfSchema + ? scanCounts.get(JSON.stringify([tableName, indexName])) + : undefined; + const scans = measuredScans !== undefined ? measuredScans : null; + const status = scans === 0 && !isPrimary && !isUnique ? "unused" : "healthy"; + + entry = { + schema: schemaName, + tableOrCollection: tableName, + indexName, + columns: [], + ...(indexType !== undefined ? { indexType } : {}), + isUnique, + isPrimary, + scans, + sizeBytes: null, + status, + }; + grouped.set(key, entry); + metaByEntry.set(entry, { + comparisonKeys: [], + ...(indexType !== undefined + ? { signature: indexType, ...(indexType !== "btree" ? { allowPrefix: false } : {}) } + : {}), + }); + } + + if (row.column_name) { + const colName = String(row.column_name); + entry.columns.push(colName); + const subPart = + row.sub_part !== null && row.sub_part !== undefined ? Number(row.sub_part) : null; + const comparisonKey = + subPart !== null && !Number.isNaN(subPart) ? `${colName}(${subPart})` : colName; + metaByEntry.get(entry)?.comparisonKeys?.push(comparisonKey); + } else { + hasUnrepresentedKeyPart.add(key); + } + } + + for (const key of hasUnrepresentedKeyPart) { + const entry = grouped.get(key); + if (entry) { + const meta = metaByEntry.get(entry); + if (meta) { + meta.comparisonKeys = []; + meta.canReplace = false; + } + } + } + + return finalizeReport(dbType, Array.from(grouped.values()), metaByEntry); + } finally { + if (connection) connection.release(); + await pool.end(); + } +} + +async function collectSqliteIndexHealth( + cfg: SQLiteConfig, + options?: CollectIndexHealthOptions, +): Promise { + const db = openSQLiteDB(cfg, { readonly: true }); + try { + const tables: string[] = options?.tableOrCollection + ? [options.tableOrCollection] + : ( + db + .prepare( + `SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name`, + ) + .all() as Array<{ name: string }> + ).map((r) => r.name); + + const entries: IndexHealthEntry[] = []; + const metaByEntry = new WeakMap(); + for (const tableName of tables) { + const idxList = db.pragma(`index_list(${quoteSqliteIdent(tableName)})`) as Array<{ + name: string; + unique: number; + origin: string; + partial?: number; + }>; + + for (const idx of idxList) { + const keyRows = ( + db.pragma(`index_xinfo(${quoteSqliteIdent(idx.name)})`) as Array<{ + seqno: number; + cid: number; + name: string | null; + coll?: string; + key?: number; + }> + ) + .filter((c) => c.key === undefined || c.key === 1) + .sort((a, b) => a.seqno - b.seqno); + + const hasExpressionKey = keyRows.some((c) => c.cid < 0 || !c.name); + const cols = keyRows + .filter((c): c is typeof c & { name: string } => c.cid >= 0 && Boolean(c.name)) + .map((c) => c.name); + const comparisonKeys = hasExpressionKey + ? [] + : keyRows + .filter((c): c is typeof c & { name: string } => c.cid >= 0 && Boolean(c.name)) + .map((c) => `${c.name}:${(c.coll || "BINARY").toUpperCase()}`); + const isPartial = idx.partial === 1; + + const entry: IndexHealthEntry = { + schema: "main", + tableOrCollection: tableName, + indexName: idx.name, + columns: cols, + isUnique: idx.unique === 1, + isPrimary: idx.origin === "pk", + isPartial, + scans: null, + sizeBytes: null, + status: "healthy", + }; + metaByEntry.set(entry, { + comparisonKeys, + ...(isPartial || hasExpressionKey ? { canReplace: false } : {}), + }); + entries.push(entry); + } + } + + return finalizeReport(DBType.SQLITE, entries, metaByEntry); + } finally { + db.close(); + } +} + +function parseDuckdbIndexColumns(expressions?: unknown, sql?: string): string[] { + if (Array.isArray(expressions)) { + const cols = expressions.map((c) => String(c).trim().replace(/^"|"$/g, "")).filter(Boolean); + if (cols.length > 0) return cols; + } else if (typeof expressions === "string" && expressions.trim()) { + const stripped = expressions.trim().replace(/^\[|\]$/g, ""); + const cols = stripped + .split(",") + .map((c) => c.trim().replace(/^"|"$/g, "")) + .filter(Boolean); + if (cols.length > 0) return cols; + } + + if (!sql) return []; + const match = sql.match(/\(([^)]+)\)\s*;?\s*$/); + if (!match) return []; + return match[1] + .split(",") + .map((c) => c.trim().replace(/^"|"$/g, "")) + .filter(Boolean); +} + +async function collectDuckdbIndexHealth( + cfg: DuckDBConfig, + options?: CollectIndexHealthOptions, +): Promise { + const rows = await runDuckDBQuery( + cfg, + `SELECT schema_name, table_name, index_name, is_unique, is_primary, expressions, sql FROM duckdb_indexes()`, + ); + + const filtered = options?.tableOrCollection + ? rows.filter((r) => r.table_name === options.tableOrCollection) + : rows; + + const metaByEntry = new WeakMap(); + const entries: IndexHealthEntry[] = filtered.map((r) => { + const entry: IndexHealthEntry = { + schema: r.schema_name ? String(r.schema_name) : undefined, + tableOrCollection: String(r.table_name), + indexName: String(r.index_name), + columns: parseDuckdbIndexColumns(r.expressions, r.sql), + isUnique: Boolean(r.is_unique), + isPrimary: Boolean(r.is_primary), + scans: null, + sizeBytes: null, + status: "healthy", + }; + metaByEntry.set(entry, { allowPrefix: false }); + return entry; + }); + + return finalizeReport(DBType.DUCKDB, entries, metaByEntry); +} + +async function collectClickhouseIndexHealth( + cfg: ClickHouseConfig, + options?: CollectIndexHealthOptions, +): Promise { + const client = getClickHouseClient(cfg); + const dbName = cfg.database || "default"; + const res = await client.query({ + query: ` + SELECT database, table, name AS index_name, expr, type_full, granularity + FROM system.data_skipping_indices + WHERE database = {db:String} + `, + query_params: { db: dbName }, + format: "JSONEachRow", + }); + const rows = (await res.json()) as Array<{ + database: string; + table: string; + index_name: string; + expr: string; + type_full?: string; + granularity?: number | string; + }>; + + const filtered = options?.tableOrCollection + ? rows.filter((r) => r.table === options.tableOrCollection) + : rows; + + const metaByEntry = new WeakMap(); + const entries: IndexHealthEntry[] = filtered.map((r) => { + const entry: IndexHealthEntry = { + schema: r.database, + tableOrCollection: r.table, + indexName: r.index_name, + columns: r.expr ? [r.expr] : [], + isUnique: false, + isPrimary: false, + scans: null, + sizeBytes: null, + status: "healthy", + }; + const hasComparableMeta = + Boolean(r.type_full) && r.granularity !== null && r.granularity !== undefined; + metaByEntry.set( + entry, + hasComparableMeta + ? { + signature: JSON.stringify([String(r.type_full), Number(r.granularity)]), + allowPrefix: false, + } + : { + canReplace: false, + allowPrefix: false, + }, + ); + return entry; + }); + + return finalizeReport(DBType.CLICKHOUSE, entries, metaByEntry); +} + +async function collectMongoIndexHealth( + cfg: MongoConfig, + options?: CollectIndexHealthOptions, +): Promise { + const collectionNames = options?.tableOrCollection + ? [options.tableOrCollection] + : (await listCollections(cfg)) + .filter((c) => c.type === undefined || c.type === "collection") + .map((c) => c.name); + + const entries: IndexHealthEntry[] = []; + const metaByEntry = new WeakMap(); + + for (const collection of collectionNames) { + const indexList = await mongoConnector.listIndexes(cfg, { collection }); + let statsMap: Record = {}; + try { + const statsResult = await mongoConnector.getIndexStats(cfg, { collection }); + statsMap = statsResult.stats; + } catch { + statsMap = {}; + } + + for (const idx of indexList.indexes) { + const isPrimary = idx.isIdIndex || idx.name === "_id_"; + const isUnique = Boolean(idx.unique); + const stat = statsMap[idx.name]; + const scans = stat ? stat.ops : null; + const status = + scans === 0 && !isPrimary && !isUnique && idx.name !== "_id_" ? "unused" : "healthy"; + + const keyEntries = Object.entries(idx.key || {}); + const entry: IndexHealthEntry = { + tableOrCollection: collection, + indexName: idx.name, + columns: keyEntries.map(([k]) => k), + isUnique, + isPrimary, + scans, + sizeBytes: typeof idx.sizeBytes === "number" ? idx.sizeBytes : null, + status, + }; + metaByEntry.set(entry, { + comparisonKeys: keyEntries.map(([k, v]) => `${k}:${JSON.stringify(v)}`), + }); + entries.push(entry); + } + } + + return finalizeReport(DBType.MONGODB, entries, metaByEntry); +} + +/** + * Collect index usage statistics, unused index flags, and duplicate/prefix-redundant + * index diagnostics for the specified database connection. + */ +export async function collectIndexHealth( + conn: unknown, + dbType: DBType, + options?: CollectIndexHealthOptions, +): Promise { + switch (dbType) { + case DBType.POSTGRES: + return collectPostgresIndexHealth(conn as PGConfig, options); + case DBType.MYSQL: + return collectMysqlIndexHealth(conn as MySQLConfig, DBType.MYSQL, options); + case DBType.MARIADB: + return collectMysqlIndexHealth(conn as MySQLConfig, DBType.MARIADB, options); + case DBType.SQLITE: + return collectSqliteIndexHealth(conn as SQLiteConfig, options); + case DBType.DUCKDB: + return collectDuckdbIndexHealth(conn as DuckDBConfig, options); + case DBType.CLICKHOUSE: + return collectClickhouseIndexHealth(conn as ClickHouseConfig, options); + case DBType.MONGODB: + return collectMongoIndexHealth(conn as MongoConfig, options); + default: { + const err = new Error(`Index health is not supported for dialect '${dbType}'`) as Error & { + code: string; + }; + err.code = "VALIDATION_ERROR"; + throw err; + } + } +} diff --git a/bridge/src/services/liveSchemaIntrospector.ts b/bridge/src/services/liveSchemaIntrospector.ts new file mode 100644 index 00000000..c6f9fc90 --- /dev/null +++ b/bridge/src/services/liveSchemaIntrospector.ts @@ -0,0 +1,586 @@ +/** + * 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 { getConnector } from "./connectorRegistry"; +import { mongoConnector, selectDb } from "../connectors/mongo"; +import { + normalizeLiveSqlSchemas, + normalizeMongoIntrospection, + type MongoIntrospectionInput, +} from "./schemaSnapshotNormalizer"; + +function escapeSqlLiteral(value: string): string { + return value.replace(/'/g, "''"); +} + +function skipSqlTrivia(sql: string, start: number): number { + let i = start; + while (i < sql.length) { + const ch = sql[i]; + if (/\s/.test(ch)) { + i++; + continue; + } + if (ch === "-" && sql[i + 1] === "-") { + const nl = sql.indexOf("\n", i + 2); + i = nl === -1 ? sql.length : nl + 1; + continue; + } + if (ch === "/" && sql[i + 1] === "*") { + const close = sql.indexOf("*/", i + 2); + i = close === -1 ? sql.length : close + 2; + continue; + } + break; + } + return i; +} + +function skipSqlQuotedToken(sql: string, i: number, allowBackslashEscape = false): number | null { + const ch = sql[i]; + if (ch === "'" || ch === '"' || ch === "`") { + let j = i + 1; + while (j < sql.length) { + if (allowBackslashEscape && sql[j] === "\\" && j + 1 < sql.length) { + j += 2; + continue; + } + if (sql[j] === ch) { + if (sql[j + 1] === ch) { + j += 2; + continue; + } + return j + 1; + } + j++; + } + return sql.length; + } + if (ch === "[") { + const close = sql.indexOf("]", i + 1); + return close === -1 ? sql.length : close + 1; + } + if (ch === "$") { + const prevTail = i > 0 ? sql.slice(Math.max(0, i - 2), i) : ""; + if (i === 0 || !/[\p{L}\p{N}_$]$/u.test(prevTail)) { + const match = sql.slice(i).match(/^\$(?:[\p{L}_][\p{L}\p{N}_]*)?\$/u); + if (match) { + const delim = match[0]; + const close = sql.indexOf(delim, i + delim.length); + if (close !== -1) { + return close + delim.length; + } + } + } + } + return null; +} + +function unquoteViewColumnIdent(token: string, allowBackslashEscape: boolean): string { + const trimmed = token.trim(); + if (!trimmed) return ""; + const first = trimmed[0]; + const last = trimmed[trimmed.length - 1]; + if ( + trimmed.length >= 2 && + ((first === '"' && last === '"') || + (first === "`" && last === "`") || + (first === "'" && last === "'")) + ) { + let inner = trimmed.slice(1, -1).split(`${first}${first}`).join(first); + if (allowBackslashEscape) { + inner = inner.replace(/\\(.)/g, "$1"); + } + return inner; + } + if (trimmed.length >= 2 && first === "[" && last === "]") { + return trimmed.slice(1, -1); + } + return trimmed; +} + +function parseViewColumnList(inner: string, allowBackslashEscape: boolean): string[] | undefined { + const columns: string[] = []; + let i = 0; + while (i < inner.length) { + i = skipSqlTrivia(inner, i); + if (i >= inner.length) break; + + if (inner[i] === ",") { + i++; + continue; + } + + const quotedEnd = skipSqlQuotedToken(inner, i, allowBackslashEscape); + if (quotedEnd !== null) { + const colName = unquoteViewColumnIdent(inner.slice(i, quotedEnd), allowBackslashEscape); + if (colName) columns.push(colName); + i = quotedEnd; + } else { + const m = inner.slice(i).match(/^[\p{L}_][\p{L}\p{N}_\p{M}$]*/u); + if (m) { + columns.push(m[0]); + i += m[0].length; + } + } + + // Advance to the next top-level comma (skipping optional ClickHouse types or trailing tokens) + let nestedDepth = 0; + while (i < inner.length) { + i = skipSqlTrivia(inner, i); + if (i >= inner.length) break; + const qEnd = skipSqlQuotedToken(inner, i, allowBackslashEscape); + if (qEnd !== null) { + i = qEnd; + continue; + } + const c = inner[i]; + if (c === "(") { + nestedDepth++; + i++; + continue; + } + if (c === ")") { + if (nestedDepth > 0) nestedDepth--; + i++; + continue; + } + if (c === "," && nestedDepth === 0) { + i++; + break; + } + i++; + } + } + + return columns.length > 0 ? columns : undefined; +} + +export interface ExtractedViewMetadata { + body: string; + columns?: string[]; +} + +/** + * Extract the query body and optional explicit column list from SQLite (`sqlite_master.sql`), + * DuckDB, and ClickHouse `CREATE VIEW ... [(cols)] AS ` catalog DDL, preserving + * PostgreSQL and MySQL/MariaDB query bodies. + */ +export function extractViewMetadata(rawDefinition: string, dbType: DBType): ExtractedViewMetadata { + const raw = String(rawDefinition ?? ""); + if (dbType === DBType.POSTGRES || dbType === DBType.MYSQL || dbType === DBType.MARIADB) { + return { body: raw }; + } + + const allowBackslashEscape = dbType === DBType.CLICKHOUSE; + + let i = skipSqlTrivia(raw, 0); + const readWord = (pos: number): { word: string; next: number } | null => { + const p = skipSqlTrivia(raw, pos); + const m = raw.slice(p).match(/^[A-Za-z_][A-Za-z0-9_]*/); + if (!m) return null; + return { word: m[0].toUpperCase(), next: p + m[0].length }; + }; + + const first = readWord(i); + if (!first || first.word !== "CREATE") { + return { body: raw.trim() }; + } + i = first.next; + + let seenView = false; + while (i < raw.length) { + const tok = readWord(i); + if (!tok) break; + i = tok.next; + if (tok.word === "VIEW") { + seenView = true; + break; + } + if ( + tok.word === "OR" || + tok.word === "REPLACE" || + tok.word === "TEMP" || + tok.word === "TEMPORARY" || + tok.word === "RECURSIVE" + ) { + continue; + } + break; + } + + if (!seenView) { + return { body: raw.trim() }; + } + + let parenDepth = 0; + let colListStart: number | null = null; + let colListEnd: number | null = null; + while (i < raw.length) { + i = skipSqlTrivia(raw, i); + if (i >= raw.length) break; + + const quotedEnd = skipSqlQuotedToken(raw, i, allowBackslashEscape); + if (quotedEnd !== null) { + i = quotedEnd; + continue; + } + + const ch = raw[i]; + if (ch === "(") { + if (parenDepth === 0 && colListStart === null) { + colListStart = i + 1; + } + parenDepth++; + i++; + continue; + } + if (ch === ")") { + if (parenDepth > 0) { + parenDepth--; + if (parenDepth === 0 && colListStart !== null && colListEnd === null) { + colListEnd = i; + } + } + i++; + continue; + } + + if (/^[a-zA-Z_]|[\u0080-\u{10FFFF}]/u.test(ch)) { + const m = raw + .slice(i) + .match(/^([a-zA-Z_]|[\u0080-\u{10FFFF}])([a-zA-Z0-9_$]|[\u0080-\u{10FFFF}])*/u); + if (m) { + i += m[0].length; + if (parenDepth === 0 && /^[aA][sS]$/.test(m[0])) { + const body = raw.slice(i).trim().replace(/;\s*$/, "").trim(); + const columns = + colListStart !== null && colListEnd !== null + ? parseViewColumnList(raw.slice(colListStart, colListEnd), allowBackslashEscape) + : undefined; + return columns ? { body, columns } : { body }; + } + continue; + } + } + + i++; + } + + return { body: raw.trim() }; +} + +/** + * Normalize SQLite (`sqlite_master.sql`) and DuckDB full `CREATE VIEW ... AS ` + * catalog DDL into consistent query body text at the introspector boundary, preserving + * PostgreSQL and MySQL/MariaDB query bodies. + */ +export function extractViewBody(rawDefinition: string, dbType: DBType): string { + return extractViewMetadata(rawDefinition, dbType).body; +} + +async function queryConnectorRows( + connector: any, + conn: unknown, + sql: string, +): Promise>> { + if (typeof connector.streamQueryCancelable !== "function") { + return []; + } + const rows: Array> = []; + const runner = connector.streamQueryCancelable( + conn, + sql, + 1000, + (batch: Array>) => { + rows.push(...batch); + }, + ); + await runner.promise; + return rows; +} + +async function introspectSchemaViews( + connector: any, + conn: unknown, + dbType: DBType, + schemaName: string, + tablesInSchema: Array<{ name: string; type?: string }>, +): Promise> { + const viewTables = tablesInSchema.filter((t) => String(t.type || "").toUpperCase() === "VIEW"); + if (typeof connector.streamQueryCancelable !== "function") { + return viewTables.map((v) => ({ name: v.name, definition: "" })); + } + + const escaped = escapeSqlLiteral(schemaName); + let sql: string | null = null; + switch (dbType) { + case DBType.POSTGRES: + sql = `SELECT viewname AS name, definition FROM pg_views WHERE schemaname = '${escaped}' ORDER BY viewname`; + break; + case DBType.MYSQL: + case DBType.MARIADB: + sql = `SELECT TABLE_NAME AS name, VIEW_DEFINITION AS definition FROM information_schema.VIEWS WHERE TABLE_SCHEMA = '${escaped}' ORDER BY TABLE_NAME`; + break; + case DBType.SQLITE: + sql = `SELECT name, sql AS definition FROM sqlite_master WHERE type = 'view' AND name NOT LIKE 'sqlite_%' ORDER BY name`; + break; + case DBType.DUCKDB: + sql = `SELECT view_name AS name, sql AS definition FROM duckdb_views() WHERE schema_name = '${escaped}' AND NOT internal ORDER BY view_name`; + break; + case DBType.CLICKHOUSE: + sql = `SELECT name, create_table_query AS definition FROM system.tables WHERE database = '${escaped}' AND engine = 'View' ORDER BY name`; + break; + default: + break; + } + + if (!sql) { + return viewTables.map((v) => ({ name: v.name, definition: "" })); + } + + const rows = await queryConnectorRows(connector, conn, sql); + const byName = new Map(); + for (const row of rows) { + const name = row.name ?? row.viewname ?? row.TABLE_NAME ?? row.view_name; + if (!name) continue; + const def = row.definition ?? row.VIEW_DEFINITION ?? row.sql ?? row.create_table_query ?? ""; + byName.set(String(name), extractViewMetadata(String(def ?? ""), dbType)); + } + + // Ensure any view reported by listTables is included even if system catalog omitted its body + for (const v of viewTables) { + if (!byName.has(v.name)) { + byName.set(v.name, { body: "" }); + } + } + + return Array.from(byName.entries()).map(([name, meta]) => ({ + name, + definition: meta.body, + ...(meta.columns ? { columns: meta.columns } : {}), + })); +} + +function mapRawColumn(col: any) { + return { + name: col.name, + type: col.type, + nullable: !col.not_nullable, + isPrimaryKey: col.is_primary_key === true, + isForeignKey: col.is_foreign_key === true, + defaultValue: col.default_value || null, + isUnique: col.is_unique === true, + isSerial: col.is_serial === true, + checkConstraint: col.check_constraint || null, + comment: col.comment || null, + maxLength: col.max_length || null, + ordinalPosition: col.ordinal_position || 0, + }; +} + +/** + * Introspect a live database connection and return its CanonicalSchemaAST. + */ +export async function introspectLiveCanonicalAST( + dbService: DatabaseService, + _queryExecutor: QueryExecutor, + databaseId: string, +): Promise { + return dbService.withConnection(databaseId, async (conn, _db, dbType) => { + 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") { + let idxRes; + try { + idxRes = await mongoConnector.listIndexes(conn as any, { collection: name }); + } catch (err: any) { + throw Object.assign( + new Error( + `Failed to introspect indexes for MongoDB collection '${name}': ${err?.message || String(err)}`, + ), + { cause: err }, + ); + } + indexes = idxRes.indexes.map((idx) => ({ + name: idx.name, + key: idx.key, + unique: idx.unique, + sparse: idx.sparse, + expireAfterSeconds: idx.expireAfterSeconds, + partialFilterExpression: idx.partialFilterExpression ?? null, + })); + } + 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 connector = getConnector(dbType) as any; + const schemas: Array<{ name: string }> = await connector.listSchemas(conn); + + const settledSchemas = await Promise.allSettled( + schemas.map(async (schema) => { + const tablesInSchema = await connector.listTables(conn, schema.name); + const batchData = await connector.getSchemaMetadataBatch(conn, schema.name); + if (dbType === DBType.CLICKHOUSE) { + if ( + batchData && + "indexMetadataError" in batchData && + batchData.indexMetadataError != null + ) { + const err = batchData.indexMetadataError; + const msg = err instanceof Error ? err.message : String(err); + throw Object.assign( + new Error(`Incomplete ClickHouse index metadata for schema '${schema.name}': ${msg}`), + { cause: err }, + ); + } + if ( + batchData && + "primaryKeyMetadataError" in batchData && + batchData.primaryKeyMetadataError != null + ) { + const err = batchData.primaryKeyMetadataError; + const msg = err instanceof Error ? err.message : String(err); + throw Object.assign( + new Error( + `Incomplete ClickHouse primary key metadata for schema '${schema.name}': ${msg}`, + ), + { cause: err }, + ); + } + const rawColErrors = batchData?.columnMetadataErrors; + const colErrorEntries: Array<[string, unknown]> = + rawColErrors instanceof Map + ? Array.from(rawColErrors.entries()) + : Array.isArray(rawColErrors) + ? rawColErrors.map((e: any, idx: number) => [ + String(e?.table ?? e?.tableName ?? idx), + e?.error ?? e, + ]) + : rawColErrors && typeof rawColErrors === "object" + ? Object.entries(rawColErrors) + : []; + if (colErrorEntries.length > 0) { + const tableList = colErrorEntries.map(([tbl]) => tbl).join(", "); + const firstErr = colErrorEntries[0][1]; + const firstMsg = firstErr instanceof Error ? firstErr.message : String(firstErr); + throw Object.assign( + new Error( + `Incomplete ClickHouse column metadata for schema '${schema.name}' (tables: ${tableList}): ${firstMsg}`, + ), + { cause: firstErr }, + ); + } + if ( + batchData && + "columnMetadataError" in batchData && + batchData.columnMetadataError != null + ) { + const err = batchData.columnMetadataError; + const msg = err instanceof Error ? err.message : String(err); + throw Object.assign( + new Error( + `Incomplete ClickHouse column metadata for schema '${schema.name}': ${msg}`, + ), + { cause: err }, + ); + } + } + const views = await introspectSchemaViews( + connector, + conn, + dbType, + schema.name, + tablesInSchema, + ); + + const finalTables = tablesInSchema.map((table: any) => { + const tableData = batchData.tables.get(table.name); + if ( + dbType === DBType.CLICKHOUSE && + String(table.type || "").toUpperCase() !== "VIEW" && + (!tableData || tableData.columns.length === 0) + ) { + throw new Error( + `Incomplete ClickHouse metadata for table '${schema.name}.${table.name}': missing column definitions`, + ); + } + const primaryKeys = + dbType === DBType.CLICKHOUSE && tableData?.reportedPrimaryKeys !== undefined + ? tableData.reportedPrimaryKeys + : (tableData?.primaryKeys ?? []); + const primaryKeyColumns = primaryKeys + .map((pk: any) => + typeof pk === "string" + ? pk + : String(pk?.column_name ?? pk?.columnName ?? pk?.name ?? ""), + ) + .filter(Boolean); + return { + name: table.name, + type: table.type, + columns: tableData?.columns.map(mapRawColumn) ?? [], + primaryKeys, + ...(primaryKeyColumns.length > 0 ? { primaryKeyColumns } : {}), + foreignKeys: tableData?.foreignKeys ?? [], + indexes: tableData?.indexes ?? [], + uniqueConstraints: tableData?.uniqueConstraints ?? [], + checkConstraints: tableData?.checkConstraints ?? [], + }; + }); + + const extra: Record = {}; + if (batchData.enumTypes !== undefined) extra.enumTypes = batchData.enumTypes; + if (batchData.sequences !== undefined) extra.sequences = batchData.sequences; + if (batchData.enumColumns !== undefined) extra.enumColumns = batchData.enumColumns; + if (batchData.autoIncrements !== undefined) extra.autoIncrements = batchData.autoIncrements; + + return { name: schema.name, tables: finalTables, views, ...extra }; + }), + ); + + const rejections = settledSchemas.filter( + (result): result is PromiseRejectedResult => result.status === "rejected", + ); + const rejected = + (typeof dbService.isFatalConnectionError === "function" + ? rejections.find((result) => dbService.isFatalConnectionError(result.reason)) + : undefined) ?? rejections[0]; + if (rejected) { + throw rejected.reason; + } + + const finalSchemas = settledSchemas.map( + (result) => (result as PromiseFulfilledResult>).value, + ); + + return normalizeLiveSqlSchemas({ schemas: finalSchemas }, dbType); + }); +} diff --git a/bridge/src/services/migrationGenerator.ts b/bridge/src/services/migrationGenerator.ts new file mode 100644 index 00000000..44da94f4 --- /dev/null +++ b/bridge/src/services/migrationGenerator.ts @@ -0,0 +1,2462 @@ +/** + * 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, + CanonicalSchema, + CanonicalSchemaAST, + CanonicalTable, + CanonicalView, + SchemaDiffItem, + SchemaDiffResult, +} from "../types/schemaDiff"; +import type { MongoMigrationManifest, MongoMigrationStep } from "../types/mongoMigration"; +import { diffSchemas } from "./schemaDiffEngine"; +import { generateMigrationVersion } from "../utils/migrationGenerator"; + +export class UnsupportedMigrationError extends Error { + readonly code = "UNSUPPORTED_OPERATION"; + + constructor(message: string) { + super(message); + this.name = "UnsupportedMigrationError"; + } +} + +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, + omitInlinePrimaryKey = false, +): 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 && !omitInlinePrimaryKey && 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, + omitFkNames?: Set, +): string { + const tableRef = qualifyName(schema, overrideTableName || table.name, dialect); + const explicitPkCols = (table as CanonicalTable & { primaryKeyColumns?: string[] }) + .primaryKeyColumns; + const colNames = new Set(table.columns.map((c) => c.name)); + const validExplicitPkCols = Array.isArray(explicitPkCols) + ? explicitPkCols.filter((name) => colNames.has(name)) + : []; + const pkColNames = + validExplicitPkCols.length > 0 + ? validExplicitPkCols + : table.columns.filter((c) => c.isPrimaryKey).map((c) => c.name); + + if (dialect !== "clickhouse") { + const hasCompositePk = pkColNames.length > 1; + const defs = table.columns.map((c) => ` ${buildColumnDefinition(c, dialect, hasCompositePk)}`); + if (hasCompositePk) { + defs.push( + ` PRIMARY KEY (${pkColNames.map((name) => quoteIdent(name, dialect)).join(", ")})`, + ); + } + for (const chk of table.checks || []) { + defs.push(` CONSTRAINT ${quoteIdent(chk.name, dialect)} CHECK (${chk.expression})`); + } + for (const fk of table.foreignKeys || []) { + if (omitFkNames?.has(fk.name)) continue; + 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 defs = table.columns.map((c) => ` ${buildColumnDefinition(c, dialect)}`); + const pkCols = pkColNames.map((name) => quoteIdent(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 assertClickHouseIndexSupported(dialect: CanonicalDialect): void { + if (dialect === "clickhouse") { + throw new UnsupportedMigrationError( + "ClickHouse index migrations are not supported: ClickHouse data-skipping indexes require ALTER TABLE ... ADD/DROP INDEX with index type and granularity metadata.", + ); + } +} + +const SUPPORTED_PG_INDEX_METHODS = new Set(["btree", "hash", "gin", "gist", "spgist", "brin"]); + +function getUnsupportedSqlIndexReason( + idx: CanonicalIndex, + dialect: CanonicalDialect, +): string | null { + if (!idx.columns || idx.columns.length === 0) { + return "index has no simple column list"; + } + if (dialect === "postgresql") { + const method = idx.indexType?.trim().toLowerCase(); + if (method && !SUPPORTED_PG_INDEX_METHODS.has(method)) { + return `unsupported PostgreSQL access method '${idx.indexType}'`; + } + } + return null; +} + +function buildCreateIndexSql( + schema: string | undefined, + tableName: string, + idx: CanonicalIndex, + dialect: CanonicalDialect, + concurrent?: boolean, +): string { + assertClickHouseIndexSupported(dialect); + 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 method = idx.indexType?.trim().toLowerCase(); + let usingClause = ""; + if (dialect === "postgresql" && method && method !== "btree") { + if (!SUPPORTED_PG_INDEX_METHODS.has(method)) { + throw new UnsupportedMigrationError( + `PostgreSQL index '${idx.name}' uses unsupported access method '${idx.indexType}'.`, + ); + } + usingClause = ` USING ${method}`; + } + const whereClause = idx.partial ? ` WHERE ${idx.partial}` : ""; + return `CREATE ${uniqueStr}INDEX ${concurrentStr}${quoteIdent(idx.name, dialect)} ON ${tableRef}${usingClause} (${cols})${whereClause};`; +} + +/** + * Normalizes a view definition into its query body and optional explicit column list + * so full `CREATE VIEW ... () AS` DDL is not double-prefixed and preserves + * explicit view column names in both forward and rollback SQL. + */ +function extractViewSpec( + view: CanonicalView & { columns?: string[] }, + dialect: CanonicalDialect, +): { columnListClause: string; body: string } { + const trimmed = view.definition.trim().replace(/;+\s*$/, ""); + let extractedColumnList: string | undefined; + let body = trimmed; + + const prefixMatch = trimmed.match( + /^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(?:TEMP(?:ORARY)?\s+)?VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?/i, + ); + if (prefixMatch) { + let pos = prefixMatch[0].length; + + const skipWs = () => { + while (pos < trimmed.length && /\s/.test(trimmed[pos])) pos++; + }; + const skipIdent = (): boolean => { + skipWs(); + if (pos >= trimmed.length) return false; + const ch = trimmed[pos]; + if (ch === '"' || ch === "`") { + pos++; + while (pos < trimmed.length) { + if (trimmed[pos] === ch) { + if (trimmed[pos + 1] === ch) { + pos += 2; + continue; + } + pos++; + return true; + } + pos++; + } + return false; + } + if (ch === "[") { + const end = trimmed.indexOf("]", pos + 1); + if (end === -1) return false; + pos = end + 1; + return true; + } + const start = pos; + while (pos < trimmed.length && !/[\s.(]/.test(trimmed[pos])) pos++; + return pos > start; + }; + + if (skipIdent()) { + skipWs(); + if (trimmed[pos] === ".") { + pos++; + skipIdent(); + } + skipWs(); + if (trimmed[pos] === "(") { + const openPos = pos; + pos++; + let depth = 1; + while (pos < trimmed.length && depth > 0) { + const c = trimmed[pos]; + if (c === '"' || c === "`" || c === "'") { + pos++; + while (pos < trimmed.length) { + if (trimmed[pos] === c) { + if (trimmed[pos + 1] === c) { + pos += 2; + continue; + } + pos++; + break; + } + pos++; + } + continue; + } + if (c === "[") { + const end = trimmed.indexOf("]", pos + 1); + pos = end === -1 ? trimmed.length : end + 1; + continue; + } + if (c === "(") depth++; + else if (c === ")") depth--; + pos++; + } + if (depth === 0) { + const inner = trimmed.slice(openPos + 1, pos - 1).trim(); + if (inner) { + extractedColumnList = `(${inner})`; + } + } + } + skipWs(); + const asMatch = trimmed.slice(pos).match(/^AS\s+([\s\S]+)$/i); + if (asMatch) { + body = asMatch[1].trim().replace(/;+\s*$/, ""); + } else { + extractedColumnList = undefined; + } + } + } + + let columnListClause = ""; + if (Array.isArray(view.columns) && view.columns.length > 0) { + columnListClause = ` (${view.columns.map((c) => quoteIdent(c, dialect)).join(", ")})`; + } else if (extractedColumnList) { + columnListClause = ` ${extractedColumnList}`; + } + + return { columnListClause, body }; +} + +function buildDropIndexSql( + schema: string | undefined, + tableName: string, + indexName: string, + dialect: CanonicalDialect, + concurrent?: boolean, +): string { + assertClickHouseIndexSupported(dialect); + 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); +} + +type SqliteTriggerDef = { name: string; sql?: string }; +type CanonicalTableWithTriggers = CanonicalTable & { triggers?: SqliteTriggerDef[] }; + +interface SqliteToken { + kind: "word" | "quotedIdent" | "other"; + value: string; +} + +/** + * Tokenizes a SQLite trigger DDL statement and extracts identifier tokens that may + * reference table columns, throwing `UnsupportedMigrationError` if the trigger + * syntax cannot be reliably verified (e.g. unclosed quotes/comments or missing BEGIN..END). + */ +function extractSqliteTriggerReferencedIdentifiers(sql: string, triggerName: string): Set { + const tokens: SqliteToken[] = []; + let i = 0; + + while (i < sql.length) { + const ch = sql[i]; + if (/\s/.test(ch)) { + i++; + continue; + } + // Line comment + if (ch === "-" && sql[i + 1] === "-") { + const nl = sql.indexOf("\n", i + 2); + i = nl === -1 ? sql.length : nl + 1; + continue; + } + // Block comment + if (ch === "/" && sql[i + 1] === "*") { + const end = sql.indexOf("*/", i + 2); + if (end === -1) { + throw new UnsupportedMigrationError( + `SQLite trigger '${triggerName}' has an unterminated block comment and cannot be verified.`, + ); + } + i = end + 2; + continue; + } + // Blob literal x'...' + if ((ch === "x" || ch === "X") && sql[i + 1] === "'") { + i += 2; + let closed = false; + while (i < sql.length) { + if (sql[i] === "'") { + i++; + closed = true; + break; + } + i++; + } + if (!closed) { + throw new UnsupportedMigrationError( + `SQLite trigger '${triggerName}' has an unterminated blob literal and cannot be verified.`, + ); + } + tokens.push({ kind: "other", value: "" }); + continue; + } + // Single-quoted string literal (or qualified identifier in SQLite such as NEW.'qty$') + if (ch === "'") { + i++; + let text = ""; + let closed = false; + while (i < sql.length) { + if (sql[i] === "'") { + if (sql[i + 1] === "'") { + text += "'"; + i += 2; + continue; + } + i++; + closed = true; + break; + } + text += sql[i]; + i++; + } + if (!closed) { + throw new UnsupportedMigrationError( + `SQLite trigger '${triggerName}' has an unterminated string literal and cannot be verified.`, + ); + } + const prevTok = tokens[tokens.length - 1]; + const isQualifiedIdent = prevTok?.kind === "other" && prevTok.value === "."; + tokens.push( + isQualifiedIdent ? { kind: "quotedIdent", value: text } : { kind: "other", value: "" }, + ); + continue; + } + // Double-quoted or backtick-quoted identifier + if (ch === '"' || ch === "`") { + const quote = ch; + i++; + let ident = ""; + let closed = false; + while (i < sql.length) { + if (sql[i] === quote) { + if (sql[i + 1] === quote) { + ident += quote; + i += 2; + continue; + } + i++; + closed = true; + break; + } + ident += sql[i]; + i++; + } + if (!closed) { + throw new UnsupportedMigrationError( + `SQLite trigger '${triggerName}' has an unterminated quoted identifier and cannot be verified.`, + ); + } + tokens.push({ kind: "quotedIdent", value: ident }); + continue; + } + // Bracketed identifier [...] + if (ch === "[") { + const end = sql.indexOf("]", i + 1); + if (end === -1) { + throw new UnsupportedMigrationError( + `SQLite trigger '${triggerName}' has an unterminated bracketed identifier and cannot be verified.`, + ); + } + tokens.push({ kind: "quotedIdent", value: sql.slice(i + 1, end) }); + i = end + 1; + continue; + } + // Unquoted identifier / keyword + if (/[A-Za-z_\x80-\uffff]/.test(ch)) { + let end = i + 1; + while (end < sql.length && /[A-Za-z0-9_$\x80-\uffff]/.test(sql[end])) { + end++; + } + tokens.push({ kind: "word", value: sql.slice(i, end) }); + i = end; + continue; + } + // Numeric literal + if (/[0-9]/.test(ch)) { + let end = i + 1; + while (end < sql.length && /[0-9a-fA-FxX._+-]/.test(sql[end])) { + if ((sql[end] === "+" || sql[end] === "-") && !/[eE]/.test(sql[end - 1])) break; + end++; + } + tokens.push({ kind: "other", value: sql.slice(i, end) }); + i = end; + continue; + } + tokens.push({ kind: "other", value: ch }); + i++; + } + + const upperWord = (idx: number) => + tokens[idx]?.kind === "word" ? tokens[idx].value.toUpperCase() : ""; + + // Verify CREATE [TEMP|TEMPORARY] TRIGGER ... BEGIN ... END structure + let pos = 0; + if (upperWord(pos) !== "CREATE") { + throw new UnsupportedMigrationError( + `SQLite trigger '${triggerName}' does not start with CREATE TRIGGER and cannot be verified.`, + ); + } + pos++; + if (upperWord(pos) === "TEMP" || upperWord(pos) === "TEMPORARY") pos++; + if (upperWord(pos) !== "TRIGGER") { + throw new UnsupportedMigrationError( + `SQLite trigger '${triggerName}' is not a valid CREATE TRIGGER statement and cannot be verified.`, + ); + } + pos++; + if (upperWord(pos) === "IF" && upperWord(pos + 1) === "NOT" && upperWord(pos + 2) === "EXISTS") { + pos += 3; + } + // Skip [schema.]trigger_name + if (pos >= tokens.length) { + throw new UnsupportedMigrationError( + `SQLite trigger '${triggerName}' is incomplete and cannot be verified.`, + ); + } + pos++; + if (tokens[pos]?.kind === "other" && tokens[pos].value === ".") { + pos += 2; + } + + const beginIdx = tokens.findIndex( + (t, idx) => idx >= pos && t.kind === "word" && t.value.toUpperCase() === "BEGIN", + ); + const lastNonSemi = + tokens[tokens.length - 1]?.kind === "other" && tokens[tokens.length - 1].value === ";" + ? tokens.length - 2 + : tokens.length - 1; + if (beginIdx === -1 || lastNonSemi <= beginIdx || upperWord(lastNonSemi) !== "END") { + throw new UnsupportedMigrationError( + `SQLite trigger '${triggerName}' is missing a valid BEGIN ... END body and cannot be verified.`, + ); + } + + // Find target table token after `ON` before `BEGIN` so `ON
` isn't treated as a column ref + let headerOnTableIdx = -1; + for (let idx = pos; idx < beginIdx; idx++) { + if (upperWord(idx) === "ON") { + if (idx + 1 < beginIdx) { + headerOnTableIdx = idx + 1; + if (tokens[idx + 2]?.kind === "other" && tokens[idx + 2].value === ".") { + headerOnTableIdx = idx + 3; + } + } + break; + } + } + + const identifiers = new Set(); + for (let idx = pos; idx <= lastNonSemi; idx++) { + if (idx === headerOnTableIdx) continue; + const tok = tokens[idx]; + if (tok.kind === "word" || tok.kind === "quotedIdent") { + identifiers.add(tok.value.toLowerCase()); + } + } + return identifiers; +} + +/** + * 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(), +): { sql: string; triggerWarning?: string } { + const tempName = `__relwave_new_${toTable.name}`; + const tempRef = quoteIdent(tempName, "sqlite"); + const origRef = quoteIdent(toTable.name, "sqlite"); + const fromRef = quoteIdent(fromTable.name, "sqlite"); + const fromCols = new Set(fromTable.columns.map((c) => c.name)); + + const targetColIdents: string[] = []; + const sourceColIdents: string[] = []; + const preservedCols = new Set(); + 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")); + preservedCols.add(col.name); + } else if (fromCols.has(col.name)) { + targetColIdents.push(quoteIdent(col.name, "sqlite")); + sourceColIdents.push(quoteIdent(col.name, "sqlite")); + preservedCols.add(col.name); + } + } + + // Validate triggers before emitting destructive rebuild statements + const triggers = (fromTable as CanonicalTableWithTriggers).triggers; + const preservedTriggers: string[] = []; + if (triggers && triggers.length > 0) { + const droppedCols = fromTable.columns + .map((c) => c.name) + .filter( + (name) => !preservedCols.has(name) && !Array.from(columnRenames.values()).includes(name), + ); + const droppedColsLower = droppedCols.map((c) => c.toLowerCase()); + for (const trig of triggers) { + if (!trig.sql || !trig.sql.trim()) { + throw new UnsupportedMigrationError( + `SQLite table rebuild for '${toTable.name}' cannot preserve trigger '${trig.name}' without its SQL definition.`, + ); + } + const referencedIdentifiers = extractSqliteTriggerReferencedIdentifiers(trig.sql, trig.name); + const referencesDropped = droppedColsLower.some((colLower) => + referencedIdentifiers.has(colLower), + ); + if (referencesDropped || columnRenames.size > 0) { + throw new UnsupportedMigrationError( + `SQLite table rebuild for '${toTable.name}' cannot automatically preserve trigger '${trig.name}' across column drops or renames.`, + ); + } + const trimmed = trig.sql.trim(); + preservedTriggers.push(trimmed.endsWith(";") ? trimmed : `${trimmed};`); + } + } + + let insertStmt: string; + if (targetColIdents.length > 0) { + insertStmt = `INSERT INTO ${tempRef} (${targetColIdents.join(", ")}) SELECT ${sourceColIdents.join(", ")} FROM ${fromRef};`; + } else { + // No columns map between source and target: preserve one defaulted row per source row if defaults permit. + const defaultCols: string[] = []; + const defaultExprs: string[] = []; + for (const col of toTable.columns) { + if (col.defaultValue !== null && col.defaultValue !== undefined) { + defaultCols.push(quoteIdent(col.name, "sqlite")); + defaultExprs.push(col.defaultValue); + } else if (col.nullable || (col.isPrimaryKey && /^integer$/i.test(col.type.trim()))) { + defaultCols.push(quoteIdent(col.name, "sqlite")); + defaultExprs.push("NULL"); + } else { + throw new UnsupportedMigrationError( + `SQLite table rebuild for '${toTable.name}' cannot preserve existing rows: no columns map from '${fromTable.name}' and target column '${col.name}' is NOT NULL without a default.`, + ); + } + } + if (defaultCols.length === 0) { + throw new UnsupportedMigrationError( + `SQLite table rebuild for '${toTable.name}' cannot preserve existing rows: target table has no columns.`, + ); + } + insertStmt = `INSERT INTO ${tempRef} (${defaultCols.join(", ")}) SELECT ${defaultExprs.join(", ")} FROM ${fromRef};`; + } + + // Note: RelWave's SQLite migration runner checks for `-- @relwave-sqlite-rebuild` and disables + // PRAGMA foreign_keys before opening db.transaction(), executes PRAGMA foreign_key_check inside + // the transaction, and restores the prior foreign_keys setting afterwards. Keep these pragmas for + // standalone CLI runs too. + const lines: string[] = [ + "-- @relwave-sqlite-rebuild", + "PRAGMA foreign_keys=OFF;", + buildCreateTableSql(schema, toTable, "sqlite", tempName), + insertStmt, + `DROP TABLE ${fromRef};`, + `ALTER TABLE ${tempRef} RENAME TO ${origRef};`, + ]; + + for (const idx of toTable.indexes || []) { + lines.push(buildCreateIndexSql(schema, toTable.name, idx, "sqlite")); + } + + let triggerWarning: string | undefined; + if (preservedTriggers.length > 0) { + lines.push(...preservedTriggers); + } else if (!triggers) { + triggerWarning = `SQLite table rebuild for '${toTable.name}' drops any triggers attached to the table; verify and recreate triggers manually if present.`; + lines.push( + `-- NOTE: SQLite table rebuilds drop any triggers attached to ${origRef}; verify and recreate triggers manually if present.`, + ); + } + + lines.push("PRAGMA foreign_key_check;"); + lines.push("-- Verify PRAGMA foreign_key_check returns no rows before committing."); + lines.push("PRAGMA foreign_keys=ON;"); + return { sql: lines.join("\n"), triggerWarning }; +} + +function buildColumnModifyStatements( + tableRef: string, + before: CanonicalColumn, + after: CanonicalColumn, + dialect: CanonicalDialect, +): string[] { + if (dialect === "sqlite") { + throw new UnsupportedMigrationError( + `SQLite does not support ALTER/MODIFY COLUMN on ${tableRef}; a table rebuild is required.`, + ); + } + 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", +]); + +const SQL_PHASE_ORDER: Record = { + SCHEMA_ADDED: 0, + ENUM_ADDED: 1, + ENUM_MODIFIED: 1, + VIEW_DROPPED: 2, + FK_DROPPED: 3, + CHECK_DROPPED: 4, + INDEX_DROPPED: 4, + TABLE_DROPPED: 5, + TABLE_RENAME: 5.5, + COLUMN_DROPPED: 6, + COLUMN_MODIFIED: 6, + COLUMN_ADDED: 6, + COLUMN_RENAME: 6, + SQLITE_REBUILD: 6, + TABLE_ADDED: 7, + CHECK_ADDED: 8, + CHECK_MODIFIED: 8, + INDEX_ADDED: 8, + INDEX_MODIFIED: 8, + FK_ADDED: 8.5, + VIEW_ADDED: 9, + VIEW_MODIFIED: 9, + ENUM_DROPPED: 10, + SCHEMA_DROPPED: 11, +}; + +function tableDependencyKey(schema: string | undefined, table: string): string { + return JSON.stringify([schema || "", table]); +} + +function hasColumnResidualChange(before: CanonicalColumn, after: CanonicalColumn): boolean { + return ( + before.type !== after.type || + before.nullable !== after.nullable || + (before.defaultValue ?? null) !== (after.defaultValue ?? null) || + before.isPrimaryKey !== after.isPrimaryKey || + before.isUnique !== after.isUnique + ); +} + +function splitFkModifiedItem(item: SchemaDiffItem): SchemaDiffItem[] { + if (item.type !== "FK_MODIFIED") return [item]; + return [ + { + ...item, + id: `${item.id}:drop`, + type: "FK_DROPPED", + after: undefined, + }, + { + ...item, + id: `${item.id}:add`, + type: "FK_ADDED", + before: undefined, + }, + ]; +} + +function sortTableAddedByDependencies(items: SchemaDiffItem[]): { + ordered: SchemaDiffItem[]; + cycleKeys: Set; +} { + const keyToItem = new Map(); + const keyOrder: string[] = []; + for (const item of items) { + const tbl = item.after as CanonicalTable | undefined; + const key = tableDependencyKey(item.schema, tbl?.name || item.tableOrCollection); + keyToItem.set(key, item); + keyOrder.push(key); + } + + const deps = new Map>(); + const dependents = new Map(); + for (const key of keyOrder) { + deps.set(key, new Set()); + dependents.set(key, []); + } + + for (const key of keyOrder) { + const item = keyToItem.get(key)!; + const tbl = item.after as CanonicalTable | undefined; + for (const fk of tbl?.foreignKeys || []) { + const targetKey = tableDependencyKey(fk.referencedSchema || item.schema, fk.referencedTable); + if (targetKey !== key && keyToItem.has(targetKey)) { + if (!deps.get(key)!.has(targetKey)) { + deps.get(key)!.add(targetKey); + dependents.get(targetKey)!.push(key); + } + } + } + } + + const queue: string[] = keyOrder.filter((k) => deps.get(k)!.size === 0); + const orderedKeys: string[] = []; + const visited = new Set(); + + while (queue.length > 0) { + const cur = queue.shift()!; + if (visited.has(cur)) continue; + visited.add(cur); + orderedKeys.push(cur); + for (const dep of dependents.get(cur) || []) { + deps.get(dep)!.delete(cur); + if (deps.get(dep)!.size === 0) { + queue.push(dep); + } + } + } + + const cycleKeys = new Set(); + for (const key of keyOrder) { + if (!visited.has(key)) { + cycleKeys.add(key); + orderedKeys.push(key); + } + } + + return { + ordered: orderedKeys.map((k) => keyToItem.get(k)!), + cycleKeys, + }; +} + +function sortTableDroppedByDependencies(items: SchemaDiffItem[]): { + ordered: SchemaDiffItem[]; + cycleKeys: Set; +} { + const keyToItem = new Map(); + const keyOrder: string[] = []; + for (const item of items) { + const tbl = item.before as CanonicalTable | undefined; + const key = tableDependencyKey(item.schema, tbl?.name || item.tableOrCollection); + keyToItem.set(key, item); + keyOrder.push(key); + } + + // Child (referencing) table must be dropped before parent (referenced) table. + const deps = new Map>(); + const dependents = new Map(); + for (const key of keyOrder) { + deps.set(key, new Set()); + dependents.set(key, []); + } + + for (const key of keyOrder) { + const item = keyToItem.get(key)!; + const tbl = item.before as CanonicalTable | undefined; + for (const fk of tbl?.foreignKeys || []) { + const parentKey = tableDependencyKey(fk.referencedSchema || item.schema, fk.referencedTable); + if (parentKey !== key && keyToItem.has(parentKey)) { + if (!deps.get(parentKey)!.has(key)) { + deps.get(parentKey)!.add(key); + dependents.get(key)!.push(parentKey); + } + } + } + } + + const queue: string[] = keyOrder.filter((k) => deps.get(k)!.size === 0); + const orderedKeys: string[] = []; + const visited = new Set(); + + while (queue.length > 0) { + const cur = queue.shift()!; + if (visited.has(cur)) continue; + visited.add(cur); + orderedKeys.push(cur); + for (const dep of dependents.get(cur) || []) { + deps.get(dep)!.delete(cur); + if (deps.get(dep)!.size === 0) { + queue.push(dep); + } + } + } + + const cycleKeys = new Set(); + for (const key of keyOrder) { + if (!visited.has(key)) { + cycleKeys.add(key); + orderedKeys.push(key); + } + } + + return { + ordered: orderedKeys.map((k) => keyToItem.get(k)!), + cycleKeys, + }; +} + +function expandSchemaAddedItems(items: SchemaDiffItem[]): SchemaDiffItem[] { + const expanded: SchemaDiffItem[] = []; + for (const item of items) { + expanded.push(item); + if (item.type !== "SCHEMA_ADDED" || !item.after) continue; + const schemaObj = item.after as CanonicalSchema; + const schemaName = schemaObj.name || item.tableOrCollection; + + for (const en of schemaObj.enums || []) { + expanded.push({ + id: `${item.id}:enum:${en.name}`, + type: "ENUM_ADDED", + severity: "safe", + schema: schemaName, + tableOrCollection: en.name, + after: en, + details: `Add enum ${schemaName}.${en.name}`, + }); + } + for (const tbl of schemaObj.tables || []) { + expanded.push({ + id: `${item.id}:table:${tbl.name}`, + type: "TABLE_ADDED", + severity: "safe", + schema: schemaName, + tableOrCollection: tbl.name, + after: tbl, + details: `Add table ${schemaName}.${tbl.name}`, + }); + } + for (const view of schemaObj.views || []) { + expanded.push({ + id: `${item.id}:view:${view.name}`, + type: "VIEW_ADDED", + severity: "safe", + schema: schemaName, + tableOrCollection: view.name, + after: view, + details: `Add view ${schemaName}.${view.name}`, + }); + } + } + return expanded; +} + +function buildSqlStatementsFromDiff( + diff: SchemaDiffResult, + sourceAst: CanonicalSchemaAST, + targetAst: CanonicalSchemaAST, + dialect: CanonicalDialect, + options: GenerateMigrationOptions, +): { + upStmts: string[]; + downStmts: string[]; + warnings: string[]; + hasDestructive: boolean; +} { + 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, + ); + + // Scheduled actions executed in strict SQL_PHASE_ORDER + const scheduledPhaseActions: Array<{ phase: number; seq: number; emit: () => void }> = []; + let actionSeq = 0; + const scheduleAction = (phase: number, emit: () => void) => { + scheduledPhaseActions.push({ phase, seq: actionSeq++, emit }); + }; + + // Residual items emitted by accepted table renames, routed into the outer phase pipeline + const tableRenameResidualItems: SchemaDiffItem[] = []; + + for (const { drop, add } of tableRenames) { + const oldRef = qualifyName(drop.schema, drop.tableOrCollection, dialect); + const newRef = qualifyName(add.schema, add.tableOrCollection, dialect); + scheduleAction(SQL_PHASE_ORDER.TABLE_RENAME, () => { + 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)};`, + ); + } + }); + + const oldTable = drop.before as CanonicalTable | undefined; + const newTable = add.after as CanonicalTable | undefined; + if (oldTable && newTable) { + const schemaName = add.schema || drop.schema || "public"; + const renamedOldTable: CanonicalTable = { ...oldTable, name: newTable.name }; + const residualSource: CanonicalSchemaAST = { + dialect, + schemas: [{ name: schemaName, tables: [renamedOldTable], enums: [], views: [] }], + }; + const residualTarget: CanonicalSchemaAST = { + dialect, + schemas: [{ name: schemaName, tables: [newTable], enums: [], views: [] }], + }; + const residualDiff = diffSchemas(residualSource, residualTarget, { detectRenames: false }); + if (residualDiff.items.length > 0) { + if (dialect === "sqlite") { + scheduleAction(SQL_PHASE_ORDER.SQLITE_REBUILD, () => { + const residual = buildSqlStatementsFromDiff( + residualDiff, + residualSource, + residualTarget, + dialect, + { concurrentIndexes: options.concurrentIndexes }, + ); + upStmts.push(...residual.upStmts); + downStmts.push(...residual.downStmts); + warnings.push(...residual.warnings); + if (residual.hasDestructive) hasDestructive = true; + }); + } else { + for (const rawItem of residualDiff.items) { + for (const splitItem of splitFkModifiedItem(rawItem)) { + const phase = SQL_PHASE_ORDER[splitItem.type] ?? 50; + if (phase < SQL_PHASE_ORDER.TABLE_DROPPED) { + tableRenameResidualItems.push({ + ...splitItem, + schema: drop.schema, + tableOrCollection: drop.tableOrCollection, + }); + } else { + tableRenameResidualItems.push({ + ...splitItem, + schema: add.schema, + tableOrCollection: add.tableOrCollection, + }); + } + } + } + } + } + } + } + + // SQLite: group table-rebuild triggers (and column renames with residual changes) by table + const sqliteRebuildTables = new Map(); + if (dialect === "sqlite") { + for (const item of diff.items) { + if (consumedIds.has(item.id)) continue; + if (SQLITE_REBUILD_TRIGGER_TYPES.has(item.type)) { + const key = tableDependencyKey(item.schema, item.tableOrCollection); + if (!sqliteRebuildTables.has(key)) { + sqliteRebuildTables.set(key, { + schema: item.schema || "", + tableName: item.tableOrCollection, + }); + } + } + } + + for (const { drop, add } of columnRenames) { + const beforeCol = drop.before as CanonicalColumn | undefined; + const afterCol = add.after as CanonicalColumn | undefined; + if (beforeCol && afterCol && hasColumnResidualChange(beforeCol, afterCol)) { + const key = tableDependencyKey(drop.schema, drop.tableOrCollection); + if (!sqliteRebuildTables.has(key)) { + sqliteRebuildTables.set(key, { + schema: drop.schema || "", + tableName: drop.tableOrCollection, + }); + } + } + } + + for (const { schema, tableName } of sqliteRebuildTables.values()) { + 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"), + ); + + for (const i of tableItems) { + consumedIds.add(i.id); + } + + 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); + } + } + + scheduleAction(SQL_PHASE_ORDER.SQLITE_REBUILD, () => { + 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 (upRebuild.triggerWarning) { + warnings.push(upRebuild.triggerWarning); + } + + 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.sql}`); + } else { + upStmts.push(upRebuild.sql); + } + downStmts.push(downRebuild.sql); + }); + } + } + + // Remaining column renames (non-rebuilt tables), plus residual column modifications + for (const { drop, add } of columnRenames) { + const key = tableDependencyKey(drop.schema, drop.tableOrCollection); + if (sqliteRebuildTables.has(key)) continue; + scheduleAction(SQL_PHASE_ORDER.COLUMN_RENAME, () => { + 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};`); + + const beforeCol = drop.before as CanonicalColumn | undefined; + const afterCol = add.after as CanonicalColumn | undefined; + if (beforeCol && afterCol) { + const normalizedBefore: CanonicalColumn = { ...beforeCol, name: afterCol.name }; + if (dialect === "sqlite") { + if (hasColumnResidualChange(normalizedBefore, afterCol)) { + throw new UnsupportedMigrationError( + `SQLite column rename on '${drop.tableOrCollection}.${afterCol.name}' with residual column changes requires a table rebuild.`, + ); + } + return; + } + const upMod = buildColumnModifyStatements(tableRef, normalizedBefore, afterCol, dialect); + const downMod = buildColumnModifyStatements(tableRef, afterCol, normalizedBefore, dialect); + if (normalizedBefore.isPrimaryKey !== afterCol.isPrimaryKey) { + const msg = `Primary key change on '${drop.tableOrCollection}.${afterCol.name}' requires manual SQL.`; + warnings.push(msg); + upMod.push( + `-- WARNING: Unsupported automatic primary-key change on ${tableRef}.${newCol}; manual SQL required.`, + ); + downMod.push( + `-- WARNING: Unsupported automatic primary-key change on ${tableRef}.${newCol}; manual SQL required.`, + ); + } + if (upMod.length > 0) upStmts.push(upMod.join("\n")); + if (downMod.length > 0) downStmts.push(downMod.join("\n")); + } + }); + } + + const rawRemainingItems = expandSchemaAddedItems( + diff.items.filter((item) => !consumedIds.has(item.id)), + ); + const remainingItems: SchemaDiffItem[] = []; + for (const item of rawRemainingItems) { + for (const splitItem of splitFkModifiedItem(item)) { + remainingItems.push(splitItem); + } + } + remainingItems.push(...tableRenameResidualItems); + + // Order remaining items by dependency phase, with topological sorting for TABLE_ADDED & TABLE_DROPPED + const rawTableAdded = remainingItems.filter((i) => i.type === "TABLE_ADDED"); + const rawTableDropped = remainingItems.filter((i) => i.type === "TABLE_DROPPED"); + const { ordered: sortedTableAdded, cycleKeys } = sortTableAddedByDependencies(rawTableAdded); + const { ordered: sortedTableDropped, cycleKeys: dropCycleKeys } = + sortTableDroppedByDependencies(rawTableDropped); + + const dropCycleOmitFkNames = new Map>(); + if (dropCycleKeys.size > 0 && dialect !== "sqlite" && dialect !== "clickhouse") { + for (const item of sortedTableDropped) { + const before = item.before as CanonicalTable | undefined; + if (!before) continue; + const key = tableDependencyKey(item.schema, before.name || item.tableOrCollection); + if (!dropCycleKeys.has(key)) continue; + const omitNames = new Set(); + for (const fk of before.foreignKeys || []) { + const targetKey = tableDependencyKey( + fk.referencedSchema || item.schema, + fk.referencedTable, + ); + if (targetKey !== key && dropCycleKeys.has(targetKey)) { + omitNames.add(fk.name); + scheduleAction(SQL_PHASE_ORDER.TABLE_DROPPED, () => { + upStmts.push(buildDropFkSql(item.schema, item.tableOrCollection, fk.name, dialect)); + downStmts.push(buildAddFkSql(item.schema, item.tableOrCollection, fk, dialect)); + }); + } + } + if (omitNames.size > 0) { + dropCycleOmitFkNames.set(key, omitNames); + } + } + } + + const deferredCycleFks: Array<{ schema?: string; tableName: string; fk: CanonicalForeignKey }> = + []; + const deferredPostIndexFks: Array<{ + schema?: string; + tableName: string; + fk: CanonicalForeignKey; + }> = []; + + const normalizedColSetKey = (cols: string[]) => JSON.stringify([...cols].sort()); + const addedTableKeys = new Set( + rawTableAdded.map((item) => { + const tbl = item.after as CanonicalTable | undefined; + return tableDependencyKey(item.schema, tbl?.name || item.tableOrCollection); + }), + ); + + const newUniqueIndexSpecsByTable = new Map>(); + for (const item of remainingItems) { + if (item.type !== "INDEX_ADDED" && item.type !== "INDEX_MODIFIED") continue; + const afterIdx = item.after as CanonicalIndex | undefined; + if (!afterIdx?.unique || afterIdx.partial || !afterIdx.columns?.length) continue; + const tblKey = tableDependencyKey(item.schema, item.tableOrCollection); + if (!newUniqueIndexSpecsByTable.has(tblKey)) { + newUniqueIndexSpecsByTable.set(tblKey, new Map()); + } + const byCols = newUniqueIndexSpecsByTable.get(tblKey)!; + const colKey = normalizedColSetKey(afterIdx.columns); + if (!byCols.has(colKey)) { + byCols.set(colKey, []); + } + byCols.get(colKey)!.push(item); + } + + const hasExistingUniqueKeyInSource = ( + schemaName: string | undefined, + tableName: string, + cols: string[], + ): boolean => { + const srcTable = findTableInAst(sourceAst, schemaName, tableName); + if (!srcTable) return false; + const targetColsKey = normalizedColSetKey(cols); + const pkCols = + Array.isArray(srcTable.primaryKeyColumns) && srcTable.primaryKeyColumns.length > 0 + ? srcTable.primaryKeyColumns + : srcTable.columns.filter((c) => c.isPrimaryKey).map((c) => c.name); + if (pkCols.length > 0 && normalizedColSetKey(pkCols) === targetColsKey) { + return true; + } + if (cols.length === 1 && srcTable.columns.some((c) => c.name === cols[0] && c.isUnique)) { + return true; + } + return (srcTable.indexes || []).some( + (idx) => idx.unique && !idx.partial && normalizedColSetKey(idx.columns) === targetColsKey, + ); + }; + + // For SQLite (which cannot defer FKs via ALTER TABLE ADD CONSTRAINT), schedule supporting + // unique indexes on existing tables before TABLE_ADDED. + const earlySqliteSupportingIndexIds = new Set(); + if (dialect === "sqlite") { + for (const item of sortedTableAdded) { + const table = item.after as CanonicalTable; + for (const fk of table.foreignKeys || []) { + const refSchema = fk.referencedSchema || item.schema; + const targetKey = tableDependencyKey(refSchema, fk.referencedTable); + if (addedTableKeys.has(targetKey)) continue; + if (hasExistingUniqueKeyInSource(refSchema, fk.referencedTable, fk.referencedColumns)) { + continue; + } + const matchingItems = newUniqueIndexSpecsByTable + .get(targetKey) + ?.get(normalizedColSetKey(fk.referencedColumns)); + if (matchingItems) { + for (const idxItem of matchingItems) { + earlySqliteSupportingIndexIds.add(idxItem.id); + } + } + } + } + } + + const buildRollbackIndexSql = ( + schema: string | undefined, + tableName: string, + idx: CanonicalIndex, + concurrentFlag: boolean, + ): string => { + const unsupportedReason = getUnsupportedSqlIndexReason(idx, dialect); + if (unsupportedReason) { + warnings.push( + `Rollback for dropped index '${idx.name}' on '${tableName}' requires manual recreation (${unsupportedReason}).`, + ); + return `-- MANUAL ROLLBACK REQUIRED: Cannot automatically recreate dropped index ${quoteIdent(idx.name, dialect)} (${unsupportedReason}).`; + } + try { + return buildCreateIndexSql(schema, tableName, idx, dialect, concurrentFlag); + } catch (err) { + if (err instanceof UnsupportedMigrationError) { + warnings.push( + `Rollback for dropped index '${idx.name}' on '${tableName}' requires manual recreation (${err.message}).`, + ); + return `-- MANUAL ROLLBACK REQUIRED: Cannot automatically recreate dropped index ${quoteIdent(idx.name, dialect)} (${err.message}).`; + } + throw err; + } + }; + + const emitDiffItem = (item: SchemaDiffItem) => { + 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); + const afterSet = new Set(after.values); + + const beforeCommon = before.values.filter((v) => afterSet.has(v)); + const afterCommon = after.values.filter((v) => beforeSet.has(v)); + if (beforeCommon.some((v, idx) => v !== afterCommon[idx])) { + const msg = `PostgreSQL cannot reorder existing enum values for ${after.name} (${beforeCommon.join(", ")} -> ${afterCommon.join(", ")}); manual migration required.`; + warnings.push(msg); + upStmts.push(`-- WARNING: ${msg}`); + } + + const currentValues = [...before.values]; + for (let i = 0; i < after.values.length; i++) { + const val = after.values[i]; + if (currentValues.includes(val)) continue; + const escVal = val.replace(/'/g, "''"); + + let prevAnchor: string | undefined; + for (let j = i - 1; j >= 0; j--) { + if (currentValues.includes(after.values[j])) { + prevAnchor = after.values[j]; + break; + } + } + let nextAnchor: string | undefined; + for (let j = i + 1; j < after.values.length; j++) { + if (currentValues.includes(after.values[j])) { + nextAnchor = after.values[j]; + break; + } + } + + if (prevAnchor !== undefined && nextAnchor !== undefined) { + upStmts.push( + `ALTER TYPE ${enumRef} ADD VALUE IF NOT EXISTS '${escVal}' AFTER '${prevAnchor.replace(/'/g, "''")}';`, + ); + currentValues.splice(currentValues.indexOf(prevAnchor) + 1, 0, val); + } else if (nextAnchor !== undefined) { + upStmts.push( + `ALTER TYPE ${enumRef} ADD VALUE IF NOT EXISTS '${escVal}' BEFORE '${nextAnchor.replace(/'/g, "''")}';`, + ); + currentValues.splice(currentValues.indexOf(nextAnchor), 0, val); + } else { + upStmts.push(`ALTER TYPE ${enumRef} ADD VALUE IF NOT EXISTS '${escVal}';`); + currentValues.push(val); + } + } + + const removed = before.values.filter((v) => !afterSet.has(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 key = tableDependencyKey(item.schema, table.name); + let omitFkNames: Set | undefined; + if (dialect !== "sqlite" && dialect !== "clickhouse") { + for (const fk of table.foreignKeys || []) { + const refSchema = fk.referencedSchema || item.schema; + const targetKey = tableDependencyKey(refSchema, fk.referencedTable); + const hasSupportingNewIdx = + Boolean( + newUniqueIndexSpecsByTable + .get(targetKey) + ?.has(normalizedColSetKey(fk.referencedColumns)), + ) && + !hasExistingUniqueKeyInSource(refSchema, fk.referencedTable, fk.referencedColumns); + if (hasSupportingNewIdx) { + if (!omitFkNames) omitFkNames = new Set(); + omitFkNames.add(fk.name); + deferredPostIndexFks.push({ schema: item.schema, tableName: table.name, fk }); + } else if (cycleKeys.has(key) && targetKey !== key && cycleKeys.has(targetKey)) { + if (!omitFkNames) omitFkNames = new Set(); + omitFkNames.add(fk.name); + deferredCycleFks.push({ schema: item.schema, tableName: table.name, fk }); + } + } + } + const createSql = buildCreateTableSql(item.schema, table, dialect, undefined, omitFkNames); + 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 key = tableDependencyKey(item.schema, before?.name || item.tableOrCollection); + const omitFkNames = dropCycleOmitFkNames.get(key); + const downSql = before + ? [ + buildCreateTableSql(item.schema, before, dialect, undefined, omitFkNames), + ...(before.indexes || []).map((idx) => + buildRollbackIndexSql(item.schema, before.name, idx, false), + ), + ].join("\n") + : `-- WARNING: Cannot automatically reverse DROP TABLE ${item.tableOrCollection}.`; + pushDestructive(item, `DROP TABLE IF EXISTS ${tableRef};`, downSql); + break; + } + case "TABLE_MODIFIED": { + const beforeMeta = item.before as { primaryKeyColumns?: unknown } | undefined; + const afterMeta = item.after as { primaryKeyColumns?: unknown } | undefined; + const isPkDiff = + item.objectName === "primaryKey" || + item.objectName === "primary_key" || + Array.isArray(beforeMeta?.primaryKeyColumns) || + Array.isArray(afterMeta?.primaryKeyColumns); + if (isPkDiff) { + const hasColPkWarning = diff.items.some( + (other) => + other.type === "COLUMN_MODIFIED" && + (other.schema || "") === (item.schema || "") && + other.tableOrCollection === item.tableOrCollection && + Boolean((other.before as CanonicalColumn | undefined)?.isPrimaryKey) !== + Boolean((other.after as CanonicalColumn | undefined)?.isPrimaryKey), + ); + if (!hasColPkWarning) { + throw new UnsupportedMigrationError( + `Primary key modification on '${item.tableOrCollection}' is not supported automatically; manual SQL is required.`, + ); + } + } + 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 upParts = buildColumnModifyStatements(tableRef, before, after, dialect); + const downParts = buildColumnModifyStatements(tableRef, after, before, dialect); + if (before.isPrimaryKey !== after.isPrimaryKey) { + const msg = `Primary key change on '${item.tableOrCollection}.${after.name}' requires manual SQL.`; + warnings.push(msg); + const colIdent = quoteIdent(after.name, dialect); + upParts.push( + `-- WARNING: Unsupported automatic primary-key change on ${tableRef}.${colIdent}; manual SQL required.`, + ); + downParts.push( + `-- WARNING: Unsupported automatic primary-key change on ${tableRef}.${colIdent}; manual SQL required.`, + ); + } + const upSql = upParts.join("\n"); + const downSql = downParts.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( + buildRollbackIndexSql(item.schema, item.tableOrCollection, before, 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 "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); + const { columnListClause, body } = extractViewSpec(after, dialect); + upStmts.push(`CREATE VIEW ${viewRef}${columnListClause} AS ${body};`); + 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) { + const { columnListClause, body } = extractViewSpec(before, dialect); + downStmts.push(`CREATE VIEW ${viewRef}${columnListClause} AS ${body};`); + } + break; + } + case "VIEW_MODIFIED": { + const before = item.before as CanonicalView; + const after = item.after as CanonicalView; + const viewRef = qualifyName(item.schema, after.name, dialect); + const { columnListClause: afterCols, body: afterBody } = extractViewSpec(after, dialect); + const { columnListClause: beforeCols, body: beforeBody } = extractViewSpec(before, dialect); + if (dialect === "sqlite") { + upStmts.push( + `DROP VIEW IF EXISTS ${viewRef};\nCREATE VIEW ${viewRef}${afterCols} AS ${afterBody};`, + ); + downStmts.push( + `DROP VIEW IF EXISTS ${viewRef};\nCREATE VIEW ${viewRef}${beforeCols} AS ${beforeBody};`, + ); + } else { + upStmts.push(`CREATE OR REPLACE VIEW ${viewRef}${afterCols} AS ${afterBody};`); + downStmts.push(`CREATE OR REPLACE VIEW ${viewRef}${beforeCols} AS ${beforeBody};`); + } + break; + } + } + }; + + for (const item of sortedTableDropped) { + scheduleAction(SQL_PHASE_ORDER.TABLE_DROPPED, () => emitDiffItem(item)); + } + for (const item of sortedTableAdded) { + scheduleAction(SQL_PHASE_ORDER.TABLE_ADDED, () => emitDiffItem(item)); + } + for (const item of remainingItems) { + if (item.type === "TABLE_ADDED" || item.type === "TABLE_DROPPED") continue; + const phase = earlySqliteSupportingIndexIds.has(item.id) + ? 6.5 + : (SQL_PHASE_ORDER[item.type] ?? 50); + scheduleAction(phase, () => emitDiffItem(item)); + } + + scheduledPhaseActions.sort((a, b) => a.phase - b.phase || a.seq - b.seq); + + let deferredCycleFksEmitted = false; + let deferredPostIndexFksEmitted = false; + for (const action of scheduledPhaseActions) { + if (!deferredCycleFksEmitted && action.phase > SQL_PHASE_ORDER.TABLE_ADDED) { + for (const { schema, tableName, fk } of deferredCycleFks) { + upStmts.push(buildAddFkSql(schema, tableName, fk, dialect)); + downStmts.push(buildDropFkSql(schema, tableName, fk.name, dialect)); + } + deferredCycleFksEmitted = true; + } + if (!deferredPostIndexFksEmitted && action.phase > SQL_PHASE_ORDER.INDEX_ADDED) { + for (const { schema, tableName, fk } of deferredPostIndexFks) { + upStmts.push(buildAddFkSql(schema, tableName, fk, dialect)); + downStmts.push(buildDropFkSql(schema, tableName, fk.name, dialect)); + } + deferredPostIndexFksEmitted = true; + } + action.emit(); + } + if (!deferredCycleFksEmitted) { + for (const { schema, tableName, fk } of deferredCycleFks) { + upStmts.push(buildAddFkSql(schema, tableName, fk, dialect)); + downStmts.push(buildDropFkSql(schema, tableName, fk.name, dialect)); + } + } + if (!deferredPostIndexFksEmitted) { + for (const { schema, tableName, fk } of deferredPostIndexFks) { + upStmts.push(buildAddFkSql(schema, tableName, fk, dialect)); + downStmts.push(buildDropFkSql(schema, tableName, fk.name, dialect)); + } + } + + return { upStmts, downStmts, warnings, hasDestructive }; +} + +function generateSqlMigration( + diff: SchemaDiffResult, + sourceAst: CanonicalSchemaAST, + targetAst: CanonicalSchemaAST, + dialect: CanonicalDialect, + version: string, + slug: string, + options: GenerateMigrationOptions, +): GeneratedMigrationResult { + const { upStmts, downStmts, warnings, hasDestructive } = buildSqlStatementsFromDiff( + diff, + sourceAst, + targetAst, + dialect, + options, + ); + + 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 downGroups: MongoMigrationStep[][] = []; + const warnings: string[] = []; + let hasDestructive = false; + let allowIrreversible = false; + + for (const item of diff.items) { + const coll = item.tableOrCollection; + + switch (item.type) { + case "TABLE_MODIFIED": { + const before = item.before as CanonicalCollection | undefined; + const after = item.after as CanonicalCollection | undefined; + if (before?.type === "view" || after?.type === "view") { + throw new UnsupportedMigrationError( + `MongoDB view/collection type transition for '${coll}' (${before?.type ?? "unknown"} -> ${after?.type ?? "unknown"}) is not supported in declarative .mql.json migrations.`, + ); + } + throw new UnsupportedMigrationError( + `Unsupported MongoDB collection modification for '${coll}': ${item.details}`, + ); + } + case "COLLECTION_ADDED": { + const after = item.after as CanonicalCollection; + if (after.type === "view") { + throw new UnsupportedMigrationError( + `MongoDB view creation for '${coll}' is not supported in declarative .mql.json migrations (views require viewOn and pipeline definitions).`, + ); + } + 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)); + } + downGroups.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 && before.type !== "view") { + downGroups.push([{ type: "createCollection", collection: coll }]); + } else if (before?.type === "view") { + warnings.push(`Rollback for dropped MongoDB view '${coll}' requires manual recreation.`); + } + break; + } + case "MONGO_INDEX_ADDED": { + const after = item.after as CanonicalMongoIndex; + up.push(toMongoCreateIndexStep(coll, after)); + downGroups.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) { + downGroups.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)); + downGroups.push([ + { type: "dropIndex", collection: coll, indexName: after.name }, + 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 } : {}), + }); + downGroups.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) { + downGroups.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 } : {}), + }); + downGroups.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: [...downGroups].reverse().flat(), + }; + + 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); +} + +export interface IndexMigrationCreateItem { + schema?: string; + tableOrCollection: string; + indexName: string; + columns: string[]; + unique?: boolean; +} + +export interface IndexMigrationDropItem { + schema?: string; + tableOrCollection: string; + indexName: string; + columns?: string[]; + sqlDefinition?: CanonicalIndex; + mongoDefinition?: CanonicalMongoIndex; + unique?: boolean; + partial?: string | null; + predicate?: string | null; + isPartial?: boolean; + indexType?: string; + key?: Record; + sparse?: boolean; + expireAfterSeconds?: number; + partialFilterExpression?: Record | null; +} + +export interface GenerateIndexMigrationOptions { + dialect: CanonicalDialect; + name?: string; + version?: string; + concurrentIndexes?: boolean; + createIndexes?: IndexMigrationCreateItem[]; + dropIndexes?: IndexMigrationDropItem[]; +} + +function toMongoKeySpec(columns: string[]): Record { + const key: Record = {}; + for (const col of columns) { + if (col) key[col] = 1; + } + return key; +} + +/** + * Generate a reversible SQL (`.sql`) or MongoDB (`.mql.json`) migration for + * creating and/or dropping indexes recommended by the AI Performance Copilot. + */ +export function generateIndexMigration( + options: GenerateIndexMigrationOptions, +): GeneratedMigrationResult { + const { dialect, concurrentIndexes = false } = options; + const createIndexes = options.createIndexes ?? []; + const dropIndexes = options.dropIndexes ?? []; + const version = options.version || generateMigrationVersion(); + const slug = slugifyMigrationName(options.name || "index_copilot"); + const warnings: string[] = []; + const hasDestructive = dropIndexes.length > 0; + + if (dialect === "clickhouse" && (createIndexes.length > 0 || dropIndexes.length > 0)) { + assertClickHouseIndexSupported(dialect); + } + + if (dialect === "mongodb") { + const up: MongoMigrationStep[] = []; + const down: MongoMigrationStep[] = []; + let allowIrreversible = false; + + for (const idx of createIndexes) { + up.push({ + type: "createIndex", + collection: idx.tableOrCollection, + key: toMongoKeySpec(idx.columns), + options: { + name: idx.indexName, + ...(idx.unique !== undefined ? { unique: idx.unique } : {}), + }, + }); + down.push({ + type: "dropIndex", + collection: idx.tableOrCollection, + indexName: idx.indexName, + }); + } + + for (const idx of dropIndexes) { + warnings.push(`Dropping index '${idx.indexName}' on collection '${idx.tableOrCollection}'`); + up.push({ + type: "dropIndex", + collection: idx.tableOrCollection, + indexName: idx.indexName, + }); + if (idx.mongoDefinition) { + down.push(toMongoCreateIndexStep(idx.tableOrCollection, idx.mongoDefinition)); + } else if (idx.key && Object.keys(idx.key).length > 0) { + down.push({ + type: "createIndex", + collection: idx.tableOrCollection, + key: idx.key, + options: { + name: idx.indexName, + ...(idx.unique !== undefined ? { unique: idx.unique } : {}), + ...(idx.sparse !== undefined ? { sparse: idx.sparse } : {}), + ...(idx.expireAfterSeconds !== undefined + ? { expireAfterSeconds: idx.expireAfterSeconds } + : {}), + ...(idx.partialFilterExpression + ? { partialFilterExpression: idx.partialFilterExpression } + : {}), + }, + }); + } else { + allowIrreversible = true; + warnings.push( + `Rollback for dropped index '${idx.indexName}' on '${idx.tableOrCollection}' requires manual recreation (full index key/options definition unavailable).`, + ); + } + } + + const manifest: MongoMigrationManifest = { + version, + id: `${version}_${slug}`, + name: slug, + description: "Generated from AI Performance & Index Copilot", + ...(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, + }; + } + + const upStmts: string[] = []; + const downStmts: string[] = []; + + for (const idx of createIndexes) { + upStmts.push( + buildCreateIndexSql( + idx.schema, + idx.tableOrCollection, + { + name: idx.indexName, + columns: idx.columns, + unique: Boolean(idx.unique), + }, + dialect, + concurrentIndexes, + ), + ); + downStmts.push( + buildDropIndexSql( + idx.schema, + idx.tableOrCollection, + idx.indexName, + dialect, + concurrentIndexes, + ), + ); + } + + for (const idx of dropIndexes) { + warnings.push(`Dropping index '${idx.indexName}' on '${idx.tableOrCollection}'`); + upStmts.push( + buildDropIndexSql( + idx.schema, + idx.tableOrCollection, + idx.indexName, + dialect, + concurrentIndexes, + ), + ); + const rawPredicate = idx.predicate ?? idx.partial ?? null; + const normalizedPredicate = rawPredicate?.trim().replace(/^WHERE\s+/i, "") || null; + + if (idx.sqlDefinition) { + const effectivePartial = + idx.sqlDefinition.partial?.trim().replace(/^WHERE\s+/i, "") || normalizedPredicate; + const effectiveDef: CanonicalIndex = { + ...idx.sqlDefinition, + partial: effectivePartial, + }; + if (idx.isPartial && !effectiveDef.partial) { + warnings.push( + `Rollback for dropped partial index '${idx.indexName}' on '${idx.tableOrCollection}' requires manual recreation (partial predicate unavailable).`, + ); + downStmts.push( + `-- MANUAL ROLLBACK REQUIRED: Cannot automatically recreate dropped partial index ${quoteIdent(idx.indexName, dialect)} without its WHERE predicate.`, + ); + } else { + const unsupportedReason = getUnsupportedSqlIndexReason(effectiveDef, dialect); + if (unsupportedReason) { + warnings.push( + `Rollback for dropped index '${idx.indexName}' on '${idx.tableOrCollection}' requires manual recreation (${unsupportedReason}).`, + ); + downStmts.push( + `-- MANUAL ROLLBACK REQUIRED: Cannot automatically recreate dropped index ${quoteIdent(idx.indexName, dialect)} (${unsupportedReason}).`, + ); + } else { + downStmts.push( + buildCreateIndexSql( + idx.schema, + idx.tableOrCollection, + effectiveDef, + dialect, + concurrentIndexes, + ), + ); + } + } + } else if (idx.columns && idx.columns.length > 0 && idx.unique !== undefined) { + if (idx.isPartial && !normalizedPredicate) { + warnings.push( + `Rollback for dropped partial index '${idx.indexName}' on '${idx.tableOrCollection}' requires manual recreation (partial predicate unavailable).`, + ); + downStmts.push( + `-- MANUAL ROLLBACK REQUIRED: Cannot automatically recreate dropped partial index ${quoteIdent(idx.indexName, dialect)} without its WHERE predicate.`, + ); + } else { + const effectiveDef: CanonicalIndex = { + name: idx.indexName, + columns: idx.columns, + unique: idx.unique, + partial: normalizedPredicate, + ...(idx.indexType ? { indexType: idx.indexType } : {}), + }; + const unsupportedReason = getUnsupportedSqlIndexReason(effectiveDef, dialect); + if (unsupportedReason) { + warnings.push( + `Rollback for dropped index '${idx.indexName}' on '${idx.tableOrCollection}' requires manual recreation (${unsupportedReason}).`, + ); + downStmts.push( + `-- MANUAL ROLLBACK REQUIRED: Cannot automatically recreate dropped index ${quoteIdent(idx.indexName, dialect)} (${unsupportedReason}).`, + ); + } else { + downStmts.push( + buildCreateIndexSql( + idx.schema, + idx.tableOrCollection, + effectiveDef, + dialect, + concurrentIndexes, + ), + ); + } + } + } else { + warnings.push( + `Rollback for dropped index '${idx.indexName}' on '${idx.tableOrCollection}' requires manual recreation (full index definition unavailable).`, + ); + downStmts.push( + `-- MANUAL ROLLBACK REQUIRED: Cannot automatically recreate dropped index ${quoteIdent(idx.indexName, dialect)} without full index definition (uniqueness/columns).`, + ); + } + } + + const filename = `${version}_${slug}.sql`; + const upSql = upStmts.length > 0 ? upStmts.join("\n\n") : "-- No index changes"; + 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, + }; +} diff --git a/bridge/src/services/migrationLock.ts b/bridge/src/services/migrationLock.ts index 10686e9d..08942692 100644 --- a/bridge/src/services/migrationLock.ts +++ b/bridge/src/services/migrationLock.ts @@ -10,13 +10,16 @@ export interface MigrationLock { updatedAt: string; } -export async function getLockFilePath(dbId: string): Promise { - const migrationsDir = await projectStoreInstance.resolveMigrationsDir(dbId); - return path.join(migrationsDir, "migration.lock.json"); +export async function getLockFilePath(dbId: string, migrationsDir?: string): Promise { + const dir = migrationsDir ?? (await projectStoreInstance.resolveMigrationsDir(dbId)); + return path.join(dir, "migration.lock.json"); } -export async function readMigrationLock(dbId: string): Promise { - const lockPath = await getLockFilePath(dbId); +export async function readMigrationLock( + dbId: string, + migrationsDir?: string, +): Promise { + const lockPath = await getLockFilePath(dbId, migrationsDir); if (!fsSync.existsSync(lockPath)) return null; try { @@ -31,8 +34,9 @@ export async function writeMigrationLock( dbId: string, schemaHash: string, appliedMigrations: string[], + migrationsDir?: string, ): Promise { - const lockPath = await getLockFilePath(dbId); + const lockPath = await getLockFilePath(dbId, migrationsDir); const lockData: MigrationLock = { version: "1", schemaHash, @@ -44,8 +48,12 @@ export async function writeMigrationLock( await fs.writeFile(lockPath, JSON.stringify(lockData, null, 2), "utf8"); } -export async function verifyMigrationLock(dbId: string, targetHash: string): Promise { - const lock = await readMigrationLock(dbId); +export async function verifyMigrationLock( + dbId: string, + targetHash: string, + migrationsDir?: string, +): Promise { + const lock = await readMigrationLock(dbId, migrationsDir); if (!lock) return false; return lock.schemaHash === targetHash; } diff --git a/bridge/src/services/projectStore.ts b/bridge/src/services/projectStore.ts index 9391f96a..c191d304 100644 --- a/bridge/src/services/projectStore.ts +++ b/bridge/src/services/projectStore.ts @@ -80,13 +80,40 @@ export type SchemaFile = { version: number; // bumped to 2 projectId: string; databaseId: string; - dialect: "postgresql" | "mysql" | "sqlite" | "duckdb" | "clickhouse" | "unknown"; + dialect: + "postgresql" | "mysql" | "mariadb" | "sqlite" | "duckdb" | "clickhouse" | "mongodb" | "unknown"; schemas: SchemaSnapshot[]; cachedAt: string; relwaveVersion: string; schemaHash: string; // SHA-256 of entire schema content }; +function deriveSchemaDialect(rawEngineOrDialect?: string | null): SchemaFile["dialect"] { + const value = (rawEngineOrDialect || "").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 "unknown"; + } +} + export type SchemaSnapshot = { name: string; tables: TableSnapshot[]; @@ -227,12 +254,69 @@ export class ProjectStore { private cacheLoaded = false; /** In-flight cache load promise — prevents redundant concurrent reads */ private cacheLoadPromise: Promise | null = null; + /** In-process mutex serializing index mutations and legacy migration directory moves */ + private indexLock: Promise = Promise.resolve(); + /** Per-project mutex serializing schema.json read-modify-write operations */ + private schemaLocks = new Map>(); constructor(projectsFolder: string = PROJECTS_FOLDER, indexFile: string = PROJECTS_INDEX_FILE) { this.projectsFolder = projectsFolder; this.indexFile = indexFile; } + private withIndexLock(fn: () => Promise): Promise { + const run = this.indexLock.then(fn, fn); + this.indexLock = run.then( + () => undefined, + () => undefined, + ); + return run; + } + + private withSchemaLock(projectId: string, fn: () => Promise): Promise { + const prev = this.schemaLocks.get(projectId) ?? Promise.resolve(); + const run = prev.then(fn, fn); + const tail = run.then( + () => undefined, + () => undefined, + ); + this.schemaLocks.set(projectId, tail); + tail.finally(() => { + if (this.schemaLocks.get(projectId) === tail) { + this.schemaLocks.delete(projectId); + } + }); + return run; + } + + private async moveDirectorySafely(fallbackDir: string, targetDir: string): Promise { + const targetParent = path.dirname(targetDir); + await fs.mkdir(targetParent, { recursive: true }); + try { + await fs.rename(fallbackDir, targetDir); + return; + } catch (err: any) { + if (err?.code !== "EXDEV") { + throw err; + } + } + + const stagingDir = path.join(targetParent, `.migrations-tmp-${process.pid}-${uuidv4()}`); + try { + await fs.cp(fallbackDir, stagingDir, { recursive: true, errorOnExist: true, force: false }); + await fs.rename(stagingDir, targetDir); + } catch (exdevErr) { + await fs.rm(stagingDir, { recursive: true, force: true }).catch(() => {}); + throw exdevErr; + } + + try { + await fs.rm(fallbackDir, { recursive: true, force: true }); + } catch (rmErr) { + console.error("Failed to remove legacy migrations dir after copy:", rmErr); + } + } + /** * Ensure the sourcePathCache is populated from the index. * Safe to call multiple times — only reads once. @@ -430,7 +514,7 @@ export class ProjectStore { version: 2, projectId: id, databaseId: params.databaseId, - dialect: engine === "postgresql" ? "postgresql" : engine === "mysql" ? "mysql" : "sqlite", // Provide fallback or infer + dialect: deriveSchemaDialect(engine), schemas: [], cachedAt: now, relwaveVersion: "1.0.0", // Hardcoded for now @@ -468,18 +552,20 @@ export class ProjectStore { }); // Update global index - const index = await this.loadIndex(); - index.projects.push({ - id, - name: meta.name, - description: meta.description, - engine, - databaseId: meta.databaseId, - status: "active", - createdAt: now, - updatedAt: now, + await this.withIndexLock(async () => { + const index = await this.loadIndex(); + index.projects.push({ + id, + name: meta.name, + description: meta.description, + engine, + databaseId: meta.databaseId, + status: "active", + createdAt: now, + updatedAt: now, + }); + await this.saveIndex(index); }); - await this.saveIndex(index); return meta; } @@ -532,14 +618,16 @@ export class ProjectStore { } // Sync the index entry (always — index is internal) - const index = await this.loadIndex(); - const entry = index.projects.find((p) => p.id === projectId); - if (entry) { - if (updates.name !== undefined) entry.name = updates.name; - if (updates.description !== undefined) entry.description = updates.description; - entry.updatedAt = now; - await this.saveIndex(index); - } + await this.withIndexLock(async () => { + const index = await this.loadIndex(); + const entry = index.projects.find((p) => p.id === projectId); + if (entry) { + if (updates.name !== undefined) entry.name = updates.name; + if (updates.description !== undefined) entry.description = updates.description; + entry.updatedAt = now; + await this.saveIndex(index); + } + }); return { ...meta, @@ -591,23 +679,34 @@ export class ProjectStore { }; await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.metadata), updated); - // Sync schema file's databaseId reference - const schemaFile = await this.getSchema(projectId); - if (schemaFile) { - schemaFile.databaseId = databaseId; - await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.schema), schemaFile); - } + // Sync schema file's databaseId and dialect reference (only relabel empty snapshots) + await this.withSchemaLock(projectId, async () => { + const schemaFile = await this.getSchema(projectId); + if (schemaFile) { + schemaFile.databaseId = databaseId; + const derivedDialect = deriveSchemaDialect(engine); + if ( + derivedDialect !== "unknown" && + (!Array.isArray(schemaFile.schemas) || schemaFile.schemas.length === 0) + ) { + schemaFile.dialect = derivedDialect; + } + await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.schema), schemaFile); + } + }); } // Sync the index entry (always — index is internal) - const index = await this.loadIndex(); - const entry = index.projects.find((p) => p.id === projectId); - if (entry) { - entry.databaseId = databaseId; - if (engine) entry.engine = engine; - entry.updatedAt = now; - await this.saveIndex(index); - } + await this.withIndexLock(async () => { + const index = await this.loadIndex(); + const entry = index.projects.find((p) => p.id === projectId); + if (entry) { + entry.databaseId = databaseId; + if (engine) entry.engine = engine; + entry.updatedAt = now; + await this.saveIndex(index); + } + }); // Return the effective metadata (with merged databaseId) return { @@ -647,14 +746,16 @@ export class ProjectStore { } // Sync the index entry - const index = await this.loadIndex(); - const entry = index.projects.find((p) => p.id === meta.id); - if (entry) { - entry.databaseId = null; - entry.status = "unlinked"; - entry.updatedAt = now; - await this.saveIndex(index); - } + await this.withIndexLock(async () => { + const index = await this.loadIndex(); + const entry = index.projects.find((p) => p.id === meta.id); + if (entry) { + entry.databaseId = null; + entry.status = "unlinked"; + entry.updatedAt = now; + await this.saveIndex(index); + } + }); } /** @@ -692,13 +793,15 @@ export class ProjectStore { } // Sync the index entry - const index = await this.loadIndex(); - const entry = index.projects.find((p) => p.id === projectId); - if (entry) { - entry.status = "active"; - entry.updatedAt = now; - await this.saveIndex(index); - } + await this.withIndexLock(async () => { + const index = await this.loadIndex(); + const entry = index.projects.find((p) => p.id === projectId); + if (entry) { + entry.status = "active"; + entry.updatedAt = now; + await this.saveIndex(index); + } + }); return { ...updated, status: "active", updatedAt: now }; } @@ -709,6 +812,40 @@ export class ProjectStore { * For imported projects the source directory is NOT deleted * (the user owns it) — only the index entry is removed. */ + /** + * Resolve the migrations directory for a specific project. + * Moves legacy AppData migrations only when this is the sole project linked to its database. + */ + async resolveProjectMigrationsDir(projectId: string): Promise { + const projectDir = await this.resolveProjectDir(projectId); + const targetDir = path.join(projectDir, "migrations"); + + await this.withIndexLock(async () => { + if (!fsSync.existsSync(targetDir)) { + const project = await this.getProject(projectId); + if (project?.databaseId) { + const { CONFIG_FOLDER } = await import("../utils/config"); + const fallbackDir = path.join(CONFIG_FOLDER, "migrations", project.databaseId); + if (fsSync.existsSync(fallbackDir)) { + const index = await this.loadIndex(); + const linkedProjects = index.projects.filter( + (p) => p.databaseId === project.databaseId, + ); + if (linkedProjects.length <= 1) { + await this.moveDirectorySafely(fallbackDir, targetDir); + } + } + } + } + + if (!fsSync.existsSync(targetDir)) { + await fs.mkdir(targetDir, { recursive: true }).catch(() => {}); + } + }); + + return targetDir; + } + /** * Resolve the migrations directory for a database. * Moves legacy migrations from AppData to the project directory if they exist. @@ -716,30 +853,27 @@ export class ProjectStore { async resolveMigrationsDir(dbId: string): Promise { const { CONFIG_FOLDER } = await import("../utils/config"); const fallbackDir = path.join(CONFIG_FOLDER, "migrations", dbId); - let targetDir = fallbackDir; - const project = await this.getProjectByDatabaseId(dbId); - if (project) { - targetDir = path.join(this.projectDir(project.id), "migrations"); - } + return this.withIndexLock(async () => { + let targetDir = fallbackDir; + const project = await this.getProjectByDatabaseId(dbId); + if (project) { + targetDir = path.join(this.projectDir(project.id), "migrations"); + } - // Migrate existing directory - if (targetDir !== fallbackDir && fsSync.existsSync(fallbackDir)) { - if (!fsSync.existsSync(targetDir)) { - await fs.mkdir(path.dirname(targetDir), { recursive: true }).catch(() => {}); - try { - await fs.rename(fallbackDir, targetDir); - } catch (e) { - console.error("Failed to migrate existing migrations dir:", e); + // Migrate existing directory + if (targetDir !== fallbackDir && fsSync.existsSync(fallbackDir)) { + if (!fsSync.existsSync(targetDir)) { + await this.moveDirectorySafely(fallbackDir, targetDir); } } - } - if (!fsSync.existsSync(targetDir)) { - await fs.mkdir(targetDir, { recursive: true }).catch(() => {}); - } + if (!fsSync.existsSync(targetDir)) { + await fs.mkdir(targetDir, { recursive: true }).catch(() => {}); + } - return targetDir; + return targetDir; + }); } async analyzeImportedProject( @@ -785,9 +919,11 @@ export class ProjectStore { // Remove from index + cache this.sourcePathCache.delete(projectId); - const index = await this.loadIndex(); - index.projects = index.projects.filter((p) => p.id !== projectId); - await this.saveIndex(index); + await this.withIndexLock(async () => { + const index = await this.loadIndex(); + index.projects = index.projects.filter((p) => p.id !== projectId); + await this.saveIndex(index); + }); } /** @@ -811,9 +947,11 @@ export class ProjectStore { // Remove from index + cache this.sourcePathCache.delete(project.id); - const index = await this.loadIndex(); - index.projects = index.projects.filter((p) => p.id !== project.id); - await this.saveIndex(index); + await this.withIndexLock(async () => { + const index = await this.loadIndex(); + index.projects = index.projects.filter((p) => p.id !== project.id); + await this.saveIndex(index); + }); } async getSchema(projectId: string): Promise { @@ -852,12 +990,44 @@ export class ProjectStore { foreignKeys: [], checks: [], })), - enums: [], - views: [], + enums: Array.isArray(s.enums) ? s.enums : [], + ...(Array.isArray(s.views) ? { views: s.views } : {}), })), }; } + /** + * Conditionally repairs only the `dialect` field on `schema.json` when the + * on-disk snapshot's `schemaHash` and `cachedAt` still match the snapshot + * read by the caller, avoiding overwriting a newer snapshot written concurrently. + */ + async repairSchemaDialect( + projectId: string, + expectedSchemaHash: string, + expectedCachedAt: string, + targetDialect: string, + ): Promise { + const normalizedDialect = deriveSchemaDialect(targetDialect); + if (normalizedDialect === "unknown") return false; + + return this.withSchemaLock(projectId, async () => { + const current = await this.getSchema(projectId); + if (!current) return false; + if (current.schemaHash !== expectedSchemaHash || current.cachedAt !== expectedCachedAt) { + return false; + } + if (current.dialect === normalizedDialect) { + return false; + } + const repaired: SchemaFile = { + ...current, + dialect: normalizedDialect, + }; + await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.schema), repaired); + return true; + }); + } + async saveSchema( projectId: string, schemas: SchemaSnapshot[], @@ -867,38 +1037,62 @@ export class ProjectStore { const meta = await this.getProject(projectId); if (!meta) throw new Error(`Project ${projectId} not found`); - // Read existing file and skip write if schema data is identical - // (avoids cachedAt churn that creates phantom git changes) - const existing = await this.getSchema(projectId); - if (existing && existing.version === 2) { - const oldData = JSON.stringify(existing.schemas); - const newData = JSON.stringify(schemas); - // If schemaHash is provided, also check if it matches - if (oldData === newData && (!schemaHash || existing.schemaHash === schemaHash)) { - return existing; // nothing changed — keep old cachedAt + let targetDialect = deriveSchemaDialect(dialect); + if (targetDialect === "unknown") { + targetDialect = deriveSchemaDialect(meta.engine); + } + if (targetDialect === "unknown" && meta.databaseId) { + try { + const db: DBMeta | undefined = await dbStoreInstance.getDB(meta.databaseId); + targetDialect = deriveSchemaDialect(db?.type); + } catch { + // db may not exist yet } } - const now = new Date().toISOString(); - const file: SchemaFile = { - version: 2, - projectId, - databaseId: meta.databaseId || "", - dialect: (dialect || - (meta.engine === "postgresql" - ? "postgresql" - : meta.engine === "mysql" || meta.engine === "mariadb" - ? "mysql" - : "sqlite")) as any, - schemas, - cachedAt: now, - relwaveVersion: "1.0.0", - schemaHash: schemaHash || "", - }; + return this.withSchemaLock(projectId, async () => { + // Read existing file and skip write if schema data is identical + // (avoids cachedAt churn that creates phantom git changes) + const existing = await this.getSchema(projectId); + if (existing && existing.version === 2) { + const oldData = JSON.stringify(existing.schemas); + const newData = JSON.stringify(schemas); + // If schemaHash is provided, also check if it matches + if (oldData === newData && (!schemaHash || existing.schemaHash === schemaHash)) { + if (targetDialect !== "unknown" && existing.dialect !== targetDialect) { + const repaired: SchemaFile = { + ...existing, + dialect: targetDialect, + }; + await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.schema), repaired); + return repaired; + } + return existing; // nothing changed — keep old cachedAt + } + } - await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.schema), file); + const now = new Date().toISOString(); + const resolvedDialect: SchemaFile["dialect"] = + targetDialect !== "unknown" + ? targetDialect + : existing?.dialect && existing.dialect !== "unknown" + ? existing.dialect + : "unknown"; + const file: SchemaFile = { + version: 2, + projectId, + databaseId: meta.databaseId || "", + dialect: resolvedDialect, + schemas, + cachedAt: now, + relwaveVersion: "1.0.0", + schemaHash: schemaHash || "", + }; - return file; + await this.writeJSON(this.projectFile(projectId, PROJECT_FILES.schema), file); + + return file; + }); } async getERDiagram(projectId: string): Promise { @@ -1557,67 +1751,69 @@ export class ProjectStore { throw new Error(`Invalid ${PROJECT_FILES.metadata}: missing required fields`); } - // ---- 2. Check for duplicate project ID ---- const id = sourceMeta.id; - const index = await this.loadIndex(); - if (index.projects.some((p) => p.id === id)) { - throw new Error(`Project "${sourceMeta.name}" is already imported (id: ${id})`); - } - - // ---- 3. Resolve engine from the linked database ---- - let engine: string | undefined; - try { - const db: DBMeta | undefined = await dbStoreInstance.getDB(databaseId); - engine = db?.type; - } catch { - // db may not exist yet - } - - // ---- 4. Register the sourcePath so projectDir() resolves correctly ---- - this.sourcePathCache.set(id, sourcePath); + return this.withIndexLock(async () => { + // ---- 2. Check for duplicate project ID ---- + const index = await this.loadIndex(); + if (index.projects.some((p) => p.id === id)) { + throw new Error(`Project "${sourceMeta.name}" is already imported (id: ${id})`); + } - // Ensure subdirectories exist in the source dir (they should, - // but be defensive) - for (const sub of ["schema", "diagrams", "queries"]) { - ensureDir(path.join(sourcePath, sub)); - } + // ---- 3. Resolve engine from the linked database ---- + let engine: string | undefined; + try { + const db: DBMeta | undefined = await dbStoreInstance.getDB(databaseId); + engine = db?.type; + } catch { + // db may not exist yet + } - // ---- 5. DO NOT modify relwave.json or sub-resource files ---- - // relwave.json keeps the original projectId & databaseId - // so forks/clones never produce unnecessary diffs. + // ---- 4. Register the sourcePath so projectDir() resolves correctly ---- + this.sourcePathCache.set(id, sourcePath); - // ---- 6. Ensure .gitignore exists in source dir ---- - await this.ensureGitignore(id); + // Ensure subdirectories exist in the source dir (they should, + // but be defensive) + for (const sub of ["schema", "diagrams", "queries"]) { + ensureDir(path.join(sourcePath, sub)); + } - // ---- 7. Write databaseId to local config (git-ignored) ---- - const localConfig: LocalConfig = { databaseId }; - const localPath = path.join(sourcePath, PROJECT_FILES.localConfig); - const existingLocal = fsSync.existsSync(localPath) - ? await this.readJSON(localPath) - : null; - await this.writeJSON(localPath, { ...existingLocal, ...localConfig }); + // ---- 5. DO NOT modify relwave.json or sub-resource files ---- + // relwave.json keeps the original projectId & databaseId + // so forks/clones never produce unnecessary diffs. + + // ---- 6. Ensure .gitignore exists in source dir ---- + await this.ensureGitignore(id); + + // ---- 7. Write databaseId to local config (git-ignored) ---- + const localConfig: LocalConfig = { databaseId }; + const localPath = path.join(sourcePath, PROJECT_FILES.localConfig); + const existingLocal = fsSync.existsSync(localPath) + ? await this.readJSON(localPath) + : null; + await this.writeJSON(localPath, { ...existingLocal, ...localConfig }); + + // ---- 8. Add to the global index ---- + const now = new Date().toISOString(); + index.projects.push({ + id, + name: sourceMeta.name, + description: sourceMeta.description, + engine: engine ?? sourceMeta.engine, + databaseId, + sourcePath, + createdAt: sourceMeta.createdAt ?? now, + updatedAt: now, + }); + await this.saveIndex(index); - // ---- 8. Add to the global index ---- - const now = new Date().toISOString(); - index.projects.push({ - id, - name: sourceMeta.name, - description: sourceMeta.description, - engine: engine ?? sourceMeta.engine, - databaseId, - sourcePath, - createdAt: sourceMeta.createdAt ?? now, - updatedAt: now, + // ---- 9. Return effective metadata (with local databaseId) ---- + return { + ...sourceMeta, + engine: engine ?? sourceMeta.engine, + databaseId, + sourcePath, + }; }); - await this.saveIndex(index); - - // ---- 9. Return effective metadata (with local databaseId) ---- - return { - ...sourceMeta, - engine: engine ?? sourceMeta.engine, - databaseId, - sourcePath, - }; } } diff --git a/bridge/src/services/queryExecutor.ts b/bridge/src/services/queryExecutor.ts index 22d9e307..f7f04617 100644 --- a/bridge/src/services/queryExecutor.ts +++ b/bridge/src/services/queryExecutor.ts @@ -170,14 +170,25 @@ export class QueryExecutor { const finalSchemas = await parallelMap(schemas, async (schema) => { try { const tablesInSchema = await connector.listTables(conn, schema.name); - const batchData = await connector.getSchemaMetadataBatch(conn, schema.name); + let batchData: any; + let isMetadataIncomplete = false; + try { + batchData = await connector.getSchemaMetadataBatch(conn, schema.name); + } catch (batchErr: any) { + isMetadataIncomplete = true; + logger.warn( + { err: batchErr.message, schema: schema.name }, + "getSchemaMetadataBatch failed; retaining discoverable tables with empty column metadata", + ); + batchData = { tables: new Map() }; + } const finalTables = tablesInSchema.map((table: any) => { - const tableData = batchData.tables.get(table.name); + const tableData = batchData.tables?.get(table.name); return { name: table.name, type: table.type, - columns: tableData?.columns.map(mapColumn) ?? [], + columns: tableData?.columns?.map(mapColumn) ?? [], primaryKeys: tableData?.primaryKeys ?? [], foreignKeys: tableData?.foreignKeys ?? [], indexes: tableData?.indexes ?? [], @@ -193,7 +204,12 @@ export class QueryExecutor { if (batchData.enumColumns !== undefined) extra.enumColumns = batchData.enumColumns; if (batchData.autoIncrements !== undefined) extra.autoIncrements = batchData.autoIncrements; - return { name: schema.name, tables: finalTables, ...extra }; + return { + name: schema.name, + tables: finalTables, + ...extra, + ...(isMetadataIncomplete ? { isMetadataIncomplete: true } : {}), + }; } catch (e: any) { logger.warn({ err: e.message, schema: schema.name }, "Skipping schema due to error"); return null; @@ -205,7 +221,12 @@ export class QueryExecutor { ? (conn as any).path || (conn as any).database : (conn as any).database; - return { name: dbName, schemas: finalSchemas.filter(Boolean) }; + const hasIncompleteMetadata = finalSchemas.some((s: any) => s?.isMetadataIncomplete); + return { + name: dbName, + schemas: finalSchemas.filter(Boolean), + ...(hasIncompleteMetadata ? { hasIncompleteMetadata: true } : {}), + }; } // ---- M2: MongoDB document engine (docs/MONGODB_M2_SPEC.md §13) ---- diff --git a/bridge/src/services/schemaDiffEngine.ts b/bridge/src/services/schemaDiffEngine.ts new file mode 100644 index 00000000..c7f974bf --- /dev/null +++ b/bridge/src/services/schemaDiffEngine.ts @@ -0,0 +1,968 @@ +/** + * 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, + CanonicalDialect, + CanonicalMongoIndex, + CanonicalSchemaAST, + CanonicalTable, + DiffSeverity, + SchemaDiffItem, + SchemaDiffResult, + SchemaDiffSummary, +} from "../types/schemaDiff"; +import { normalizeExpressionForComparison } from "./schemaSnapshotNormalizer"; + +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][a-z0-9\s]*)\(\s*([+-]?\d+(?:\s*,\s*[+-]?\d+)*)\s*\)$/); + if (!match) return null; + const base = match[1].trim(); + const params = match[2].split(",").map((p) => parseInt(p.trim(), 10)); + return { base, params }; +} + +function isNumericPrecisionType(base: string): boolean { + return base === "numeric" || base === "decimal"; +} + +/** + * 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 (isNumericPrecisionType(from) && parsedTo && isNumericPrecisionType(parsedTo.base)) { + return true; + } + if (parsedFrom && parsedTo) { + if (isNumericPrecisionType(parsedFrom.base) && isNumericPrecisionType(parsedTo.base)) { + const fromPrecision = parsedFrom.params[0]; + const fromScale = parsedFrom.params[1] ?? 0; + const toPrecision = parsedTo.params[0]; + const toScale = parsedTo.params[1] ?? 0; + const fromIntDigits = fromPrecision - fromScale; + const toIntDigits = toPrecision - toScale; + return toIntDigits < fromIntDigits || toScale < fromScale; + } + + if (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) { + const fromIntDigits = parsedFrom.params[0] - parsedFrom.params[1]; + const toIntDigits = parsedTo.params[0] - parsedTo.params[1]; + return toIntDigits < fromIntDigits || 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 can fail on existing NULL rows even when a default is set + if (before.nullable && !after.nullable) { + 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 (requires backfill or verification that no NULL rows exist)", + ); + } + 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 JSON.stringify([type, schema || "", tableOrCollection, objectName || ""]); +} + +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 getEffectivePrimaryKeyColumns(table: CanonicalTable): string[] { + if (table.primaryKeyColumns !== undefined) { + return table.primaryKeyColumns; + } + return [...table.columns] + .filter((c) => c.isPrimaryKey) + .sort((a, b) => a.ordinalPosition - b.ordinalPosition) + .map((c) => c.name); +} + +function primaryKeysMatch( + srcTable: CanonicalTable, + tgtTable: CanonicalTable, + srcPkCols: string[], + tgtPkCols: string[], +): boolean { + if (srcTable.primaryKeyColumns !== undefined && tgtTable.primaryKeyColumns !== undefined) { + return ( + srcPkCols.length === tgtPkCols.length && srcPkCols.every((col, idx) => col === tgtPkCols[idx]) + ); + } + + // Either side lacks ordered primaryKeyColumns metadata (e.g., legacy column-flag-only + // snapshots): compare PK column sets without order sensitivity. + const srcSet = new Set(srcPkCols); + const tgtSet = new Set(tgtPkCols); + return srcSet.size === tgtSet.size && Array.from(srcSet).every((col) => tgtSet.has(col)); +} + +function diffTableObjects( + schemaName: string, + srcTable: CanonicalTable, + tgtTable: CanonicalTable, + items: SchemaDiffItem[], + dialect: CanonicalDialect, +): 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`, + }); + } + + const srcPkCols = getEffectivePrimaryKeyColumns(srcTable); + const tgtPkCols = getEffectivePrimaryKeyColumns(tgtTable); + if (!primaryKeysMatch(srcTable, tgtTable, srcPkCols, tgtPkCols)) { + items.push({ + id: buildItemId("TABLE_MODIFIED", schemaName, srcTable.name, "primaryKey"), + type: "TABLE_MODIFIED", + severity: srcPkCols.length > 0 ? "destructive" : "warning", + schema: schemaName, + tableOrCollection: srcTable.name, + objectName: "primaryKey", + before: srcPkCols, + after: tgtPkCols, + details: `Primary key on ${schemaName}.${srcTable.name} changed: (${srcPkCols.join(", ") || "none"}) -> (${tgtPkCols.join(", ") || "none"})`, + }); + } + + // 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 and comparison-equivalent quoting when everything semantic is identical + const semBefore = { + ...srcCol, + ordinalPosition: 0, + defaultValue: normalizeExpressionForComparison(srcCol.defaultValue, dialect), + }; + const semAfter = { + ...tgtCol, + ordinalPosition: 0, + defaultValue: normalizeExpressionForComparison(tgtCol.defaultValue, dialect), + }; + 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 { + const cmpBefore = { + ...before, + partial: normalizeExpressionForComparison(before.partial ?? null, dialect), + }; + const cmpAfter = { + ...after, + partial: normalizeExpressionForComparison(after.partial ?? null, dialect), + }; + if (!deepEqual(cmpBefore, cmpAfter)) { + 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 { + const cmpBefore = { + ...before, + expression: normalizeExpressionForComparison(before.expression, dialect) || "", + }; + const cmpAfter = { + ...after, + expression: normalizeExpressionForComparison(after.expression, dialect) || "", + }; + if (!deepEqual(cmpBefore, cmpAfter)) { + 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 dialect = target.dialect || source.dialect; + 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, dialect); + } + } + + 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 { + const cmpBefore = { + name: before.name, + definition: normalizeExpressionForComparison(before.definition, dialect) || "", + columns: before.columns?.length ? before.columns : undefined, + }; + const cmpAfter = { + name: after.name, + definition: normalizeExpressionForComparison(after.definition, dialect) || "", + columns: after.columns?.length ? after.columns : undefined, + }; + if (!deepEqual(cmpBefore, cmpAfter)) { + 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 mongoIndexKeySignature(key: Record): string { + return JSON.stringify(Object.entries(key)); +} + +function mongoIndexesEqual(a: CanonicalMongoIndex, b: CanonicalMongoIndex): boolean { + if (a.name !== b.name || a.unique !== b.unique || a.sparse !== b.sparse) return false; + if ((a.expireAfterSeconds ?? undefined) !== (b.expireAfterSeconds ?? undefined)) return false; + if (mongoIndexKeySignature(a.key) !== mongoIndexKeySignature(b.key)) return false; + return deepEqual(a.partialFilterExpression ?? null, b.partialFilterExpression ?? null); +} + +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; + } + + if (srcColl.type !== tgtColl.type) { + items.push({ + id: buildItemId("TABLE_MODIFIED", undefined, collName, `${srcColl.type}->${tgtColl.type}`), + type: "TABLE_MODIFIED", + severity: "destructive", + tableOrCollection: collName, + before: srcColl, + after: tgtColl, + details: `Unsupported MongoDB type transition on ${collName}: ${srcColl.type} -> ${tgtColl.type}`, + }); + 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 (!mongoIndexesEqual(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) => mongoIndexKeySignature(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) => mongoIndexKeySignature(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; + + if (source.dialect && target.dialect && source.dialect !== target.dialect) { + throw new Error( + `Cannot diff schemas with mismatched dialects: ${source.dialect} vs ${target.dialect}`, + ); + } + + 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..99ef0670 --- /dev/null +++ b/bridge/src/services/schemaSnapshotNormalizer.ts @@ -0,0 +1,1230 @@ +/** + * 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"; + } +} + +function isMySqlCommentStart(input: string, dashIndex: number): boolean { + const nextIdx = dashIndex + 2; + if (nextIdx >= input.length) return true; + const nextChar = input[nextIdx]; + const code = nextChar.charCodeAt(0); + return (code >= 0x00 && code <= 0x1f) || code === 0x7f || /\s/.test(nextChar); +} + +/** + * Split a SQL fragment into quoted and unquoted segments, preserving + * single-quoted string literals, dollar-quoted PostgreSQL string literals, + * and double-quoted/backtick-quoted identifiers. + */ +function splitSqlQuoted( + input: string, + dialect?: CanonicalDialect, +): Array<{ text: string; quoted: boolean; quoteChar?: string; comment?: boolean }> { + const parts: Array<{ text: string; quoted: boolean; quoteChar?: string; comment?: boolean }> = []; + const isMySqlLikeDashComment = dialect === "mysql" || dialect === "mariadb"; + let buf = ""; + let i = 0; + + while (i < input.length) { + const ch = input[i]; + if (ch === "'" || ch === '"' || ch === "`") { + if (buf) { + parts.push({ text: buf, quoted: false }); + buf = ""; + } + const quote = ch; + let token = quote; + i++; + while (i < input.length) { + const c = input[i]; + token += c; + if (c === "\\" && i + 1 < input.length) { + i++; + token += input[i]; + i++; + continue; + } + if (c === quote) { + if (i + 1 < input.length && input[i + 1] === quote) { + i++; + token += input[i]; + i++; + continue; + } + i++; + break; + } + i++; + } + parts.push({ text: token, quoted: true, quoteChar: quote }); + } else if ( + (ch === "-" && + input[i + 1] === "-" && + (!isMySqlLikeDashComment || isMySqlCommentStart(input, i))) || + (ch === "#" && (dialect === "mysql" || dialect === "mariadb")) + ) { + if (buf) { + parts.push({ text: buf, quoted: false }); + buf = ""; + } + let end = i + (ch === "#" ? 1 : 2); + while (end < input.length && input[end] !== "\n" && input[end] !== "\r") { + end++; + } + if (end < input.length) { + while (end < input.length && /\s/.test(input[end])) { + end++; + } + } + parts.push({ text: input.slice(i, end), quoted: false, comment: true }); + i = end; + } else if (ch === "/" && input[i + 1] === "*") { + if (buf) { + parts.push({ text: buf, quoted: false }); + buf = ""; + } + const closeIdx = input.indexOf("*/", i + 2); + const end = closeIdx === -1 ? input.length : closeIdx + 2; + parts.push({ text: input.slice(i, end), quoted: false, comment: true }); + i = end; + } else if (ch === "$") { + // Only start a dollar-quoted string when NOT immediately preceded by an identifier character + const prevTail = i > 0 ? input.slice(Math.max(0, i - 2), i) : ""; + const precededByIdent = i > 0 && /[\p{L}\p{N}_$]$/u.test(prevTail); + if (!precededByIdent) { + const dollarMatch = input.slice(i).match(/^\$(?:[\p{L}_][\p{L}\p{N}_]*)?\$/u); + if (dollarMatch) { + const delim = dollarMatch[0]; + const closeIdx = input.indexOf(delim, i + delim.length); + if (closeIdx !== -1) { + if (buf) { + parts.push({ text: buf, quoted: false }); + buf = ""; + } + const end = closeIdx + delim.length; + parts.push({ text: input.slice(i, end), quoted: true, quoteChar: "$" }); + i = end; + continue; + } + } + } + buf += ch; + i++; + } else { + buf += ch; + i++; + } + } + + if (buf) { + parts.push({ text: buf, quoted: false }); + } + return parts; +} + +/** + * 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`) outside quoted values. + */ +export function canonicalizeType( + rawType: string | null | undefined, + dialect: CanonicalDialect, +): string { + if (!rawType) return "unknown"; + const trimmed = rawType.trim(); + if (!trimmed) return "unknown"; + + let normalized = splitSqlQuoted(trimmed, dialect) + .map((part) => { + if (part.quoted) return part.text; + return part.text + .toLowerCase() + .replace(/\s+/g, " ") + .replace(/\s*\(\s*/g, "(") + .replace(/\s*\)/g, ")") + .replace(/\)(?=[a-z])/g, ") ") + .replace(/\s*,\s*/g, ", "); + }) + .join(""); + + 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 (Object.prototype.hasOwnProperty.call(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; +} + +const SQL_RESERVED_KEYWORDS: ReadonlySet = new Set([ + "all", + "alter", + "analyse", + "analyze", + "and", + "any", + "array", + "as", + "asc", + "asymmetric", + "authorization", + "begin", + "between", + "binary", + "both", + "by", + "case", + "cast", + "check", + "collate", + "collation", + "column", + "commit", + "concurrently", + "constraint", + "create", + "cross", + "current_catalog", + "current_date", + "current_role", + "current_schema", + "current_time", + "current_timestamp", + "current_user", + "default", + "deferrable", + "delete", + "desc", + "distinct", + "do", + "drop", + "else", + "end", + "except", + "exists", + "false", + "fetch", + "filter", + "for", + "foreign", + "freeze", + "from", + "full", + "grant", + "group", + "having", + "if", + "ilike", + "in", + "index", + "initially", + "inner", + "insert", + "intersect", + "into", + "is", + "isnull", + "join", + "key", + "lateral", + "leading", + "left", + "like", + "limit", + "localtime", + "localtimestamp", + "natural", + "not", + "notnull", + "null", + "nulls", + "offset", + "on", + "only", + "or", + "order", + "outer", + "over", + "overlaps", + "partition", + "placing", + "primary", + "references", + "returning", + "revoke", + "right", + "rollback", + "row", + "rows", + "schema", + "select", + "session_user", + "set", + "similar", + "some", + "symmetric", + "system_user", + "table", + "tablesample", + "then", + "to", + "trailing", + "trigger", + "true", + "truncate", + "type", + "union", + "unique", + "update", + "user", + "using", + "values", + "variadic", + "verbose", + "view", + "when", + "where", + "window", + "with", +]); + +const DIALECT_EXTRA_RESERVED_KEYWORDS: Partial>> = { + mysql: new Set([ + "accessible", + "add", + "asensitive", + "before", + "bigint", + "blob", + "call", + "cascade", + "change", + "char", + "character", + "condition", + "continue", + "convert", + "cube", + "cume_dist", + "cursor", + "database", + "databases", + "dec", + "decimal", + "declare", + "delayed", + "dense_rank", + "describe", + "deterministic", + "distinctrow", + "div", + "double", + "dual", + "each", + "elseif", + "empty", + "enclosed", + "escaped", + "exit", + "explain", + "first_value", + "float", + "force", + "fulltext", + "function", + "generated", + "get", + "grouping", + "groups", + "high_priority", + "ignore", + "infile", + "inout", + "insensitive", + "int", + "integer", + "interval", + "iterate", + "json_table", + "keys", + "kill", + "lag", + "last_value", + "lead", + "leave", + "linear", + "lines", + "load", + "lock", + "long", + "longblob", + "longtext", + "loop", + "low_priority", + "match", + "maxvalue", + "mediumblob", + "mediumint", + "mediumtext", + "mod", + "modifies", + "no_write_to_binlog", + "nth_value", + "ntile", + "numeric", + "of", + "optimize", + "option", + "optionally", + "out", + "outfile", + "percent_rank", + "persist", + "persist_only", + "precision", + "procedure", + "purge", + "range", + "rank", + "read", + "reads", + "read_write", + "real", + "recursive", + "regexp", + "release", + "rename", + "repeat", + "replace", + "require", + "resignal", + "restrict", + "return", + "rlike", + "row_number", + "schemas", + "sensitive", + "separator", + "show", + "signal", + "smallint", + "spatial", + "specific", + "sql", + "sqlexception", + "sqlstate", + "sqlwarning", + "ssl", + "starting", + "stored", + "straight_join", + "system", + "terminated", + "tinyblob", + "tinyint", + "tinytext", + "undo", + "unlock", + "unsigned", + "usage", + "use", + "utc_date", + "utc_time", + "utc_timestamp", + "varbinary", + "varchar", + "varying", + "virtual", + "while", + "write", + "xor", + "zerofill", + ]), + mariadb: new Set([ + "accessible", + "add", + "asensitive", + "before", + "bigint", + "blob", + "call", + "cascade", + "change", + "char", + "character", + "condition", + "continue", + "convert", + "cursor", + "database", + "databases", + "dec", + "decimal", + "declare", + "delayed", + "describe", + "deterministic", + "distinctrow", + "div", + "double", + "dual", + "each", + "elseif", + "enclosed", + "escaped", + "exit", + "explain", + "float", + "force", + "fulltext", + "generated", + "get", + "high_priority", + "ignore", + "infile", + "inout", + "insensitive", + "int", + "integer", + "interval", + "iterate", + "keys", + "kill", + "leave", + "linear", + "lines", + "load", + "lock", + "long", + "longblob", + "longtext", + "loop", + "low_priority", + "match", + "maxvalue", + "mediumblob", + "mediumint", + "mediumtext", + "mod", + "modifies", + "no_write_to_binlog", + "numeric", + "optimize", + "option", + "optionally", + "out", + "outfile", + "precision", + "procedure", + "purge", + "range", + "read", + "reads", + "read_write", + "real", + "recursive", + "regexp", + "release", + "rename", + "repeat", + "replace", + "require", + "resignal", + "restrict", + "return", + "rlike", + "schemas", + "sensitive", + "separator", + "show", + "signal", + "smallint", + "spatial", + "specific", + "sql", + "sqlexception", + "sqlstate", + "sqlwarning", + "ssl", + "starting", + "stored", + "straight_join", + "terminated", + "tinyblob", + "tinyint", + "tinytext", + "undo", + "unlock", + "unsigned", + "usage", + "use", + "utc_date", + "utc_time", + "utc_timestamp", + "varbinary", + "varchar", + "varying", + "virtual", + "while", + "write", + "xor", + "zerofill", + ]), + sqlite: new Set([ + "abort", + "action", + "add", + "after", + "always", + "attach", + "autoincrement", + "before", + "cascade", + "conflict", + "current", + "database", + "deferred", + "detach", + "each", + "escape", + "exclude", + "exclusive", + "explain", + "fail", + "first", + "following", + "generated", + "glob", + "groups", + "ignore", + "immediate", + "indexed", + "instead", + "last", + "match", + "materialized", + "no", + "nothing", + "of", + "others", + "plan", + "pragma", + "preceding", + "query", + "raise", + "range", + "recursive", + "regexp", + "reindex", + "release", + "rename", + "replace", + "restrict", + "savepoint", + "temp", + "temporary", + "ties", + "transaction", + "unbounded", + "vacuum", + "virtual", + "without", + ]), + duckdb: new Set([ + "anti", + "asof", + "describe", + "pivot", + "positional", + "qualify", + "semi", + "summarize", + "try_cast", + "unpivot", + ]), + clickhouse: new Set([ + "final", + "format", + "global", + "paste", + "prewhere", + "sample", + "settings", + "totals", + ]), +}; + +function isNonUnquotableKeyword(identifier: string, dialect?: CanonicalDialect): boolean { + if (SQL_RESERVED_KEYWORDS.has(identifier)) return true; + if (dialect) { + return DIALECT_EXTRA_RESERVED_KEYWORDS[dialect]?.has(identifier) ?? false; + } + return false; +} + +/** + * Normalize SQL expressions (defaults, check constraints, index predicates, view definitions). + * Collapses whitespace outside quoted literals/identifiers while preserving all quoted tokens verbatim + * and keeping line-comment newline terminators intact. + */ +export function normalizeExpression( + expr: string | null | undefined, + dialect?: CanonicalDialect, +): string | null { + if (expr === null || expr === undefined) return null; + const trimmed = String(expr).trim(); + if (!trimmed) return null; + + return splitSqlQuoted(trimmed, dialect) + .map((part, idx, parts) => { + if (part.quoted) { + return part.text; + } + if (part.comment) { + return part.text.startsWith("--") || part.text.startsWith("#") + ? part.text.replace(/\r?\n\s*$/, "\n") + : part.text; + } + if ( + dialect === "postgresql" && + idx > 0 && + idx < parts.length - 1 && + parts[idx - 1].quoted && + parts[idx - 1].quoteChar === "'" && + parts[idx + 1].quoted && + parts[idx + 1].quoteChar === "'" && + /^\s*[\r\n]\s*$/.test(part.text) + ) { + return "\n"; + } + return part.text.replace(/\s+/g, " ").replace(/\(\s+/g, "(").replace(/\s+\)/g, ")"); + }) + .join("") + .trim(); +} + +/** + * Compute a dialect-aware comparison-only form of a SQL expression that equates + * simple unquoted identifiers with quoted lowercase non-keyword identifiers + * without mutating the executable SQL stored on the AST. + */ +export function normalizeExpressionForComparison( + expr: string | null | undefined, + dialect?: CanonicalDialect, +): string | null { + const normalized = normalizeExpression(expr, dialect); + if (normalized === null) return null; + + const isMySqlLike = dialect === "mysql" || dialect === "mariadb" || dialect === "clickhouse"; + const allowedQuotes = isMySqlLike + ? new Set(["`"]) + : dialect === "sqlite" + ? new Set(['"', "`"]) + : new Set(['"']); + + return splitSqlQuoted(normalized, dialect) + .map((part) => { + if (!part.quoted || !part.quoteChar || !allowedQuotes.has(part.quoteChar)) { + return part.text; + } + const inner = part.text.slice(1, -1); + if (/^[a-z_][a-z0-9_]*$/.test(inner) && !isNonUnquotableKeyword(inner, dialect)) { + return inner; + } + return part.text; + }) + .join("") + .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, dialect), + 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, + dialect: CanonicalDialect, +): 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, dialect), + ...(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, dialect), + 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, + dialect: CanonicalDialect, +): CanonicalCheck[] { + const checks: CanonicalCheck[] = (rawChecks || []).map((c: any) => ({ + name: String(c.name ?? c.constraint_name), + expression: + normalizeExpression(c.expression ?? c.definition ?? c.check_clause ?? "", dialect) || "", + })); + 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, dialect: CanonicalDialect): CanonicalView[] { + const views: CanonicalView[] = (rawViews || []).map((v: any) => { + const columns = Array.isArray(v.columns) + ? v.columns.map((c: unknown) => String(c)).filter(Boolean) + : undefined; + return { + name: String(v.name), + definition: normalizeExpression(v.definition, dialect) || "", + ...(columns && columns.length > 0 ? { columns } : {}), + }; + }); + views.sort((a, b) => compareNames(a.name, b.name)); + return views; +} + +function normalizePrimaryKeyColumns(t: any): string[] | undefined { + const seen = new Set(); + const addUnique = (name: string, out: string[]) => { + if (name && !seen.has(name)) { + seen.add(name); + out.push(name); + } + }; + + if (Array.isArray(t.primaryKeyColumns) && t.primaryKeyColumns.length > 0) { + const out: string[] = []; + for (const col of t.primaryKeyColumns) { + addUnique(String(col), out); + } + if (out.length > 0) return out; + } + + if (Array.isArray(t.primaryKeys) && t.primaryKeys.length > 0) { + const out: string[] = []; + for (const pk of t.primaryKeys) { + const name = + typeof pk === "string" ? pk : String(pk?.column_name ?? pk?.columnName ?? pk?.name ?? ""); + addUnique(name, out); + } + if (out.length > 0) return out; + } + + // Do not infer composite or single-column PK order from column ordinalPosition when + // explicit primaryKeyColumns/primaryKeys metadata is absent; leave primaryKeyColumns undefined. + return undefined; +} + +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) => { + const primaryKeyColumns = normalizePrimaryKeyColumns(t); + return { + name: String(t.name), + type: String(t.type || "BASE TABLE").toUpperCase(), + columns: normalizeColumns(t.columns, dialect), + ...(primaryKeyColumns && primaryKeyColumns.length > 0 ? { primaryKeyColumns } : {}), + indexes: normalizeIndexes(t.indexes, dialect), + foreignKeys: normalizeForeignKeys(t.foreignKeys), + checks: normalizeChecks(t.checks ?? t.checkConstraints, dialect), + 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, dialect); + + 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; + engine?: string; + schemas?: SchemaSnapshot[]; + collections?: MongoIntrospectionInput[]; + }, + dialectOverride?: string | CanonicalDialect, +): CanonicalSchemaAST { + const dialect = normalizeDialect( + dialectOverride ?? (input as any)?.engine ?? (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/ai.ts b/bridge/src/types/ai.ts index 3af4cccd..579908a8 100644 --- a/bridge/src/types/ai.ts +++ b/bridge/src/types/ai.ts @@ -1,5 +1,7 @@ // ── Shared types for the AI integration layer (moved from src/ai/ai.types.ts) +import type { IndexHealthReport, NormalizedExplainPlan } from "./performance"; + export type AIProviderName = "anthropic" | "openai" | "gemini" | "groq" | "mistral" | "ollama"; /** @@ -94,3 +96,44 @@ export interface AIRecommendChartParams extends AIRequestBase { } export interface AITestConnectionParams extends AIRequestBase {} + +// ── Performance & Index Copilot types ──────────────────────────────────── + +export type AIRecommendedIndex = { + schema?: string; + tableOrCollection: string; + indexName: string; + columns: string[]; + unique?: boolean; + reason: string; + ddlPreview: string; +}; + +export type AIDropIndexCandidate = { + schema?: string; + tableOrCollection: string; + indexName: string; + reason: string; +}; + +export type AIPerformanceAnalysisInput = { + dialect: string; + query: string; + plan: NormalizedExplainPlan; + indexHealth?: IndexHealthReport; + redactLiterals?: boolean; +}; + +export type AIPerformanceResult = { + summary: string; + estimatedImpact: "high" | "medium" | "low"; + rewrittenQuery?: string; + recommendedIndexes: AIRecommendedIndex[]; + dropCandidates: AIDropIndexCandidate[]; + warnings: string[]; +}; + +export type AIAnalyzePerformanceParams = AIRequestBase & { + input: AIPerformanceAnalysisInput; + skipCache?: boolean; +}; diff --git a/bridge/src/types/index.ts b/bridge/src/types/index.ts index cc95126d..3743e2d7 100644 --- a/bridge/src/types/index.ts +++ b/bridge/src/types/index.ts @@ -20,6 +20,8 @@ export * from "./mongo"; export * from "./mongoMigration"; export * from "./mongoBulk"; export * from "./ai"; +export * from "./schemaDiff"; +export * from "./performance"; export { SSHConfig } from "./common"; export enum DBType { diff --git a/bridge/src/types/performance.ts b/bridge/src/types/performance.ts new file mode 100644 index 00000000..99800893 --- /dev/null +++ b/bridge/src/types/performance.ts @@ -0,0 +1,80 @@ +/** + * Performance & Index Health Types + * + * Normalized types for EXPLAIN plan analysis and index health diagnostics + * across all supported SQL and NoSQL dialects. + */ + +export type ExplainBottleneckType = + "FULL_SCAN" | "FILESORT" | "TEMP_TABLE" | "HIGH_COST" | "LOW_SELECTIVITY"; + +export type ExplainBottleneck = { + type: ExplainBottleneckType; + target?: string; + details: string; + severity: "warning" | "critical"; +}; + +export type ExplainPlanNode = { + nodeType: string; + relation?: string; + indexName?: string; + cost?: number; + rows?: number; + actualRows?: number; + actualTimeMs?: number; + filter?: string; + children: ExplainPlanNode[]; +}; + +export type NormalizedExplainPlan = { + dialect: string; + query: string; + analyzed: boolean; + executionTimeMs?: number; + planningTimeMs?: number; + totalCost?: number; + rowsExamined?: number; + rowsReturned?: number; + bottlenecks: ExplainBottleneck[]; + planTree: ExplainPlanNode; + rawPlan: unknown; +}; + +export type IndexHealthEntry = { + schema?: string; + tableOrCollection: string; + indexName: string; + columns: string[]; + indexType?: string; + isUnique: boolean; + isPrimary: boolean; + sqlDefinition?: string; + predicate?: string | null; + isPartial?: boolean; + scans: number | null; + sizeBytes: number | null; + status: "healthy" | "unused" | "duplicate"; + duplicateOf?: string; +}; + +export type DuplicateIndexPair = { + schema?: string; + tableOrCollection: string; + indexName: string; + redundantWith: string; + reason: string; +}; + +export type IndexHealthReport = { + dialect: string; + indexes: IndexHealthEntry[]; + unusedIndexes: IndexHealthEntry[]; + duplicateIndexes: DuplicateIndexPair[]; + summary: { + total: number; + unusedCount: number; + duplicateCount: number; + totalSizeBytes: number; + }; +}; diff --git a/bridge/src/types/schemaDiff.ts b/bridge/src/types/schemaDiff.ts new file mode 100644 index 00000000..f4faa154 --- /dev/null +++ b/bridge/src/types/schemaDiff.ts @@ -0,0 +1,163 @@ +/** + * 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[]; + primaryKeyColumns?: string[]; + indexes: CanonicalIndex[]; + foreignKeys: CanonicalForeignKey[]; + checks: CanonicalCheck[]; + comment?: string | null; +} + +export interface CanonicalEnum { + name: string; + values: string[]; +} + +export interface CanonicalView { + name: string; + definition: string; + columns?: 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[]; + coverageWarnings?: string[]; +} diff --git a/src/__tests__/explainPlanAndIndexHealth.test.ts b/src/__tests__/explainPlanAndIndexHealth.test.ts new file mode 100644 index 00000000..6ce54e82 --- /dev/null +++ b/src/__tests__/explainPlanAndIndexHealth.test.ts @@ -0,0 +1,365 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { + computeSelectivityRatio, + countPlanNodes, + getWorstSeverity, +} from "../features/workspace/components/ExplainPlanDialog"; +import { + buildScaffoldDropPayload, + filterIndexHealthEntries, + formatIndexBytes, +} from "../features/database/components/IndexHealthPanel"; +import type { ExplainBottleneck, ExplainPlanNode } from "../services/bridge/query"; +import { + normalizeIndexHealthEntry, + normalizeIndexHealthReport, + type IndexHealthEntry, +} from "../services/bridge/indexHealth"; +import { indexHealthKeys } from "../features/database/hooks/useIndexHealth"; + +describe("ExplainPlanDialog pure helpers", () => { + it("computeSelectivityRatio computes ratio and handles invalid/edge inputs", () => { + assert.equal(computeSelectivityRatio(1000, 250), 0.25); + assert.equal(computeSelectivityRatio(500, 0), 0); + assert.equal(computeSelectivityRatio(0, 10), null); + assert.equal(computeSelectivityRatio(-5, 10), null); + assert.equal(computeSelectivityRatio(100, -1), null); + assert.equal(computeSelectivityRatio(undefined, 10), null); + assert.equal(computeSelectivityRatio(100, undefined), null); + assert.equal(computeSelectivityRatio(Number.NaN, 10), null); + }); + + it("countPlanNodes recursively counts tree nodes", () => { + assert.equal(countPlanNodes(null), 0); + assert.equal(countPlanNodes(undefined), 0); + + const leaf: ExplainPlanNode = { nodeType: "Seq Scan", relation: "users", children: [] }; + assert.equal(countPlanNodes(leaf), 1); + + const tree: ExplainPlanNode = { + nodeType: "Hash Join", + children: [ + { + nodeType: "Seq Scan", + relation: "orders", + children: [], + }, + { + nodeType: "Hash", + children: [ + { + nodeType: "Index Scan", + relation: "users", + indexName: "idx_users_id", + children: [], + }, + ], + }, + ], + }; + assert.equal(countPlanNodes(tree), 4); + }); + + it("getWorstSeverity returns highest severity across bottlenecks", () => { + assert.equal(getWorstSeverity([]), "none"); + + const warningsOnly: ExplainBottleneck[] = [ + { type: "HIGH_COST", details: "Cost exceeds threshold", severity: "warning" }, + ]; + assert.equal(getWorstSeverity(warningsOnly), "warning"); + + const mixed: ExplainBottleneck[] = [ + { type: "HIGH_COST", details: "Cost exceeds threshold", severity: "warning" }, + { + type: "FULL_SCAN", + target: "orders", + details: "Sequential scan on 1M rows", + severity: "critical", + }, + ]; + assert.equal(getWorstSeverity(mixed), "critical"); + }); +}); + +describe("IndexHealthPanel pure helpers", () => { + const SAMPLE_INDEXES: IndexHealthEntry[] = [ + { + name: "users_pkey", + tableOrCollection: "users", + schema: "public", + columns: ["id"], + primary: true, + unique: true, + scans: 45200, + sizeBytes: 1048576, + status: "healthy", + }, + { + name: "idx_orders_legacy_status", + tableOrCollection: "orders", + schema: "public", + columns: ["legacy_status"], + scans: 0, + sizeBytes: 524288, + status: "unused", + reason: "0 scans since stats reset", + }, + { + name: "idx_orders_user_dup", + tableOrCollection: "orders", + schema: "analytics", + columns: ["user_id", "created_at"], + scans: 12, + sizeBytes: 262144, + status: "duplicate", + redundantWith: "idx_orders_user_created", + }, + ]; + + it("filterIndexHealthEntries filters by status pill", () => { + assert.equal(filterIndexHealthEntries(SAMPLE_INDEXES, "all", "").length, 3); + assert.deepEqual( + filterIndexHealthEntries(SAMPLE_INDEXES, "unused", "").map((e) => e.name), + ["idx_orders_legacy_status"], + ); + assert.deepEqual( + filterIndexHealthEntries(SAMPLE_INDEXES, "duplicate", "").map((e) => e.name), + ["idx_orders_user_dup"], + ); + assert.deepEqual( + filterIndexHealthEntries(SAMPLE_INDEXES, "healthy", "").map((e) => e.name), + ["users_pkey"], + ); + }); + + it("filterIndexHealthEntries filters by search term across name, table, schema, and columns", () => { + assert.deepEqual( + filterIndexHealthEntries(SAMPLE_INDEXES, "all", "LEGACY_STATUS").map((e) => e.name), + ["idx_orders_legacy_status"], + ); + assert.deepEqual( + filterIndexHealthEntries(SAMPLE_INDEXES, "all", "analytics").map((e) => e.name), + ["idx_orders_user_dup"], + ); + assert.deepEqual( + filterIndexHealthEntries(SAMPLE_INDEXES, "all", "created_at").map((e) => e.name), + ["idx_orders_user_dup"], + ); + assert.equal(filterIndexHealthEntries(SAMPLE_INDEXES, "unused", "analytics").length, 0); + }); + + it("formatIndexBytes formats byte values into readable units", () => { + assert.equal(formatIndexBytes(undefined), "—"); + assert.equal(formatIndexBytes(-10), "—"); + assert.equal(formatIndexBytes(Number.NaN), "—"); + assert.equal(formatIndexBytes(0), "0 B"); + assert.equal(formatIndexBytes(512), "512 B"); + assert.equal(formatIndexBytes(1536), "1.5 KB"); + assert.equal(formatIndexBytes(1048576), "1.0 MB"); + assert.equal(formatIndexBytes(2 * 1024 * 1024 * 1024), "2.0 GB"); + }); + + it("normalizeIndexHealthEntry and normalizeIndexHealthReport map bridge fields and preserve isOffline", () => { + const mapped = normalizeIndexHealthEntry({ + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_dup", + columns: ["user_id"], + isUnique: true, + isPrimary: false, + scans: null, + sizeBytes: 4096, + status: "duplicate", + duplicateOf: "idx_orders_user_created", + }); + + assert.equal(mapped.name, "idx_orders_dup"); + assert.equal(mapped.unique, true); + assert.equal(mapped.primary, false); + assert.equal(mapped.scans, undefined); + assert.equal(mapped.sizeBytes, 4096); + assert.equal(mapped.redundantWith, "idx_orders_user_created"); + + const partial = normalizeIndexHealthEntry({ + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_active", + columns: ["created_at"], + indexType: "gin", + status: "unused", + sqlDefinition: + "CREATE INDEX idx_orders_active ON public.orders USING gin (created_at) WHERE (active = true)", + predicate: "(active = true)", + isPartial: true, + }); + assert.equal(partial.indexType, "gin"); + assert.equal( + partial.sqlDefinition, + "CREATE INDEX idx_orders_active ON public.orders USING gin (created_at) WHERE (active = true)", + ); + assert.equal(partial.predicate, "(active = true)"); + assert.equal(partial.isPartial, true); + + const partialWithoutPredicate = normalizeIndexHealthEntry({ + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_partial_unknown", + columns: ["created_at"], + status: "unused", + predicate: null, + isPartial: true, + }); + assert.equal(partialWithoutPredicate.predicate, null); + assert.equal(partialWithoutPredicate.isPartial, true); + + const report = normalizeIndexHealthReport({ + ok: true, + isOffline: true, + data: { + dialect: "postgresql", + indexes: [ + { + tableOrCollection: "orders", + indexName: "orders_pkey", + columns: ["id"], + isUnique: true, + isPrimary: true, + scans: 10, + sizeBytes: 8192, + status: "healthy", + }, + ], + unusedIndexes: [], + duplicateIndexes: [], + summary: { total: 1, unusedCount: 0, duplicateCount: 0, totalSizeBytes: 8192 }, + }, + }); + + assert.equal(report.isOffline, true); + assert.equal(report.indexes[0].name, "orders_pkey"); + assert.equal(report.indexes[0].primary, true); + assert.equal(report.summary.total, 1); + }); + + it("indexHealthKeys.detail keeps all-tables scope distinct from table named 'all'", () => { + assert.notDeepEqual(indexHealthKeys.detail("db-1"), indexHealthKeys.detail("db-1", "all")); + assert.deepEqual(indexHealthKeys.detail("db-1"), ["indexHealth", "db-1", null]); + assert.deepEqual(indexHealthKeys.detail("db-1", "all"), ["indexHealth", "db-1", "all"]); + }); + + it("buildScaffoldDropPayload propagates unique flag and metadata for each selected index", () => { + const entries: IndexHealthEntry[] = [ + { + name: "idx_users_email_uq", + tableOrCollection: "users", + schema: "public", + columns: ["email"], + unique: true, + status: "duplicate", + }, + { + name: "idx_orders_legacy", + tableOrCollection: "orders", + schema: "public", + columns: ["legacy_id"], + unique: false, + status: "unused", + }, + { + name: "idx_logs_created", + tableOrCollection: "logs", + columns: ["created_at"], + status: "unused", + }, + ]; + + const payload = buildScaffoldDropPayload("proj-1", entries, { + save: true, + confirmDestructive: true, + concurrentIndexes: true, + name: "drop_redundant", + }); + + assert.equal(payload.projectId, "proj-1"); + assert.equal(payload.save, true); + assert.equal(payload.confirmDestructive, true); + assert.equal(payload.concurrentIndexes, true); + assert.equal(payload.name, "drop_redundant"); + assert.deepEqual(payload.dropIndexes, [ + { + schema: "public", + tableOrCollection: "users", + indexName: "idx_users_email_uq", + columns: ["email"], + unique: true, + }, + { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_legacy", + columns: ["legacy_id"], + unique: false, + }, + { + schema: undefined, + tableOrCollection: "logs", + indexName: "idx_logs_created", + columns: ["created_at"], + }, + ]); + }); + + it("buildScaffoldDropPayload forwards partial-index metadata and indexType when defined", () => { + const entries: IndexHealthEntry[] = [ + { + name: "idx_orders_active", + tableOrCollection: "orders", + schema: "public", + columns: ["created_at"], + unique: false, + indexType: "gin", + status: "unused", + sqlDefinition: + "CREATE INDEX idx_orders_active ON public.orders USING gin (created_at) WHERE (active = true)", + predicate: "(active = true)", + isPartial: true, + }, + { + name: "idx_orders_partial_null_pred", + tableOrCollection: "orders", + schema: "public", + columns: ["updated_at"], + indexType: "hash", + status: "unused", + predicate: null, + isPartial: true, + }, + ]; + + const payload = buildScaffoldDropPayload("proj-1", entries); + assert.deepEqual(payload.dropIndexes, [ + { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_active", + columns: ["created_at"], + unique: false, + indexType: "gin", + sqlDefinition: + "CREATE INDEX idx_orders_active ON public.orders USING gin (created_at) WHERE (active = true)", + predicate: "(active = true)", + isPartial: true, + }, + { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_partial_null_pred", + columns: ["updated_at"], + indexType: "hash", + predicate: null, + isPartial: true, + }, + ]); + }); +}); diff --git a/src/__tests__/performanceCopilot.test.ts b/src/__tests__/performanceCopilot.test.ts new file mode 100644 index 00000000..011dc596 --- /dev/null +++ b/src/__tests__/performanceCopilot.test.ts @@ -0,0 +1,144 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { + shouldDefaultRedactLiterals, + buildScaffoldCreatePayload, +} from "../features/workspace/components/ExplainPlanDialog"; +import { + getIndexSelectionKey, + toggleSelectedIndexKey, + isDroppableIndexEntry, + buildScaffoldDropPayload, +} from "../features/database/components/IndexHealthPanel"; +import type { AIRecommendedIndex } from "../services/bridge/ai"; +import type { IndexHealthEntry } from "../services/bridge/indexHealth"; + +describe("Performance Copilot pure helpers", () => { + it("shouldDefaultRedactLiterals returns false only for local ollama", () => { + assert.equal(shouldDefaultRedactLiterals("ollama"), false); + assert.equal(shouldDefaultRedactLiterals("openai"), true); + assert.equal(shouldDefaultRedactLiterals("anthropic"), true); + assert.equal(shouldDefaultRedactLiterals("gemini"), true); + assert.equal(shouldDefaultRedactLiterals("groq"), true); + assert.equal(shouldDefaultRedactLiterals("mistral"), true); + assert.equal(shouldDefaultRedactLiterals(undefined), true); + }); + + it("buildScaffoldCreatePayload constructs createIndexes migration payload", () => { + const rec: AIRecommendedIndex = { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_customer_status", + columns: ["customer_id", "status"], + unique: false, + reason: "Eliminates sequential scan on orders", + ddlPreview: "CREATE INDEX idx_orders_customer_status ON public.orders (customer_id, status);", + }; + + const previewPayload = buildScaffoldCreatePayload("proj-1", rec, true); + assert.deepEqual(previewPayload, { + projectId: "proj-1", + name: "add_idx_orders_customer_status", + save: false, + concurrentIndexes: true, + createIndexes: [ + { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_customer_status", + columns: ["customer_id", "status"], + unique: false, + }, + ], + }); + + const savePayload = buildScaffoldCreatePayload("proj-1", rec, false, true); + assert.equal(savePayload.save, true); + assert.equal(savePayload.concurrentIndexes, false); + }); + + it("toggleSelectedIndexKey toggles keys immutably", () => { + const k1 = getIndexSelectionKey({ + schema: "public", + tableOrCollection: "orders", + name: "idx_old", + }); + const k2 = getIndexSelectionKey({ + tableOrCollection: "users", + name: "idx_dup", + }); + + assert.equal(k1, "public::orders::idx_old"); + assert.equal(k2, "::users::idx_dup"); + + const initial: string[] = []; + const addedOne = toggleSelectedIndexKey(initial, k1); + assert.deepEqual(initial, []); + assert.deepEqual(addedOne, [k1]); + + const addedTwo = toggleSelectedIndexKey(addedOne, k2); + assert.deepEqual(addedTwo, [k1, k2]); + + const removedOne = toggleSelectedIndexKey(addedTwo, k1); + assert.deepEqual(removedOne, [k2]); + }); + + it("isDroppableIndexEntry allows only non-primary unused or duplicate indexes", () => { + const base: IndexHealthEntry = { + name: "idx_test", + tableOrCollection: "orders", + columns: ["status"], + status: "unused", + }; + + assert.equal(isDroppableIndexEntry(base), true); + assert.equal(isDroppableIndexEntry({ ...base, status: "duplicate" }), true); + assert.equal(isDroppableIndexEntry({ ...base, status: "healthy" }), false); + assert.equal(isDroppableIndexEntry({ ...base, status: "unused", primary: true }), false); + }); + + it("buildScaffoldDropPayload constructs dropIndexes migration payload", () => { + const entries: IndexHealthEntry[] = [ + { + name: "idx_orders_legacy", + tableOrCollection: "orders", + schema: "public", + columns: ["legacy_col"], + status: "unused", + }, + { + name: "idx_orders_dup", + tableOrCollection: "orders", + columns: ["user_id"], + status: "duplicate", + }, + ]; + + const payload = buildScaffoldDropPayload("proj-42", entries, { + save: true, + confirmDestructive: true, + }); + + assert.deepEqual(payload, { + projectId: "proj-42", + name: "drop_2_indexes", + save: true, + confirmDestructive: true, + concurrentIndexes: false, + dropIndexes: [ + { + schema: "public", + tableOrCollection: "orders", + indexName: "idx_orders_legacy", + columns: ["legacy_col"], + }, + { + schema: undefined, + tableOrCollection: "orders", + indexName: "idx_orders_dup", + columns: ["user_id"], + }, + ], + }); + }); +}); diff --git a/src/__tests__/schemaDiffMigration.test.ts b/src/__tests__/schemaDiffMigration.test.ts new file mode 100644 index 00000000..13fcce73 --- /dev/null +++ b/src/__tests__/schemaDiffMigration.test.ts @@ -0,0 +1,576 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import React from "react"; +import ReactDOMServer from "react-dom/server"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { + canSaveGeneratedMigration, + computeMigrationContentHash, + doPreviewInputsMatch, + filterDiffItems, + groupDiffItemsByTarget, + hasRequiredRefs, + normalizePreviewInputs, + reducePendingStageFile, + toggleRenameCandidateId, + useSchemaDiffMigration, +} from "../features/database/hooks/useSchemaDiffMigration"; +import { getNoChangesStatusCopy } from "../features/database/components/SchemaDiffMigrationDialog"; +import { + migrationService, + type GeneratedMigrationResult, + type SchemaDiffItem, +} from "../services/bridge/migration"; +import { DatabaseBridge } from "../services/bridge/databaseBridge"; + +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); + }); + + it("matches preview input snapshots canonically and rejects mismatched or pending saves", () => { + const base = normalizePreviewInputs({ + projectId: "proj-1", + mode: "ref-vs-ref", + sourceRef: " main ", + targetRef: "feature", + migrationName: " add_bio ", + acceptRenameIds: ["b", "a"], + concurrentIndexes: false, + }); + + const reordered = normalizePreviewInputs({ + projectId: "proj-1", + mode: "ref-vs-ref", + sourceRef: "main", + targetRef: " feature ", + migrationName: "add_bio", + acceptRenameIds: ["a", "b"], + concurrentIndexes: false, + }); + + const changedTarget = normalizePreviewInputs({ + projectId: "proj-1", + mode: "ref-vs-ref", + sourceRef: "main", + targetRef: "HEAD~1", + migrationName: "add_bio", + acceptRenameIds: ["a", "b"], + concurrentIndexes: false, + }); + + const changedMigrationName = normalizePreviewInputs({ + projectId: "proj-1", + mode: "ref-vs-ref", + sourceRef: "main", + targetRef: "feature", + migrationName: "add_bio_v2", + acceptRenameIds: ["a", "b"], + concurrentIndexes: false, + }); + + assert.equal(doPreviewInputsMatch(null, base), false); + assert.equal(doPreviewInputsMatch(base, reordered), true); + assert.equal(doPreviewInputsMatch(base, changedTarget), false); + assert.equal(doPreviewInputsMatch(base, changedMigrationName), false); + + assert.equal( + canSaveGeneratedMigration({ + generated: makeGenerated(), + confirmDestructive: false, + isSaving: false, + isScanning: true, + previewMatchesInputs: true, + }), + false, + ); + assert.equal( + canSaveGeneratedMigration({ + generated: makeGenerated(), + confirmDestructive: false, + isSaving: false, + isGeneratingPreview: true, + previewMatchesInputs: true, + }), + false, + ); + assert.equal( + canSaveGeneratedMigration({ + generated: makeGenerated(), + confirmDestructive: false, + isSaving: false, + hasRequiredRefs: false, + previewMatchesInputs: true, + }), + false, + ); + assert.equal( + canSaveGeneratedMigration({ + generated: makeGenerated(), + confirmDestructive: false, + isSaving: false, + previewMatchesInputs: false, + }), + false, + ); + }); + + it("computes SHA-256 hex digest with CRLF normalized to LF", async () => { + const lfSql = "-- +goose Up\nALTER TABLE users ADD COLUMN bio text;\n"; + const crlfSql = "-- +goose Up\r\nALTER TABLE users ADD COLUMN bio text;\r\n"; + + const expected = createHash("sha256").update(lfSql, "utf8").digest("hex"); + const lfHash = await computeMigrationContentHash(lfSql); + const crlfHash = await computeMigrationContentHash(crlfSql); + + assert.equal(lfHash, expected); + assert.equal(crlfHash, expected); + assert.match(lfHash, /^[0-9a-f]{64}$/); + assert.notEqual(await computeMigrationContentHash(`${lfSql}SELECT 1;`), expected); + }); + + it("preserves pendingStageFile recovery state across scans/option changes and clears only on stage/dismiss/close", () => { + const pending = { + filepath: "migrations/20261128_add_bio.sql", + filename: "20261128_add_bio.sql", + }; + + const failedState = reducePendingStageFile(null, { type: "stage_failed", file: pending }); + assert.deepEqual(failedState, pending); + + // Re-scan, preview updates, and mode/ref/rename/concurrent option changes preserve recovery state + assert.deepEqual(reducePendingStageFile(failedState, { type: "scan_started" }), pending); + assert.deepEqual(reducePendingStageFile(failedState, { type: "preview_updated" }), pending); + assert.deepEqual(reducePendingStageFile(failedState, { type: "options_changed" }), pending); + + // Cleared only after successful staging, explicit dismissal, or dialog close + assert.equal(reducePendingStageFile(failedState, { type: "stage_succeeded" }), null); + assert.equal(reducePendingStageFile(failedState, { type: "dismissed" }), null); + assert.equal(reducePendingStageFile(failedState, { type: "dialog_closed" }), null); + }); + + it("defaults omitted migrationName to empty string in normalizePreviewInputs", () => { + const omitted = normalizePreviewInputs({ + projectId: "proj-1", + mode: "live-vs-snapshot", + sourceRef: "", + targetRef: "", + acceptRenameIds: [], + concurrentIndexes: false, + }); + const whitespace = normalizePreviewInputs({ + projectId: "proj-1", + mode: "live-vs-snapshot", + sourceRef: "", + targetRef: "", + migrationName: " ", + acceptRenameIds: [], + concurrentIndexes: false, + }); + assert.equal(omitted.migrationName, ""); + assert.equal(doPreviewInputsMatch(omitted, whitespace), true); + }); + + it("DatabaseBridge.listMigrations forwards optional projectRoot and projectId", async () => { + const calls: Array<{ method: string; params: Record }> = []; + const mockBridge = new DatabaseBridge((async ( + method: string, + params: Record, + ) => { + calls.push({ method, params }); + return { ok: true, data: { appliedMigrations: [], localMigrations: [] } }; + }) as any); + + await mockBridge.listMigrations("db-1", undefined, "proj-42"); + await mockBridge.listMigrations("db-1", "/repo", "proj-42"); + await mockBridge.listMigrations("db-1"); + + assert.deepEqual(calls, [ + { method: "migration.list", params: { dbId: "db-1", projectId: "proj-42" } }, + { + method: "migration.list", + params: { dbId: "db-1", projectRoot: "/repo", projectId: "proj-42" }, + }, + { method: "migration.list", params: { dbId: "db-1" } }, + ]); + }); + + it("DatabaseBridge.applyMongoMigration and rollbackMongoMigration forward optional projectId", async () => { + const calls: Array<{ method: string; params: Record }> = []; + const mockBridge = new DatabaseBridge((async ( + method: string, + params: Record, + ) => { + calls.push({ method, params }); + return { ok: true, data: { success: true } }; + }) as any); + + await mockBridge.applyMongoMigration("db-1", { + version: "20261129_01", + dryRun: true, + projectId: "proj-9", + ownerId: "owner-1", + }); + await mockBridge.applyMongoMigration("db-1"); + await mockBridge.rollbackMongoMigration("db-1", "20261129_01", { + force: true, + projectRoot: "/repo", + projectId: "proj-9", + }); + + assert.deepEqual(calls, [ + { + method: "migration.apply", + params: { + dbId: "db-1", + version: "20261129_01", + dryRun: true, + projectId: "proj-9", + ownerId: "owner-1", + }, + }, + { + method: "migration.apply", + params: { dbId: "db-1" }, + }, + { + method: "migration.rollback", + params: { + dbId: "db-1", + version: "20261129_01", + force: true, + projectRoot: "/repo", + projectId: "proj-9", + }, + }, + ]); + }); + + it("getNoChangesStatusCopy distinguishes complete sync from incomplete schema coverage", () => { + const complete = getNoChangesStatusCopy({ + sourceLabel: "snapshot", + targetLabel: "live", + coverageWarnings: [], + }); + assert.equal(complete.hasCoverageWarnings, false); + assert.equal(complete.inspectorTitle, "Schemas are in sync"); + assert.equal( + complete.inspectorDescription, + "No differences detected between snapshot and live.", + ); + assert.equal(complete.previewMessage, "No migration needed."); + + const incomplete = getNoChangesStatusCopy({ + sourceLabel: "snapshot", + targetLabel: "live", + coverageWarnings: ["Snapshot does not include view definitions; views were skipped."], + }); + assert.equal(incomplete.hasCoverageWarnings, true); + assert.equal(incomplete.inspectorTitle, "No differences confirmed in comparable objects"); + assert.match(incomplete.inspectorDescription, /Coverage is incomplete/i); + assert.doesNotMatch(incomplete.inspectorTitle, /in sync/i); + assert.doesNotMatch(incomplete.previewMessage, /No migration needed/i); + }); + + it("useSchemaDiffMigration.generatePreview resets confirmDestructive for active preview and ignores stale responses", async () => { + const internals = (React as any) + .__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE; + let origUseState: any; + let origUseRef: any; + const origGenerateFromDiff = migrationService.generateFromDiff; + + const queryClient = new QueryClient(); + const stateSlots: any[] = []; + const refSlots: Array<{ current: any }> = []; + let hookResult!: ReturnType; + + function Harness() { + let stateIdx = 0; + let refIdx = 0; + if (!origUseState && internals?.H) { + origUseState = internals.H.useState; + origUseRef = internals.H.useRef; + } + internals.H.useState = (initial: any) => { + const slot = stateIdx++; + if (!(slot in stateSlots)) { + stateSlots[slot] = typeof initial === "function" ? initial() : initial; + } + const setState = (updater: any) => { + stateSlots[slot] = typeof updater === "function" ? updater(stateSlots[slot]) : updater; + }; + return [stateSlots[slot], setState]; + }; + internals.H.useRef = (initial: any) => { + const slot = refIdx++; + if (!(slot in refSlots)) { + refSlots[slot] = { current: initial }; + } + return refSlots[slot]; + }; + try { + hookResult = useSchemaDiffMigration({ + projectId: "proj-1", + dbId: "db-1", + open: false, + }); + } finally { + if (origUseState && internals?.H) { + internals.H.useState = origUseState; + internals.H.useRef = origUseRef; + } + } + return null; + } + + const render = () => { + ReactDOMServer.renderToStaticMarkup( + React.createElement( + QueryClientProvider, + { client: queryClient }, + React.createElement(Harness), + ), + ); + }; + + try { + const previewA = makeGenerated({ filename: "20261129_a.sql", hasDestructive: true }); + const previewB = makeGenerated({ filename: "20261129_b.sql", hasDestructive: true }); + const previewStale = makeGenerated({ filename: "20261129_stale.sql", hasDestructive: true }); + + let nextPreview = previewA; + migrationService.generateFromDiff = async () => nextPreview; + + render(); + await hookResult.generatePreview(); + render(); + + assert.equal(hookResult.generated?.filename, "20261129_a.sql"); + assert.equal(hookResult.confirmDestructive, false); + + // User confirms destructive preview A + hookResult.setConfirmDestructive(true); + render(); + assert.equal(hookResult.confirmDestructive, true); + + // Regenerating preview B clears confirmDestructive when preview B is accepted + nextPreview = previewB; + await hookResult.generatePreview({ name: "updated_name" }); + render(); + assert.equal(hookResult.generated?.filename, "20261129_b.sql"); + assert.equal(hookResult.confirmDestructive, false); + + // Stale response arriving after a newer active request must NOT reset confirmation + let resolveStale!: (value: GeneratedMigrationResult) => void; + let resolveActive!: (value: GeneratedMigrationResult) => void; + let callCount = 0; + migrationService.generateFromDiff = () => { + callCount++; + if (callCount === 1) { + return new Promise((res) => { + resolveStale = res; + }); + } + return new Promise((res) => { + resolveActive = res; + }); + }; + + const stalePromise = hookResult.generatePreview({ name: "first" }); + const activePromise = hookResult.generatePreview({ name: "second" }); + resolveActive(previewB); + await activePromise; + render(); + + hookResult.setConfirmDestructive(true); + render(); + assert.equal(hookResult.confirmDestructive, true); + + resolveStale(previewStale); + await stalePromise; + render(); + + assert.equal(hookResult.generated?.filename, "20261129_b.sql"); + assert.equal(hookResult.confirmDestructive, true); + } finally { + if (origUseState && internals?.H) { + internals.H.useState = origUseState; + internals.H.useRef = origUseRef; + } + migrationService.generateFromDiff = origGenerateFromDiff; + } + }); +}); diff --git a/src/features/database/components/DataViewPanel.tsx b/src/features/database/components/DataViewPanel.tsx index 3aebdcd0..9c5ff3cb 100644 --- a/src/features/database/components/DataViewPanel.tsx +++ b/src/features/database/components/DataViewPanel.tsx @@ -7,6 +7,7 @@ import { ChevronDown, PanelLeftClose, PanelLeft, + Activity, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Spinner } from "@/components/ui/spinner"; @@ -47,6 +48,7 @@ interface DataViewPanelProps { // Actions onRefresh: () => void; onMigrationsOpen: () => void; + onIndexHealthOpen?: () => void; onExport: (format: "csv" | "json") => void; isExporting: boolean; onChart: () => void; @@ -91,6 +93,7 @@ export const DataViewPanel = ({ onToggleSidebar, onRefresh, onMigrationsOpen, + onIndexHealthOpen, onExport, isExporting, onChart, @@ -164,6 +167,12 @@ export const DataViewPanel = ({
+ {onIndexHealthOpen && ( + + )} +
+ ); + } + + 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 + +
+ +
+ {selectedEntries.length > 0 && ( + + )} + + +
+
+ + {/* 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}`); + const selectionKey = getIndexSelectionKey(entry); + const droppable = isDroppableIndexEntry(entry); + const isSelected = selectedKeys.includes(selectionKey); + + return ( + + + {droppable ? ( + + setSelectedKeys((prev) => toggleSelectedIndexKey(prev, selectionKey)) + } + aria-label={`Select ${entry.name} for drop migration`} + /> + ) : null} + + +
+ {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 + + )} +
+
+ ); + })} +
+
+ + )} + + + {/* Drop Index Migration Preview & Destructive Confirmation Dialog */} + { + if (!nextOpen && !isSavingDrop) { + closeDropDialog(); + } + }} + > + + + + + Scaffold Drop Index Migration + + + Review the generated migration to drop {previewedEntries.length}{" "} + {previewedEntries.length === 1 ? "index" : "indexes"} + {dropPreview?.filename ? ` (${dropPreview.filename})` : ""}. + + + +
+
+ +
+

Destructive operation

+

+ Dropping indexes can degrade query performance if an index is still needed by + infrequent workloads or reporting queries. +

+
+
+ +
+ {previewedEntries.map((e) => ( + + {e.schema ? `${e.schema}.${e.tableOrCollection}` : e.tableOrCollection}.{e.name} + + ))} +
+ + {isPreviewingDrop ? ( +
+ + Generating drop migration preview… +
+ ) : dropError ? ( +
+ {dropError} +
+ ) : dropPreview ? ( + <> + {dropPreview.warnings.length > 0 && ( +
+ {dropPreview.warnings.map((w, idx) => ( +
+ + {w} +
+ ))} +
+ )} + + +
+                    {dropPreview.content}
+                  
+
+ + ) : null} + +
+ setConfirmDestructive(Boolean(checked))} + disabled={isPreviewingDrop || isSavingDrop} + /> + +
+
+ + + + + +
+
+ + ); +} diff --git a/src/features/database/components/MigrationsPanel.tsx b/src/features/database/components/MigrationsPanel.tsx index f30157e9..1efa721f 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, @@ -39,7 +54,7 @@ export default function MigrationsPanel({ migrations, baselined, dbId }: Migrati handleDelete, handleViewSQL, setShowSQLDialog, - } = useMigrationsPanel({ migrations, baselined, dbId }); + } = useMigrationsPanel({ migrations, baselined, dbId, projectId: effectiveProjectId }); if (isRefreshing) { return ; @@ -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..19e0103e --- /dev/null +++ b/src/features/database/components/SchemaDiffMigrationDialog.tsx @@ -0,0 +1,686 @@ +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, SchemaDiffResult } 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 ; +} + +export interface NoChangesStatusCopy { + hasCoverageWarnings: boolean; + inspectorTitle: string; + inspectorDescription: string; + previewMessage: string; +} + +/** + * Returns inspector and preview copy when a schema diff reports `hasChanges: false`, + * avoiding "in sync" / "no migration needed" claims when schema coverage is incomplete. + */ +export function getNoChangesStatusCopy( + diffResult: Pick, +): NoChangesStatusCopy { + const hasCoverageWarnings = Boolean( + diffResult.coverageWarnings && diffResult.coverageWarnings.length > 0, + ); + if (hasCoverageWarnings) { + return { + hasCoverageWarnings: true, + inspectorTitle: "No differences confirmed in comparable objects", + inspectorDescription: `No differences were detected among comparable objects between ${diffResult.sourceLabel} and ${diffResult.targetLabel}. Coverage is incomplete — review warnings above.`, + previewMessage: "Coverage is incomplete — review warnings above.", + }; + } + return { + hasCoverageWarnings: false, + inspectorTitle: "Schemas are in sync", + inspectorDescription: `No differences detected between ${diffResult.sourceLabel} and ${diffResult.targetLabel}.`, + previewMessage: "No migration needed.", + }; +} + +/** + * 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, + previewMatchesInputs, + hasPendingStageRetry, + runDiff, + generatePreview, + saveMigration, + } = useSchemaDiffMigration({ + projectId, + dbId, + projectDir, + open, + onSaved: (meta) => { + onSaved?.(); + if (!meta?.stagingFailed) { + 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 = ( + inputId: string, + label: string, + value: string, + onChange: (val: string) => void, + placeholder: string, + ) => { + const datalistId = `${inputId}-datalist`; + + return ( +
+ +
+ onChange(e.target.value)} + placeholder={placeholder} + list={branchNames.length > 0 ? datalistId : undefined} + className="h-8 text-xs font-mono flex-1 min-w-0" + /> + {branchNames.length > 0 && ( + <> + + {branchNames.map((name) => ( + + + + )} +
+
+ ); + }; + + const formattedManifest = useMemo(() => { + if (!generated) return ""; + if (generated.manifest) { + return JSON.stringify(generated.manifest, null, 2); + } + return generated.content; + }, [generated]); + + const noChangesCopy = useMemo( + () => (diffResult && !diffResult.hasChanges ? getNoChangesStatusCopy(diffResult) : null), + [diffResult], + ); + + 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( + "schema-diff-source-ref", + "Source Ref", + sourceRef, + setSourceRef, + "e.g. main", + )} + + {mode !== "live-vs-snapshot" && + renderRefSelector( + "schema-diff-target-ref", + 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} + +
+ )} + + {/* Coverage Warnings Banner */} + {diffResult?.coverageWarnings && diffResult.coverageWarnings.length > 0 && ( +
+ + + Coverage Notice + + {diffResult.coverageWarnings.map((warning, idx) => ( +
• {warning}
+ ))} +
+
+
+ )} + + {/* 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. +
+ ) : noChangesCopy ? ( +
+ {noChangesCopy.hasCoverageWarnings ? ( + + ) : ( + + )} +

{noChangesCopy.inspectorTitle}

+

+ {noChangesCopy.inspectorDescription} +

+
+ ) : 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 && + !previewMatchesInputs && + !isGeneratingPreview && + !isScanning && + diffResult?.hasChanges && ( +
+ + + Preview Out of Date + + + Migration inputs changed since the last preview. Regenerate preview before + saving. + + + + +
+ )} + + {generated && generated.warnings.length > 0 && ( +
+ + + Warnings + + {generated.warnings.map((w, idx) => ( +
• {w}
+ ))} +
+
+
+ )} + +
+ {isGeneratingPreview ? ( +
+ + Generating migration preview... +
+ ) : !generated ? ( +
+ {noChangesCopy + ? noChangesCopy.previewMessage + : "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/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..64a0cd72 --- /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 ?? null] 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/database/hooks/useMigrationsPanel.ts b/src/features/database/hooks/useMigrationsPanel.ts index daa2b1aa..eac9c67c 100644 --- a/src/features/database/hooks/useMigrationsPanel.ts +++ b/src/features/database/hooks/useMigrationsPanel.ts @@ -8,9 +8,15 @@ interface MigrationsPanelProps { migrations: MigrationsData; baselined: boolean; dbId: string; + projectId?: string; } -export function useMigrationsPanel({ migrations, baselined, dbId }: MigrationsPanelProps) { +export function useMigrationsPanel({ + migrations, + baselined, + dbId, + projectId, +}: MigrationsPanelProps) { const { local, applied } = migrations; const { invalidateDatabase } = useInvalidateCache(); const [selectedMigration, setSelectedMigration] = useState<{ @@ -53,7 +59,7 @@ export function useMigrationsPanel({ migrations, baselined, dbId }: MigrationsPa const handleApply = async (version: string, name: string) => { try { - await migrationService.applyMigration(dbId, version); + await migrationService.applyMigration(dbId, version, projectId); toast.success("Migration applied successfully", { description: `Applied migration: ${name}`, }); @@ -67,7 +73,7 @@ export function useMigrationsPanel({ migrations, baselined, dbId }: MigrationsPa const handleRollback = async (version: string, name: string) => { try { - await migrationService.rollbackMigration(dbId, version); + await migrationService.rollbackMigration(dbId, version, projectId); toast.success("Migration rolled back successfully", { description: `Rolled back migration: ${name}`, }); @@ -81,7 +87,7 @@ export function useMigrationsPanel({ migrations, baselined, dbId }: MigrationsPa const handleDelete = async (version: string, name: string) => { try { - await migrationService.deleteMigration(dbId, version); + await migrationService.deleteMigration(dbId, version, projectId); toast.success("Migration deleted successfully", { description: `Deleted migration: ${name}`, }); @@ -95,7 +101,7 @@ export function useMigrationsPanel({ migrations, baselined, dbId }: MigrationsPa const handleViewSQL = async (version: string, name: string) => { try { - const sql = await migrationService.getMigrationSQL(dbId, version); + const sql = await migrationService.getMigrationSQL(dbId, version, projectId); setSqlContent(sql); setSelectedMigration({ version, name }); setShowSQLDialog(true); diff --git a/src/features/database/hooks/useSchemaDiffMigration.ts b/src/features/database/hooks/useSchemaDiffMigration.ts new file mode 100644 index 00000000..6b0d537b --- /dev/null +++ b/src/features/database/hooks/useSchemaDiffMigration.ts @@ -0,0 +1,634 @@ +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]; +} + +export interface PreviewInputSnapshot { + projectId: string; + mode: SchemaDiffMode; + sourceRef: string; + targetRef: string; + migrationName: string; + acceptRenameIds: string[]; + concurrentIndexes: boolean; +} + +/** + * Normalizes diff/preview inputs into a canonical snapshot for comparison. + */ +export function normalizePreviewInputs(params: { + projectId: string; + mode: SchemaDiffMode; + sourceRef: string; + targetRef: string; + migrationName?: string; + acceptRenameIds: string[]; + concurrentIndexes: boolean; +}): PreviewInputSnapshot { + return { + projectId: params.projectId, + mode: params.mode, + sourceRef: params.mode === "ref-vs-ref" ? params.sourceRef.trim() : "", + targetRef: params.mode !== "live-vs-snapshot" ? params.targetRef.trim() : "", + migrationName: (params.migrationName ?? "").trim(), + acceptRenameIds: [...params.acceptRenameIds].sort(), + concurrentIndexes: params.concurrentIndexes, + }; +} + +/** + * Returns true when the current inputs match the last successfully previewed inputs. + */ +export function doPreviewInputsMatch( + snapshot: PreviewInputSnapshot | null, + current: PreviewInputSnapshot, +): boolean { + if (!snapshot) return false; + if ( + snapshot.projectId !== current.projectId || + snapshot.mode !== current.mode || + snapshot.sourceRef !== current.sourceRef || + snapshot.targetRef !== current.targetRef || + snapshot.migrationName !== current.migrationName || + snapshot.concurrentIndexes !== current.concurrentIndexes || + snapshot.acceptRenameIds.length !== current.acceptRenameIds.length + ) { + return false; + } + return snapshot.acceptRenameIds.every((id, idx) => id === current.acceptRenameIds[idx]); +} + +/** + * Determine whether saving the generated migration is allowed. + */ +export function canSaveGeneratedMigration(params: { + generated: GeneratedMigrationResult | null; + confirmDestructive: boolean; + isSaving: boolean; + isScanning?: boolean; + isGeneratingPreview?: boolean; + hasRequiredRefs?: boolean; + previewMatchesInputs?: boolean; +}): boolean { + const { + generated, + confirmDestructive, + isSaving, + isScanning = false, + isGeneratingPreview = false, + hasRequiredRefs: refsValid = true, + previewMatchesInputs = true, + } = params; + if (!generated || isSaving || isScanning || isGeneratingPreview) return false; + if (!refsValid || !previewMatchesInputs) 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 PendingStageFile { + filepath: string; + filename: string; +} + +export type StageRecoveryEvent = + | { type: "stage_failed"; file: PendingStageFile } + | { type: "stage_succeeded" } + | { type: "scan_started" } + | { type: "preview_updated" } + | { type: "options_changed" } + | { type: "dismissed" } + | { type: "dialog_closed" }; + +/** + * Reduces Git-staging recovery state independently from schema scans and preview updates. + * Recovery state is only cleared when staging succeeds, is explicitly dismissed, or the dialog closes. + */ +export function reducePendingStageFile( + current: PendingStageFile | null, + event: StageRecoveryEvent, +): PendingStageFile | null { + switch (event.type) { + case "stage_failed": + return event.file; + case "stage_succeeded": + case "dismissed": + case "dialog_closed": + return null; + case "scan_started": + case "preview_updated": + case "options_changed": + return current; + } +} + +/** + * Computes a lowercase SHA-256 hex digest of migration content with CRLF normalized to LF. + */ +export async function computeMigrationContentHash(content: string): Promise { + const normalized = content.replace(/\r\n/g, "\n"); + const encoded = new TextEncoder().encode(normalized); + const subtle = globalThis.crypto?.subtle; + if (!subtle) { + throw new Error("Web Crypto subtle.digest is unavailable for migration content hashing"); + } + const digestBuffer = await subtle.digest("SHA-256", encoded); + return Array.from(new Uint8Array(digestBuffer)) + .map((byte) => byte.toString(16).padStart(2, "0")) + .join(""); +} + +export interface UseSchemaDiffMigrationOptions { + projectId?: string; + dbId?: string; + projectDir?: string | null; + open?: boolean; + onSaved?: (meta?: { stagingFailed?: boolean }) => 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 [previewedInputs, setPreviewedInputs] = useState(null); + const [pendingStageFile, setPendingStageFile] = useState(null); + const [isScanning, setIsScanning] = useState(false); + const [isGeneratingPreview, setIsGeneratingPreview] = useState(false); + const [isSaving, setIsSaving] = useState(false); + const [error, setError] = useState(null); + + const diffRequestIdRef = useRef(0); + const previewRequestIdRef = useRef(0); + + 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; + + const activeRenameIds = opts?.renameIds ?? acceptRenameIdsRef.current; + const activeConcurrent = opts?.concurrent ?? concurrentIndexesRef.current; + const activeMigrationName = opts?.name ?? migrationNameRef.current; + const snapshot = normalizePreviewInputs({ + projectId, + mode: activeMode, + sourceRef: activeSource, + targetRef: activeTarget, + migrationName: activeMigrationName, + acceptRenameIds: activeRenameIds, + concurrentIndexes: activeConcurrent, + }); + + const requestId = ++previewRequestIdRef.current; + setIsGeneratingPreview(true); + setPreviewedInputs(null); + setError(null); + try { + const preview = await migrationService.generateFromDiff({ + projectId, + mode: activeMode, + sourceRef: snapshot.sourceRef || undefined, + targetRef: snapshot.targetRef || undefined, + name: snapshot.migrationName || undefined, + save: false, + acceptRenameIds: activeRenameIds, + confirmDestructive: true, + concurrentIndexes: activeConcurrent, + }); + if (previewRequestIdRef.current !== requestId) return; + setConfirmDestructive(false); + setGenerated(preview); + setPreviewedInputs(snapshot); + } catch (err: any) { + if (previewRequestIdRef.current !== requestId) return; + setConfirmDestructive(false); + setGenerated(null); + setPreviewedInputs(null); + setError(err?.message ?? "Failed to generate migration preview"); + } finally { + if (previewRequestIdRef.current === requestId) { + 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; + + const scanId = ++diffRequestIdRef.current; + previewRequestIdRef.current += 1; + setIsGeneratingPreview(false); + setPreviewedInputs(null); + + if (!hasRequiredRefs(activeMode, activeSource, activeTarget)) { + setIsScanning(false); + setConfirmDestructive(false); + 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, + }); + if (diffRequestIdRef.current !== scanId) return; + setDiffResult(diff); + + if (diff.hasChanges) { + await generatePreview({ + mode: activeMode, + sourceRef: activeSource, + targetRef: activeTarget, + renameIds: [], + }); + } else { + setGenerated(null); + setPreviewedInputs(null); + } + } catch (err: any) { + if (diffRequestIdRef.current !== scanId) return; + setDiffResult(null); + setGenerated(null); + setPreviewedInputs(null); + setError(err?.message ?? "Failed to diff schema"); + } finally { + if (diffRequestIdRef.current === scanId) { + 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) { + setPendingStageFile((prev) => reducePendingStageFile(prev, { type: "dialog_closed" })); + return; + } + if (hasRequiredRefs(mode, sourceRef, targetRef)) { + void runDiff(); + } + return () => { + diffRequestIdRef.current += 1; + previewRequestIdRef.current += 1; + setIsScanning(false); + setIsGeneratingPreview(false); + }; + // 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 currentPreviewInputs = useMemo( + () => + projectId + ? normalizePreviewInputs({ + projectId, + mode, + sourceRef, + targetRef, + migrationName, + acceptRenameIds, + concurrentIndexes, + }) + : null, + [projectId, mode, sourceRef, targetRef, migrationName, acceptRenameIds, concurrentIndexes], + ); + + const previewMatchesInputs = useMemo( + () => + currentPreviewInputs !== null && doPreviewInputsMatch(previewedInputs, currentPreviewInputs), + [previewedInputs, currentPreviewInputs], + ); + + const refsValid = useMemo( + () => hasRequiredRefs(mode, sourceRef, targetRef), + [mode, sourceRef, targetRef], + ); + + const canSave = useMemo( + () => + canSaveGeneratedMigration({ + generated, + confirmDestructive, + isSaving, + isScanning, + isGeneratingPreview, + hasRequiredRefs: refsValid, + previewMatchesInputs, + }), + [ + generated, + confirmDestructive, + isSaving, + isScanning, + isGeneratingPreview, + refsValid, + previewMatchesInputs, + ], + ); + + const dismissPendingStageRetry = useCallback(() => { + setPendingStageFile((prev) => reducePendingStageFile(prev, { type: "dismissed" })); + }, []); + + const saveMigration = useCallback( + async (stageInGit = false) => { + if (stageInGit && pendingStageFile && projectDir) { + setIsSaving(true); + setError(null); + try { + await gitService.gitStage(projectDir, [pendingStageFile.filepath]); + await Promise.all([ + queryClient.invalidateQueries({ queryKey: gitKeys.status(projectDir) }), + queryClient.invalidateQueries({ queryKey: gitKeys.changes(projectDir) }), + ]); + const stagedFilename = pendingStageFile.filename; + setPendingStageFile((prev) => reducePendingStageFile(prev, { type: "stage_succeeded" })); + toast.success("Migration staged in Git", { description: stagedFilename }); + onSaved?.(); + } catch (stageErr: any) { + const stageMsg = stageErr?.message ?? "Failed to stage migration in Git"; + setError( + `Migration saved (${pendingStageFile.filename}), but Git staging failed: ${stageMsg}`, + ); + toast.warning("Migration saved, but Git staging failed", { + description: stageMsg, + }); + } finally { + setIsSaving(false); + } + return; + } + + if (!projectId || !canSave || !previewedInputs || !generated) return; + + setIsSaving(true); + setError(null); + let saved: GeneratedMigrationResult; + try { + const expectedContentHash = await computeMigrationContentHash(generated.content); + saved = await migrationService.generateFromDiff({ + projectId: previewedInputs.projectId, + mode: previewedInputs.mode, + sourceRef: previewedInputs.sourceRef || undefined, + targetRef: previewedInputs.targetRef || undefined, + name: previewedInputs.migrationName || undefined, + version: generated.version, + save: true, + acceptRenameIds: previewedInputs.acceptRenameIds, + confirmDestructive, + concurrentIndexes: previewedInputs.concurrentIndexes, + expectedContentHash, + }); + } catch (err: any) { + const message = err?.message ?? "Failed to save migration"; + setError(message); + toast.error("Failed to save migration", { description: message }); + setIsSaving(false); + return; + } + + if (dbId) { + await invalidateDatabase(dbId); + await queryClient.invalidateQueries({ queryKey: ["mongoMigrations", dbId] }); + } else { + await queryClient.invalidateQueries({ queryKey: ["projects"] }); + } + + if (stageInGit && projectDir && saved.filepath) { + try { + await gitService.gitStage(projectDir, [saved.filepath]); + await Promise.all([ + queryClient.invalidateQueries({ queryKey: gitKeys.status(projectDir) }), + queryClient.invalidateQueries({ queryKey: gitKeys.changes(projectDir) }), + ]); + setPendingStageFile((prev) => reducePendingStageFile(prev, { type: "stage_succeeded" })); + toast.success("Migration saved & staged in Git", { + description: saved.filename, + }); + onSaved?.(); + } catch (stageErr: any) { + const stageMsg = stageErr?.message ?? "Failed to stage migration in Git"; + setPendingStageFile((prev) => + reducePendingStageFile(prev, { + type: "stage_failed", + file: { filepath: saved.filepath!, filename: saved.filename }, + }), + ); + setError(`Migration saved (${saved.filename}), but Git staging failed: ${stageMsg}`); + toast.warning("Migration saved, but Git staging failed", { + description: stageMsg, + }); + onSaved?.({ stagingFailed: true }); + } finally { + setIsSaving(false); + } + return; + } + + toast.success("Migration saved successfully", { + description: saved.filename, + }); + onSaved?.(); + setIsSaving(false); + }, + [ + projectId, + canSave, + previewedInputs, + generated, + pendingStageFile, + confirmDestructive, + 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, + previewMatchesInputs, + stagingFailed: Boolean(pendingStageFile), + hasPendingStageRetry: Boolean(pendingStageFile), + dismissPendingStageRetry, + 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 + + + ) : ( + + )} + + + {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; + projectId?: string; + sql?: string; + collection?: string; + filter?: unknown; + pipeline?: unknown[]; +} + +const IMPACT_BADGE_STYLES: Record<"high" | "medium" | "low", string> = { + high: "bg-destructive/15 text-destructive border-destructive/40", + medium: "bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/40", + low: "bg-emerald-500/15 text-emerald-600 dark:text-emerald-400 border-emerald-500/40", +}; + +/** + * Modal dialog displaying a normalized query execution plan, summary metrics, + * detected bottlenecks, recursive plan tree, raw JSON output, and AI Performance Copilot. + */ +export function ExplainPlanDialog({ + open, + onOpenChange, + dbId, + projectId, + sql, + collection, + filter, + pipeline, +}: ExplainPlanDialogProps) { + const queryClient = useQueryClient(); + const { invalidateDatabase } = useInvalidateCache(); + const { settings } = useAISettings(); + const { data: database } = useDatabase(dbId); + const { data: resolvedProject } = useProjectByDatabaseId(projectId ? undefined : dbId); + const effectiveProjectId = projectId ?? resolvedProject?.id; + + 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" | "copilot">("tree"); + const [copied, setCopied] = useState(false); + const [copiedRewrite, setCopiedRewrite] = useState(false); + + const hasToggledRedactRef = useRef(false); + const [redactLiterals, setRedactLiterals] = useState(() => + shouldDefaultRedactLiterals(settings.defaultProvider), + ); + const [aiLoading, setAiLoading] = useState(false); + const [aiError, setAiError] = useState(null); + const [aiResult, setAiResult] = useState(null); + + const [scaffoldRec, setScaffoldRec] = useState(null); + const [scaffoldPreview, setScaffoldPreview] = useState(null); + const [scaffoldPreviewMeta, setScaffoldPreviewMeta] = useState<{ + projectId: string; + rec: AIRecommendedIndex; + concurrent: boolean; + } | null>(null); + const [concurrentIndexes, setConcurrentIndexes] = useState(false); + const [isScaffolding, setIsScaffolding] = useState(false); + const [isSavingMigration, setIsSavingMigration] = useState(false); + const [scaffoldError, setScaffoldError] = useState(null); + + const explainRequestIdRef = useRef(0); + const planGenerationRef = useRef(0); + const copilotRequestIdRef = useRef(0); + const scaffoldRequestIdRef = useRef(0); + + useEffect(() => { + if (!hasToggledRedactRef.current) { + setRedactLiterals(shouldDefaultRedactLiterals(settings.defaultProvider)); + } + }, [settings.defaultProvider]); + + const runExplain = useCallback( + async (useAnalyze: boolean) => { + if (!dbId || (!sql?.trim() && !collection)) return; + const requestId = ++explainRequestIdRef.current; + planGenerationRef.current += 1; + copilotRequestIdRef.current += 1; + setLoading(true); + setError(null); + setAiResult(null); + setAiError(null); + setAiLoading(false); + try { + const result = await queryService.explainPlan({ + dbId, + sql: sql?.trim(), + collection, + filter, + pipeline, + analyze: useAnalyze, + }); + if (explainRequestIdRef.current !== requestId) return; + setPlan(result); + } catch (err: any) { + if (explainRequestIdRef.current !== requestId) return; + setError(err?.message ?? String(err)); + setPlan(null); + } finally { + if (explainRequestIdRef.current === requestId) { + setLoading(false); + } + } + }, + [dbId, sql, collection, filter, pipeline], + ); + + useEffect(() => { + if (!open) { + explainRequestIdRef.current += 1; + planGenerationRef.current += 1; + copilotRequestIdRef.current += 1; + setLoading(false); + setAiLoading(false); + return; + } + void runExplain(analyze); + return () => { + explainRequestIdRef.current += 1; + planGenerationRef.current += 1; + copilotRequestIdRef.current += 1; + setLoading(false); + setAiLoading(false); + }; + }, [open, analyze, runExplain]); + + const runAICopilot = useCallback( + async (skipCache = false) => { + if (!plan) return; + const requestId = ++copilotRequestIdRef.current; + const expectedPlanGen = planGenerationRef.current; + setAiLoading(true); + setAiError(null); + setActiveTab("copilot"); + try { + const queryText = plan.query || sql?.trim() || collection || ""; + const res = await aiService.analyzePerformance( + settings, + { + dialect: plan.dialect, + query: queryText, + plan, + redactLiterals, + }, + { + skipCache, + datasourceName: database?.name, + }, + ); + if ( + copilotRequestIdRef.current !== requestId || + planGenerationRef.current !== expectedPlanGen + ) { + return; + } + setAiResult(res); + } catch (err: any) { + if ( + copilotRequestIdRef.current !== requestId || + planGenerationRef.current !== expectedPlanGen + ) { + return; + } + setAiError(err?.message ?? String(err)); + } finally { + if ( + copilotRequestIdRef.current === requestId && + planGenerationRef.current === expectedPlanGen + ) { + setAiLoading(false); + } + } + }, + [plan, sql, collection, settings, redactLiterals, database?.name], + ); + + const closeScaffoldDialog = useCallback(() => { + scaffoldRequestIdRef.current += 1; + setIsScaffolding(false); + setScaffoldRec(null); + setScaffoldPreview(null); + setScaffoldPreviewMeta(null); + setScaffoldError(null); + }, []); + + const openScaffoldPreview = useCallback( + async (rec: AIRecommendedIndex, concurrent = concurrentIndexes) => { + if (!effectiveProjectId) { + toast.error("No project linked", { + description: "Link this database to a project to scaffold index migrations.", + }); + return; + } + const requestId = ++scaffoldRequestIdRef.current; + const targetProjectId = effectiveProjectId; + setScaffoldRec(rec); + setScaffoldPreview(null); + setScaffoldPreviewMeta(null); + setScaffoldError(null); + setIsScaffolding(true); + try { + const preview = await migrationService.scaffoldIndexMigration( + buildScaffoldCreatePayload(targetProjectId, rec, concurrent, false), + ); + if (scaffoldRequestIdRef.current !== requestId) return; + setScaffoldPreview(preview); + setScaffoldPreviewMeta({ projectId: targetProjectId, rec, concurrent }); + } catch (err: any) { + if (scaffoldRequestIdRef.current !== requestId) return; + setScaffoldPreview(null); + setScaffoldPreviewMeta(null); + setScaffoldError(err?.message ?? "Failed to preview index migration"); + } finally { + if (scaffoldRequestIdRef.current === requestId) { + setIsScaffolding(false); + } + } + }, + [effectiveProjectId, concurrentIndexes], + ); + + const handleSaveScaffoldedMigration = useCallback(async () => { + if (!scaffoldPreview || !scaffoldPreviewMeta) return; + setIsSavingMigration(true); + setScaffoldError(null); + try { + const saved = await migrationService.scaffoldIndexMigration( + buildScaffoldCreatePayload( + scaffoldPreviewMeta.projectId, + scaffoldPreviewMeta.rec, + scaffoldPreviewMeta.concurrent, + true, + ), + ); + await invalidateDatabase(dbId); + await queryClient.invalidateQueries({ queryKey: ["mongoMigrations", dbId] }); + toast.success("Index migration saved", { description: saved.filename }); + closeScaffoldDialog(); + } catch (err: any) { + const msg = err?.message ?? "Failed to save index migration"; + setScaffoldError(msg); + toast.error("Failed to save migration", { description: msg }); + } finally { + setIsSavingMigration(false); + } + }, [ + scaffoldPreview, + scaffoldPreviewMeta, + invalidateDatabase, + dbId, + queryClient, + closeScaffoldDialog, + ]); + + const handleCopyText = async (text: string, onCopied: (val: boolean) => void) => { + try { + await navigator.clipboard.writeText(text); + onCopied(true); + setTimeout(() => onCopied(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 + + )} +
+ +
+
+ { + hasToggledRedactRef.current = true; + setRedactLiterals(checked); + }} + disabled={aiLoading} + /> + +
+ + + + +
+
+
+ + {/* 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, Raw JSON, & Copilot Insights Tabs */} + setActiveTab(v as "tree" | "raw" | "copilot")} + className="flex-1 min-h-0 flex flex-col" + > +
+ + + + Plan Tree ({nodeCount} {nodeCount === 1 ? "node" : "nodes"}) + + + + Raw JSON + + + + Copilot Insights + {aiResult && aiResult.recommendedIndexes.length > 0 && ( + + {aiResult.recommendedIndexes.length} + + )} + + + + {worstSeverity !== "none" && ( + + {plan.bottlenecks.length}{" "} + {plan.bottlenecks.length === 1 ? "bottleneck" : "bottlenecks"} + + )} +
+ + + + + + + + + + +
+                        {JSON.stringify(plan.rawPlan, null, 2)}
+                      
+
+
+ + + + {aiLoading ? ( +
+ + Analyzing execution plan with AI Copilot… +
+ ) : aiError ? ( +
+
+ +
+

AI Copilot analysis failed

+

{aiError}

+
+
+ +
+ ) : !aiResult ? ( +
+ +

+ Click Analyze with AI Copilot to get query rewrite and + index recommendations. +

+
+ ) : ( +
+ {/* Summary Header */} +
+
+
+ + {aiResult.estimatedImpact} impact + + {aiResult.redacted && ( + + + Redacted + + )} + {aiResult.cached && ( + + Cached + + )} +
+ + +
+ +

+ {aiResult.summary} +

+
+ + {/* Warnings */} + {aiResult.warnings.length > 0 && ( +
+ {aiResult.warnings.map((w, idx) => ( +
+ + {w} +
+ ))} +
+ )} + + {/* Rewritten Query */} + {aiResult.rewrittenQuery && ( +
+
+ + + Suggested Query Rewrite + + +
+
+                                {aiResult.rewrittenQuery}
+                              
+
+ )} + + {/* Recommended Indexes */} + {aiResult.recommendedIndexes.length > 0 && ( +
+

+ Recommended Indexes ({aiResult.recommendedIndexes.length}) +

+ {aiResult.recommendedIndexes.map((rec, idx) => ( +
+
+
+
+ + {rec.indexName} + + + {rec.schema + ? `${rec.schema}.${rec.tableOrCollection}` + : rec.tableOrCollection} + + {rec.unique && ( + + UNIQUE + + )} +
+

+ {rec.reason} +

+
+ + +
+ +
+                                    {rec.ddlPreview}
+                                  
+
+ ))} +
+ )} + + {/* Drop Candidates */} + {aiResult.dropCandidates.length > 0 && ( +
+

+ Drop Candidates ({aiResult.dropCandidates.length}) +

+ {aiResult.dropCandidates.map((cand, idx) => ( +
+
+ + {cand.indexName} + + + on{" "} + {cand.schema + ? `${cand.schema}.${cand.tableOrCollection}` + : cand.tableOrCollection} + +

{cand.reason}

+
+
+ ))} +
+ )} +
+ )} +
+
+
+ + ) : null} +
+
+
+ + {/* Index Migration Scaffold Preview Dialog */} + { + if (!nextOpen && !isSavingMigration) { + closeScaffoldDialog(); + } + }} + > + + + + + Scaffold Index Migration + + + {scaffoldPreview?.filename ?? scaffoldRec?.indexName} + + + +
+ {scaffoldPreview?.format === "sql" && ( +
+ { + const next = Boolean(checked); + setConcurrentIndexes(next); + if (scaffoldRec) { + void openScaffoldPreview(scaffoldRec, next); + } + }} + disabled={isScaffolding || isSavingMigration} + /> + +
+ )} + + {isScaffolding ? ( +
+ + Generating migration preview… +
+ ) : scaffoldError ? ( +
+ {scaffoldError} +
+ ) : scaffoldPreview ? ( + <> + {scaffoldPreview.warnings.length > 0 && ( +
+ {scaffoldPreview.warnings.map((w, idx) => ( +
+ + {w} +
+ ))} +
+ )} + + +
+                    {scaffoldPreview.content}
+                  
+
+ + ) : null} +
+ + + + + +
+
+ + ); +} + +interface ExplainPlanButtonProps { + dbId: string; + projectId?: string; + sql: string; + disabled?: boolean; +} + +/** + * Toolbar button that opens the `ExplainPlanDialog` for the active SQL query. + */ +export function ExplainPlanButton({ dbId, projectId, 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 */}