feat(dolt): add database-aware version control workspace
This commit is contained in:
1 parent
3e6e43c57c
commit
cf1476a6dc
29 files changed
+5411
-6
No files matched your search
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { driverProfileCompletionObjects, driverProfileCompletionTableMetadata, driverProfileCompletionTables, driverProfileExtension, driverProfileObjectTreeProfileForConnection } from "@/lib/database/driverProfileExtensions";
|
||||
import { driverProfileCompletionObjects, driverProfileCompletionTableMetadata, driverProfileCompletionTables, driverProfileDatabaseWorkspace, driverProfileExtension, driverProfileObjectTreeProfileForConnection } from "@/lib/database/driverProfileExtensions";
|
||||
import type { ConnectionConfig } from "@/types/database";
|
||||
|
||||
const completionContext = {
|
||||
@@ -33,6 +33,17 @@ describe("driverProfileExtensions", () => {
|
||||
expect(driverProfileCompletionObjects("dolt", completionContext).map((object) => object.name)).toContain("DOLT_HASHOF");
|
||||
expect(driverProfileCompletionTables("dolt", { ...completionContext, suggestTables: true }).map((table) => table.name)).toContain("DOLT_LOG");
|
||||
expect(driverProfileCompletionTableMetadata("dolt", "dolt_log")).toEqual({ detail: "Dolt system table", boost: -1200 });
|
||||
const workspace = driverProfileDatabaseWorkspace("dolt");
|
||||
expect(workspace).toMatchObject({
|
||||
mode: "dolt-version-control",
|
||||
menuLabelKey: "doltVersionControl.open",
|
||||
tabTitleKey: "doltVersionControl.title",
|
||||
tabScope: "connection",
|
||||
entryScopes: ["connection", "database"],
|
||||
});
|
||||
expect(workspace?.resolveTarget?.("inventory", "connection")).toEqual({ database: "inventory" });
|
||||
expect(workspace?.resolveTarget?.("inventory/feature/orders", "connection")).toEqual({ database: "inventory" });
|
||||
expect(workspace?.resolveTarget?.("inventory/feature/orders", "database")).toEqual({ database: "inventory", branch: "feature/orders" });
|
||||
});
|
||||
|
||||
it("leaves ordinary MySQL without profile capabilities", () => {
|
||||
@@ -41,5 +52,6 @@ describe("driverProfileExtensions", () => {
|
||||
expect(driverProfileCompletionObjects("mysql", completionContext)).toEqual([]);
|
||||
expect(driverProfileCompletionTables("mysql", { ...completionContext, suggestTables: true })).toEqual([]);
|
||||
expect(driverProfileCompletionTableMetadata("mysql", "dolt_log")).toBeUndefined();
|
||||
expect(driverProfileDatabaseWorkspace("mysql")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildDoltTextDiff, detectDoltCellFormat, doltCellCopyText, doltCellDisplayValue, formatDoltCellText, type DoltDiffCellTarget } from "@/lib/dolt/doltCellDiff";
|
||||
|
||||
function target(overrides: Partial<DoltDiffCellTarget> = {}): DoltDiffCellTarget {
|
||||
return {
|
||||
rowIndex: 0,
|
||||
columnIndex: 0,
|
||||
side: "after",
|
||||
columnName: "payload",
|
||||
columnKind: "unchanged",
|
||||
rowKind: "modified",
|
||||
beforeValue: "old",
|
||||
afterValue: "new",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const labels = { nullValue: "NULL", rowMissing: "Row does not exist", columnMissing: "Column does not exist" };
|
||||
|
||||
describe("doltCellDiff", () => {
|
||||
it("distinguishes null values from missing rows and columns", () => {
|
||||
expect(doltCellDisplayValue(target({ beforeValue: null }), "before", labels)).toEqual({ state: "value", text: "NULL", rawText: "", canFormat: false });
|
||||
expect(doltCellDisplayValue(target({ rowKind: "added" }), "before", labels).state).toBe("row-missing");
|
||||
expect(doltCellDisplayValue(target({ columnKind: "added" }), "before", labels).state).toBe("column-missing");
|
||||
expect(doltCellCopyText(target({ beforeValue: null }), "before")).toBe("");
|
||||
expect(doltCellCopyText(target({ rowKind: "added" }), "before")).toBeNull();
|
||||
});
|
||||
|
||||
it("manually formats single-line JSON without changing large number tokens", () => {
|
||||
const display = doltCellDisplayValue(target({ afterValue: '{"id":9007199254740993123,"items":[1,2]}' }), "after", labels);
|
||||
expect(formatDoltCellText(display, "json")).toEqual({
|
||||
text: '{\n "id": 9007199254740993123,\n "items": [\n 1,\n 2\n ]\n}',
|
||||
error: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("manually formats XML and preserves raw text when parsing fails", () => {
|
||||
const valid = doltCellDisplayValue(target({ afterValue: "<root><item>1</item><item>2</item></root>" }), "after", labels);
|
||||
expect(formatDoltCellText(valid, "xml").text).toBe("<root>\n <item>1</item>\n <item>2</item>\n</root>");
|
||||
|
||||
const invalid = doltCellDisplayValue(target({ afterValue: "<root>" }), "after", labels);
|
||||
const result = formatDoltCellText(invalid, "xml");
|
||||
expect(result.text).toBe("<root>");
|
||||
expect(result.error).toMatch(/Unclosed/i);
|
||||
});
|
||||
|
||||
it("automatically detects validated JSON or XML and falls back to raw text", () => {
|
||||
const json = doltCellDisplayValue(target({ beforeValue: '{"value":1}' }), "before", labels);
|
||||
const brokenJson = doltCellDisplayValue(target({ afterValue: '{"value":' }), "after", labels);
|
||||
expect(detectDoltCellFormat([json, brokenJson])).toBe("json");
|
||||
|
||||
const xml = doltCellDisplayValue(target({ beforeValue: "<root><value>1</value></root>" }), "before", labels);
|
||||
expect(detectDoltCellFormat([xml])).toBe("xml");
|
||||
expect(detectDoltCellFormat([json, xml])).toBe("raw");
|
||||
expect(detectDoltCellFormat([doltCellDisplayValue(target({ beforeValue: "plain text" }), "before", labels)])).toBe("raw");
|
||||
});
|
||||
|
||||
it("builds aligned line and character-level modifications", () => {
|
||||
const rows = buildDoltTextDiff("{\n value: 1\n}", "{\n value: 2\n enabled: true\n}");
|
||||
expect(rows.map((row) => row.kind)).toEqual(["equal", "modified", "added", "equal"]);
|
||||
expect(rows[1].beforeSegments.some((segment) => segment.changed && segment.text === "1")).toBe(true);
|
||||
expect(rows[1].afterSegments.some((segment) => segment.changed && segment.text === "2")).toBe(true);
|
||||
expect(rows[2]).toMatchObject({ beforeLineNumber: null, afterLineNumber: 3, afterText: " enabled: true" });
|
||||
});
|
||||
|
||||
it("keeps empty values visible as one aligned row", () => {
|
||||
expect(buildDoltTextDiff("", "")).toEqual([expect.objectContaining({ kind: "equal", beforeLineNumber: 1, afterLineNumber: 1, beforeText: "", afterText: "" })]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,255 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { QueryResult } from "@/types/database";
|
||||
import {
|
||||
doltAddAllSql,
|
||||
doltCheckoutBranchSql,
|
||||
doltCommitSql,
|
||||
doltCreateBranchSql,
|
||||
doltCreateTagSql,
|
||||
doltClientSessionScope,
|
||||
doltDeleteBranchSql,
|
||||
doltDeleteTagSql,
|
||||
doltDiffSummarySql,
|
||||
doltDiscardWorkingTreeSql,
|
||||
doltGraphEdgePath,
|
||||
doltGraphEdgeRoute,
|
||||
doltHardResetSql,
|
||||
doltLogSql,
|
||||
doltMergeBranchSql,
|
||||
doltRevertCommitSql,
|
||||
doltRefColorIndexes,
|
||||
doltRefsByCommit,
|
||||
doltStatusSql,
|
||||
doltTableChangeFlags,
|
||||
doltTableChangeKind,
|
||||
doltTableChangeSymbol,
|
||||
doltTableDiffCountSql,
|
||||
doltTableDiffSql,
|
||||
layoutDoltCommitGraph,
|
||||
parseDoltBranches,
|
||||
parseDoltCommits,
|
||||
parseDoltRowDiff,
|
||||
parseDoltStatus,
|
||||
parseDoltTableChanges,
|
||||
parseDoltTags,
|
||||
} from "@/lib/dolt/doltVersionControl";
|
||||
|
||||
function result(columns: string[], rows: QueryResult["rows"]): QueryResult {
|
||||
return { columns, rows, affected_rows: 0, execution_time_ms: 1 };
|
||||
}
|
||||
|
||||
describe("doltVersionControl", () => {
|
||||
it("quotes revision and table arguments in generated SQL", () => {
|
||||
expect(doltLogSql("feature/o'hare", 10)).toBe("SELECT * FROM DOLT_LOG('feature/o''hare', '--parents', '--decorate', 'short') LIMIT 10");
|
||||
expect(doltLogSql("feature\\o'hare", 10)).toBe("SELECT * FROM DOLT_LOG('feature\\\\o''hare', '--parents', '--decorate', 'short') LIMIT 10");
|
||||
expect(doltStatusSql()).toBe("SELECT table_name, staged, status FROM dolt_status ORDER BY table_name, staged DESC");
|
||||
expect(doltAddAllSql()).toBe("CALL DOLT_ADD('.')");
|
||||
expect(doltCommitSql("fix user's row")).toBe("CALL DOLT_COMMIT('-m', 'fix user''s row')");
|
||||
expect(doltDiffSummarySql("main", "release'1")).toBe("SELECT * FROM DOLT_DIFF_SUMMARY('main', 'release''1')");
|
||||
expect(doltTableDiffSql("HEAD", "WORKING", "order'items", 25)).toBe("SELECT * FROM DOLT_DIFF('HEAD', 'WORKING', 'order''items') LIMIT 25");
|
||||
expect(doltTableDiffSql("HEAD", "WORKING", "order'items", 25, 50)).toBe("SELECT * FROM DOLT_DIFF('HEAD', 'WORKING', 'order''items') LIMIT 25 OFFSET 50");
|
||||
expect(doltTableDiffCountSql("HEAD", "WORKING", "order'items")).toBe("SELECT COUNT(*) AS row_count FROM DOLT_DIFF('HEAD', 'WORKING', 'order''items')");
|
||||
expect(doltCreateBranchSql("feature/o'hare", "HEAD")).toBe("CALL DOLT_BRANCH('feature/o''hare', 'HEAD')");
|
||||
expect(doltMergeBranchSql("release'1")).toBe("CALL DOLT_MERGE('release''1')");
|
||||
expect(doltCheckoutBranchSql("feature/o'hare")).toBe("CALL DOLT_CHECKOUT('feature/o''hare')");
|
||||
expect(doltRevertCommitSql("abc'123")).toBe("CALL DOLT_REVERT('abc''123')");
|
||||
expect(doltHardResetSql("abc'123")).toBe("CALL DOLT_RESET('--hard', 'abc''123')");
|
||||
expect(doltDiscardWorkingTreeSql()).toBe("CALL DOLT_RESET('--hard', 'HEAD')");
|
||||
expect(doltCreateTagSql("v1'o", "HEAD")).toBe("CALL DOLT_TAG('v1''o', 'HEAD')");
|
||||
expect(doltDeleteTagSql("v0'o")).toBe("CALL DOLT_TAG('-d', 'v0''o')");
|
||||
expect(doltDeleteBranchSql("old'branch")).toBe("CALL DOLT_BRANCH('-d', 'old''branch')");
|
||||
});
|
||||
|
||||
it("builds database-scoped client sessions", () => {
|
||||
expect(doltClientSessionScope("connection-1", "database_a")).toEqual({
|
||||
connectionId: "connection-1",
|
||||
database: "database_a",
|
||||
clientSessionId: "dolt-version-control:connection-1:database_a",
|
||||
});
|
||||
expect(doltClientSessionScope("connection-1", "database_b").clientSessionId).not.toBe(doltClientSessionScope("connection-1", "database_a").clientSessionId);
|
||||
});
|
||||
|
||||
it("parses staged and unstaged working tree changes", () => {
|
||||
const changes = parseDoltStatus(
|
||||
result(
|
||||
["status", "table_name", "staged"],
|
||||
[
|
||||
["modified", "orders", true],
|
||||
["new table", "customers", 0],
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
expect(changes).toEqual([
|
||||
{ tableName: "orders", staged: true, status: "modified" },
|
||||
{ tableName: "customers", staged: false, status: "new table" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("parses Dolt refs, commits, decorations, and table changes by column name", () => {
|
||||
const branchRows = result(["hash", "name"], [["abc123", "main"]]);
|
||||
const tagRows = result(["tag_hash", "tag_name"], [["abc123", "v1.0"]]);
|
||||
const commitRows = result(["commit_hash", "parents", "committer", "email", "date", "message", "refs"], [["abc123", "def456, 789abc", "Ada", "ada@example.com", "2026-08-17", "Ship it", "HEAD -> main, tag: v1.0"]]);
|
||||
const changeRows = result(["to_table_name", "from_table_name", "diff_type", "data_change", "schema_change"], [["orders", "orders", "modified", 1, 0]]);
|
||||
|
||||
const branches = parseDoltBranches(branchRows, "main");
|
||||
const tags = parseDoltTags(tagRows);
|
||||
const commits = parseDoltCommits(commitRows);
|
||||
|
||||
expect(branches).toEqual([{ name: "main", hash: "abc123", kind: "branch", active: true }]);
|
||||
expect(tags[0]).toMatchObject({ name: "v1.0", hash: "abc123", kind: "tag" });
|
||||
expect(commits[0]).toMatchObject({ hash: "abc123", parents: ["def456", "789abc"], committer: "Ada", message: "Ship it" });
|
||||
expect(commits[0].refs).toEqual(["main", "tag: v1.0"]);
|
||||
expect(parseDoltTableChanges(changeRows)).toEqual([{ tableName: "orders", fromTableName: "orders", toTableName: "orders", diffType: "modified", dataChange: true, schemaChange: false }]);
|
||||
expect(
|
||||
doltRefsByCommit(commits, [...branches, ...tags])
|
||||
.get("abc123")
|
||||
?.map((item) => item.name),
|
||||
).toEqual(["main", "v1.0"]);
|
||||
});
|
||||
|
||||
it("classifies table changes with reference-style symbols and flags", () => {
|
||||
const added = { diffType: "CREATE", dataChange: false, schemaChange: true } as const;
|
||||
const removed = { diffType: "deleted", dataChange: true, schemaChange: true } as const;
|
||||
const modified = { diffType: "modified", dataChange: true, schemaChange: false } as const;
|
||||
const schemaOnly = { diffType: "modified", dataChange: false, schemaChange: true } as const;
|
||||
const metadataOnly = { diffType: "modified", dataChange: false, schemaChange: false } as const;
|
||||
|
||||
expect(doltTableChangeKind(added)).toBe("added");
|
||||
expect(doltTableChangeSymbol(added)).toBe("+");
|
||||
expect(doltTableChangeFlags(added)).toEqual(["schema"]);
|
||||
|
||||
expect(doltTableChangeKind(removed)).toBe("removed");
|
||||
expect(doltTableChangeSymbol(removed)).toBe("-");
|
||||
expect(doltTableChangeFlags(removed)).toEqual(["data", "schema"]);
|
||||
|
||||
expect(doltTableChangeKind(modified)).toBe("modified");
|
||||
expect(doltTableChangeSymbol(modified)).toBe("*");
|
||||
expect(doltTableChangeFlags(modified)).toEqual(["data"]);
|
||||
|
||||
expect(doltTableChangeKind(schemaOnly)).toBe("schema");
|
||||
expect(doltTableChangeSymbol(schemaOnly)).toBe("*");
|
||||
expect(doltTableChangeFlags(schemaOnly)).toEqual(["schema"]);
|
||||
|
||||
expect(doltTableChangeKind(metadataOnly)).toBe("modified");
|
||||
expect(doltTableChangeFlags(metadataOnly)).toEqual(["metadata"]);
|
||||
});
|
||||
|
||||
it("assigns stable lanes to a merge history", () => {
|
||||
const commits = [
|
||||
{ hash: "merge", parents: ["main-parent", "feature-parent"], committer: "", email: "", date: "", message: "merge", refs: ["HEAD -> main"] },
|
||||
{ hash: "main-parent", parents: ["root"], committer: "", email: "", date: "", message: "main", refs: [] },
|
||||
{ hash: "feature-parent", parents: ["root"], committer: "", email: "", date: "", message: "feature", refs: ["feature"] },
|
||||
{ hash: "root", parents: [], committer: "", email: "", date: "", message: "root", refs: ["tag: v1"] },
|
||||
];
|
||||
const refs = [
|
||||
{ name: "main", hash: "merge", kind: "branch" as const, active: true },
|
||||
{ name: "feature", hash: "feature-parent", kind: "branch" as const, active: false },
|
||||
{ name: "v1", hash: "root", kind: "tag" as const, active: false },
|
||||
];
|
||||
|
||||
const layout = layoutDoltCommitGraph(commits, refs, "main");
|
||||
expect(layout.laneCount).toBeGreaterThanOrEqual(2);
|
||||
expect(layout.rows.map((row) => row.lane)).toEqual([0, 0, 1, 0]);
|
||||
expect(layout.rows.map((row) => row.nodeRef)).toEqual(["main", "main", "feature", "v1"]);
|
||||
expect(layout.rows[0].edges).toEqual([
|
||||
{ fromLane: 0, toLane: 0, colorLane: 0, colorRef: "main" },
|
||||
{ fromLane: 0, toLane: 1, colorLane: 1, colorRef: "feature" },
|
||||
]);
|
||||
expect(layout.rows[1].edges).toContainEqual({ fromLane: 1, toLane: 1, colorLane: 1, colorRef: "feature" });
|
||||
expect(layout.rows[2].edges).toContainEqual({ fromLane: 1, toLane: 0, colorLane: 1, colorRef: "feature" });
|
||||
});
|
||||
|
||||
it("keeps the active branch first-parent chain in lane zero when side commits are interleaved", () => {
|
||||
const commits = [
|
||||
{ hash: "merge", parents: ["main-2", "feature-2"], committer: "", email: "", date: "", message: "merge", refs: ["HEAD -> main"] },
|
||||
{ hash: "feature-2", parents: ["feature-1"], committer: "", email: "", date: "", message: "feature 2", refs: ["feature"] },
|
||||
{ hash: "main-2", parents: ["root"], committer: "", email: "", date: "", message: "main 2", refs: [] },
|
||||
{ hash: "feature-1", parents: ["root"], committer: "", email: "", date: "", message: "feature 1", refs: [] },
|
||||
{ hash: "root", parents: [], committer: "", email: "", date: "", message: "root", refs: [] },
|
||||
];
|
||||
const refs = [
|
||||
{ name: "main", hash: "merge", kind: "branch" as const, active: true },
|
||||
{ name: "feature", hash: "feature-2", kind: "branch" as const, active: false },
|
||||
];
|
||||
|
||||
expect(layoutDoltCommitGraph(commits, refs, "main").rows.map((row) => row.lane)).toEqual([0, 1, 0, 1, 0]);
|
||||
});
|
||||
|
||||
it("starts fork edges at the real parent and ends merge edges at the merge commit", () => {
|
||||
expect(doltGraphEdgeRoute(0, 0, 3, 2)).toBe("direct");
|
||||
expect(doltGraphEdgeRoute(0, 1, 1, 2)).toBe("direct");
|
||||
expect(doltGraphEdgeRoute(0, 1, 3, 1)).toBe("fork");
|
||||
expect(doltGraphEdgeRoute(0, 1, 3, 2)).toBe("merge");
|
||||
expect(doltGraphEdgePath(18, 105, 18, 15)).toBe("M 18 105 L 18 15");
|
||||
expect(doltGraphEdgePath(18, 105, 36, 15, "fork")).toBe("M 18 105 L 36 75 L 36 15");
|
||||
expect(doltGraphEdgePath(18, 105, 54, 15, "fork")).toBe("M 18 105 L 54 75 L 54 15");
|
||||
expect(doltGraphEdgePath(18, 105, 36, 15, "merge")).toBe("M 18 105 L 18 45 L 36 15");
|
||||
expect(doltGraphEdgePath(18, 105, 54, 15, "merge")).toBe("M 18 105 L 18 45 L 54 15");
|
||||
expect(doltGraphEdgePath(18, 45, 36, 15)).toBe("M 18 45 L 36 15");
|
||||
});
|
||||
|
||||
it("deduplicates log decorations against branch and tag records", () => {
|
||||
const commits = [{ hash: "abc123", parents: [], committer: "", email: "", date: "", message: "", refs: ["HEAD -> main", "tag: v1.0", "refs/tags/v2.0"] }];
|
||||
const refs = [
|
||||
{ name: "main", hash: "abc123", kind: "branch" as const, active: true },
|
||||
{ name: "v1.0", hash: "abc123", kind: "tag" as const, active: false },
|
||||
];
|
||||
|
||||
expect(doltRefsByCommit(commits, refs).get("abc123")).toEqual([refs[0], refs[1], { name: "v2.0", hash: "abc123", kind: "tag", active: false }]);
|
||||
});
|
||||
|
||||
it("assigns ref colors independently of query order", () => {
|
||||
const first = doltRefColorIndexes(["main", "feature", "v1.0"], 18);
|
||||
const second = doltRefColorIndexes(["v1.0", "main", "feature"], 18);
|
||||
|
||||
expect([...first]).toEqual([...second]);
|
||||
expect(new Set(first.values()).size).toBe(3);
|
||||
});
|
||||
|
||||
it("pairs from/to diff columns and infers row changes", () => {
|
||||
const parsed = parseDoltRowDiff(
|
||||
result(
|
||||
["from_id", "to_id", "from_name", "to_name", "diff_type", "commit_hash"],
|
||||
[
|
||||
[null, 1, null, "Ada", "added", "abc"],
|
||||
[2, 2, "Old", "New", "modified", "def"],
|
||||
[3, null, "Removed", null, "removed", "ghi"],
|
||||
],
|
||||
),
|
||||
);
|
||||
expect(parsed.columns).toEqual(["id", "name"]);
|
||||
expect(parsed.columnKinds).toEqual(["unchanged", "unchanged"]);
|
||||
expect(parsed.rows).toEqual([
|
||||
{ kind: "added", before: [null, null], after: [1, "Ada"], changedColumns: ["id", "name"] },
|
||||
{ kind: "modified", before: [2, "Old"], after: [2, "New"], changedColumns: ["name"] },
|
||||
{ kind: "removed", before: [3, "Removed"], after: [null, null], changedColumns: ["id", "name"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("accepts qualified, quoted, and suffix-style diff columns", () => {
|
||||
const parsed = parseDoltRowDiff(result(["d.`id_from`", "d.`id_to`", '"from_name"', '"to_name"', "d.diff_type"], [[1, 1, "Old", "New", "modified"]]));
|
||||
|
||||
expect(parsed).toEqual({
|
||||
columns: ["id", "name"],
|
||||
columnKinds: ["unchanged", "unchanged"],
|
||||
rows: [{ kind: "modified", before: [1, "Old"], after: [1, "New"], changedColumns: ["name"] }],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps schema-only columns aligned and identifies additions and removals", () => {
|
||||
const parsed = parseDoltRowDiff(result(["from_id", "to_id", "from_legacy", "to_created_at", "diff_type"], [[1, 1, "old", "new", "modified"]]));
|
||||
|
||||
expect(parsed).toEqual({
|
||||
columns: ["id", "legacy", "created_at"],
|
||||
columnKinds: ["unchanged", "removed", "added"],
|
||||
rows: [{ kind: "modified", before: [1, "old", null], after: [1, null, "new"], changedColumns: ["legacy", "created_at"] }],
|
||||
});
|
||||
});
|
||||
|
||||
it("infers schema columns when Dolt returns both sides with one side empty", () => {
|
||||
const parsed = parseDoltRowDiff(result(["from_id", "to_id", "from_legacy", "to_legacy", "from_created_at", "to_created_at", "diff_type"], [[1, 1, "old", null, null, "new", "modified"]]), true);
|
||||
|
||||
expect(parsed.columnKinds).toEqual(["unchanged", "removed", "added"]);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { useConnectionStore } from "@/stores/connectionStore";
|
||||
import { connectionGroupDisplayName, executionSummaryItems, middleEllipsis, queryResultBaseSql, queryResultExecutionSql, resultGridCacheKey, resultGridInstanceKey, resultSourceRange, statementExecutionMarkers, tabTooltipLines, tabularResultItems } from "@/lib/tabs/tabPresentation";
|
||||
import { connectionGroupDisplayName, executionSummaryItems, middleEllipsis, queryResultBaseSql, queryResultExecutionSql, resultGridCacheKey, resultGridInstanceKey, resultSourceRange, statementExecutionMarkers, tabDisplayTitle, tabTooltipLines, tabularResultItems } from "@/lib/tabs/tabPresentation";
|
||||
import { sqlTextFingerprint } from "@/lib/sql/sqlTextFingerprint";
|
||||
import type { ConnectionConfig, QueryTab } from "@/types/database";
|
||||
|
||||
@@ -146,6 +146,14 @@ describe("query result grid identity", () => {
|
||||
});
|
||||
|
||||
describe("tab group presentation", () => {
|
||||
it("uses the live database and branch context for Dolt version control tabs", () => {
|
||||
const store = useConnectionStore();
|
||||
store.connections = [{ id: "conn-1", name: "Production Dolt", db_type: "mysql", driver_profile: "dolt", database: "app" } as ConnectionConfig];
|
||||
|
||||
expect(tabDisplayTitle(queryTab({ mode: "dolt-version-control", title: "Dolt Version Control", workspaceBranch: "feature/orders" }), translate)).toBe("Production Dolt VCS@db.feature/orders");
|
||||
expect(tabDisplayTitle(queryTab({ mode: "dolt-version-control", title: "Dolt Version Control" }), translate)).toBe("Production Dolt VCS@db");
|
||||
});
|
||||
|
||||
it("adds the full, live group path to tab tooltips", () => {
|
||||
const store = useConnectionStore();
|
||||
store.connections = [{ id: "conn-1", name: "PostgreSQL", db_type: "postgres", database: "app" } as ConnectionConfig];
|
||||
|
||||
@@ -122,6 +122,16 @@ export function isDoltDriverProfile(driverProfile?: string): boolean {
|
||||
return driverProfile?.toLowerCase() === DOLT_DRIVER_PROFILE;
|
||||
}
|
||||
|
||||
export function doltWorkspaceTarget(database: string, source: "connection" | "database") {
|
||||
const separator = database.indexOf("/");
|
||||
if (separator <= 0) return { database };
|
||||
const baseDatabase = database.slice(0, separator);
|
||||
const branch = database.slice(separator + 1);
|
||||
// Connection-level navigation uses the database's default branch. A tree
|
||||
// database entry may explicitly address a Dolt db/branch revision database.
|
||||
return source === "database" && branch ? { database: baseDatabase, branch } : { database: baseDatabase };
|
||||
}
|
||||
|
||||
type DoltConnectionConfig = Pick<ConnectionConfig, "driver_profile"> & Partial<Pick<ConnectionConfig, "external_config">>;
|
||||
|
||||
function externalConfigRecord(value: unknown): Record<string, unknown> {
|
||||
@@ -174,6 +184,14 @@ export function doltSqlRoutineSignatures(driverProfile?: string): Map<string, st
|
||||
|
||||
export const DOLT_DRIVER_PROFILE_EXTENSION: DriverProfileExtensionDefinition = {
|
||||
id: DOLT_DRIVER_PROFILE,
|
||||
databaseWorkspace: {
|
||||
mode: "dolt-version-control",
|
||||
menuLabelKey: "doltVersionControl.open",
|
||||
tabTitleKey: "doltVersionControl.title",
|
||||
tabScope: "connection",
|
||||
entryScopes: ["connection", "database"],
|
||||
resolveTarget: doltWorkspaceTarget,
|
||||
},
|
||||
objectTreeProfile: doltObjectTreeProfileForConnection,
|
||||
completionTableMetadata: (tableName) =>
|
||||
tableName.toLowerCase().startsWith("dolt")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { DOLT_DRIVER_PROFILE_EXTENSION } from "@/lib/database/doltProfile";
|
||||
import type { SqlCompletionObject, SqlCompletionTable, SqlStatementKind } from "@/lib/sql/sqlCompletion";
|
||||
import type { ConnectionConfig, TableNameFilter, TreeNodeType } from "@/types/database";
|
||||
import type { ConnectionConfig, QueryTab, TableNameFilter, TreeNodeType } from "@/types/database";
|
||||
|
||||
export type DriverProfileObjectTreeProfile = {
|
||||
cacheKey: string;
|
||||
@@ -22,6 +22,25 @@ export type DriverProfileSqlCompletionContext = {
|
||||
|
||||
export type DriverProfileCompletionTableMetadata = Pick<SqlCompletionTable, "detail" | "boost">;
|
||||
|
||||
export type DriverProfileWorkspaceTarget = {
|
||||
database: string;
|
||||
branch?: string;
|
||||
};
|
||||
|
||||
export type DriverProfileWorkspaceScope = "database" | "connection";
|
||||
|
||||
export type DriverProfileDatabaseWorkspace = {
|
||||
mode: QueryTab["mode"];
|
||||
menuLabelKey: string;
|
||||
tabTitleKey: string;
|
||||
/** Determines whether tabs are reused per connection or per database. */
|
||||
tabScope: DriverProfileWorkspaceScope;
|
||||
/** Tree levels whose context menu exposes the workspace entry. */
|
||||
entryScopes: readonly DriverProfileWorkspaceScope[];
|
||||
/** Maps a tree database name to the context opened by the workspace. */
|
||||
resolveTarget?: (database: string, source: DriverProfileWorkspaceScope) => DriverProfileWorkspaceTarget;
|
||||
};
|
||||
|
||||
export type DriverProfileExtensionDefinition = {
|
||||
id: string;
|
||||
objectTreeProfile?: (config: ConnectionConfig) => DriverProfileObjectTreeProfile | undefined;
|
||||
@@ -30,6 +49,7 @@ export type DriverProfileExtensionDefinition = {
|
||||
completionTables?: (context: DriverProfileSqlCompletionContext) => SqlCompletionTable[];
|
||||
sqlBuiltinTerms?: () => string;
|
||||
routineSignatures?: () => Map<string, string[]>;
|
||||
databaseWorkspace?: DriverProfileDatabaseWorkspace;
|
||||
};
|
||||
|
||||
export const DRIVER_PROFILE_EXTENSIONS = [DOLT_DRIVER_PROFILE_EXTENSION] as const satisfies readonly DriverProfileExtensionDefinition[];
|
||||
@@ -69,3 +89,7 @@ export function driverProfileSqlBuiltinTerms(driverProfile?: string): string {
|
||||
export function driverProfileRoutineSignatures(driverProfile?: string): Map<string, string[]> {
|
||||
return driverProfileExtension(driverProfile)?.routineSignatures?.() ?? new Map();
|
||||
}
|
||||
|
||||
export function driverProfileDatabaseWorkspace(driverProfile?: string): DriverProfileDatabaseWorkspace | undefined {
|
||||
return driverProfileExtension(driverProfile)?.databaseWorkspace;
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
import { diffChars, diffLines, type Change } from "diff";
|
||||
import { formatJsonSource } from "@/lib/common/safeJsonFormat";
|
||||
import { formatXmlSource } from "@/lib/common/xmlFormat";
|
||||
import type { QueryResult } from "@/types/database";
|
||||
import type { DoltDiffColumnKind, DoltRowChangeKind } from "@/lib/dolt/doltVersionControl";
|
||||
|
||||
export type DoltCellValue = QueryResult["rows"][number][number];
|
||||
export type DoltCellSide = "before" | "after";
|
||||
export type DoltCellFormat = "raw" | "json" | "xml";
|
||||
export type DoltCellFormatMode = "auto" | DoltCellFormat;
|
||||
export type DoltCellValueState = "value" | "row-missing" | "column-missing";
|
||||
export type DoltTextDiffKind = "equal" | "added" | "removed" | "modified";
|
||||
|
||||
export interface DoltDiffCellTarget {
|
||||
rowIndex: number;
|
||||
columnIndex: number;
|
||||
side: DoltCellSide;
|
||||
columnName: string;
|
||||
columnKind: DoltDiffColumnKind;
|
||||
rowKind: DoltRowChangeKind;
|
||||
beforeValue: DoltCellValue;
|
||||
afterValue: DoltCellValue;
|
||||
}
|
||||
|
||||
export interface DoltCellDisplayValue {
|
||||
state: DoltCellValueState;
|
||||
text: string;
|
||||
rawText: string;
|
||||
canFormat: boolean;
|
||||
}
|
||||
|
||||
export interface DoltCellFormatResult {
|
||||
text: string;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface DoltTextDiffSegment {
|
||||
text: string;
|
||||
changed: boolean;
|
||||
}
|
||||
|
||||
export interface DoltTextDiffRow {
|
||||
kind: DoltTextDiffKind;
|
||||
beforeLineNumber: number | null;
|
||||
afterLineNumber: number | null;
|
||||
beforeText: string;
|
||||
afterText: string;
|
||||
beforeSegments: DoltTextDiffSegment[];
|
||||
afterSegments: DoltTextDiffSegment[];
|
||||
}
|
||||
|
||||
const MAX_DETAILED_LINE_DIFF_CHARACTERS = 500_000;
|
||||
const MAX_CHARACTER_DIFF_CHARACTERS = 20_000;
|
||||
|
||||
export function doltCellValueState(target: DoltDiffCellTarget, side: DoltCellSide): DoltCellValueState {
|
||||
if (side === "before") {
|
||||
if (target.columnKind === "added") return "column-missing";
|
||||
if (target.rowKind === "added") return "row-missing";
|
||||
} else {
|
||||
if (target.columnKind === "removed") return "column-missing";
|
||||
if (target.rowKind === "removed") return "row-missing";
|
||||
}
|
||||
return "value";
|
||||
}
|
||||
|
||||
export function doltCellDisplayValue(target: DoltDiffCellTarget, side: DoltCellSide, labels: { nullValue: string; rowMissing: string; columnMissing: string }): DoltCellDisplayValue {
|
||||
const state = doltCellValueState(target, side);
|
||||
if (state === "row-missing") return { state, text: labels.rowMissing, rawText: "", canFormat: false };
|
||||
if (state === "column-missing") return { state, text: labels.columnMissing, rawText: "", canFormat: false };
|
||||
const value = side === "before" ? target.beforeValue : target.afterValue;
|
||||
if (value === null) return { state, text: labels.nullValue, rawText: "", canFormat: false };
|
||||
const text = String(value);
|
||||
return { state, text, rawText: text, canFormat: typeof value === "string" };
|
||||
}
|
||||
|
||||
export function formatDoltCellText(value: DoltCellDisplayValue, format: DoltCellFormat): DoltCellFormatResult {
|
||||
if (format === "raw" || !value.canFormat) return { text: value.text, error: null };
|
||||
try {
|
||||
return {
|
||||
text: format === "json" ? formatJsonSource(value.rawText, 2) : formatXmlSource(value.rawText, " "),
|
||||
error: null,
|
||||
};
|
||||
} catch (error) {
|
||||
return { text: value.text, error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
}
|
||||
|
||||
export function detectDoltCellFormat(values: readonly DoltCellDisplayValue[]): DoltCellFormat {
|
||||
const candidates = values.filter((value) => value.canFormat && value.rawText.trim()).map((value) => value.rawText.trim());
|
||||
const jsonCandidates = candidates.filter((value) => value.startsWith("{") || value.startsWith("["));
|
||||
const xmlCandidates = candidates.filter((value) => value.startsWith("<"));
|
||||
const hasValidJson = jsonCandidates.some((value) => !formatDoltCellText({ state: "value", text: value, rawText: value, canFormat: true }, "json").error);
|
||||
const hasValidXml = xmlCandidates.some((value) => !formatDoltCellText({ state: "value", text: value, rawText: value, canFormat: true }, "xml").error);
|
||||
if (hasValidJson !== hasValidXml) return hasValidJson ? "json" : "xml";
|
||||
return "raw";
|
||||
}
|
||||
|
||||
function normalizeLineEndings(value: string): string {
|
||||
return value.replace(/\r\n?/g, "\n");
|
||||
}
|
||||
|
||||
function linesFromChange(change: Change): string[] {
|
||||
if (!change.value) return [];
|
||||
const lines = change.value.split("\n");
|
||||
if (change.value.endsWith("\n")) lines.pop();
|
||||
return lines;
|
||||
}
|
||||
|
||||
function unchangedSegments(text: string): DoltTextDiffSegment[] {
|
||||
return text ? [{ text, changed: false }] : [];
|
||||
}
|
||||
|
||||
function changedSegments(beforeText: string, afterText: string): { before: DoltTextDiffSegment[]; after: DoltTextDiffSegment[] } {
|
||||
if (beforeText.length + afterText.length > MAX_CHARACTER_DIFF_CHARACTERS) {
|
||||
return {
|
||||
before: beforeText ? [{ text: beforeText, changed: true }] : [],
|
||||
after: afterText ? [{ text: afterText, changed: true }] : [],
|
||||
};
|
||||
}
|
||||
const changes = diffChars(beforeText, afterText);
|
||||
return {
|
||||
before: changes.filter((change) => !change.added).map((change) => ({ text: change.value, changed: !!change.removed })),
|
||||
after: changes.filter((change) => !change.removed).map((change) => ({ text: change.value, changed: !!change.added })),
|
||||
};
|
||||
}
|
||||
|
||||
function appendEqualRows(rows: DoltTextDiffRow[], lines: string[], beforeLine: { value: number }, afterLine: { value: number }) {
|
||||
for (const line of lines) {
|
||||
rows.push({
|
||||
kind: "equal",
|
||||
beforeLineNumber: beforeLine.value++,
|
||||
afterLineNumber: afterLine.value++,
|
||||
beforeText: line,
|
||||
afterText: line,
|
||||
beforeSegments: unchangedSegments(line),
|
||||
afterSegments: unchangedSegments(line),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function appendChangedRows(rows: DoltTextDiffRow[], removed: string[], added: string[], beforeLine: { value: number }, afterLine: { value: number }) {
|
||||
const count = Math.max(removed.length, added.length);
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const beforeText = removed[index];
|
||||
const afterText = added[index];
|
||||
if (beforeText !== undefined && afterText !== undefined) {
|
||||
const segments = changedSegments(beforeText, afterText);
|
||||
rows.push({
|
||||
kind: beforeText === afterText ? "equal" : "modified",
|
||||
beforeLineNumber: beforeLine.value++,
|
||||
afterLineNumber: afterLine.value++,
|
||||
beforeText,
|
||||
afterText,
|
||||
beforeSegments: beforeText === afterText ? unchangedSegments(beforeText) : segments.before,
|
||||
afterSegments: beforeText === afterText ? unchangedSegments(afterText) : segments.after,
|
||||
});
|
||||
} else if (beforeText !== undefined) {
|
||||
rows.push({
|
||||
kind: "removed",
|
||||
beforeLineNumber: beforeLine.value++,
|
||||
afterLineNumber: null,
|
||||
beforeText,
|
||||
afterText: "",
|
||||
beforeSegments: unchangedSegments(beforeText),
|
||||
afterSegments: [],
|
||||
});
|
||||
} else if (afterText !== undefined) {
|
||||
rows.push({
|
||||
kind: "added",
|
||||
beforeLineNumber: null,
|
||||
afterLineNumber: afterLine.value++,
|
||||
beforeText: "",
|
||||
afterText,
|
||||
beforeSegments: [],
|
||||
afterSegments: unchangedSegments(afterText),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function buildFallbackRows(before: string, after: string): DoltTextDiffRow[] {
|
||||
const beforeLines = before.split("\n");
|
||||
const afterLines = after.split("\n");
|
||||
const rows: DoltTextDiffRow[] = [];
|
||||
appendChangedRows(rows, beforeLines, afterLines, { value: 1 }, { value: 1 });
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function buildDoltTextDiff(beforeValue: string, afterValue: string): DoltTextDiffRow[] {
|
||||
const before = normalizeLineEndings(beforeValue);
|
||||
const after = normalizeLineEndings(afterValue);
|
||||
if (before.length + after.length > MAX_DETAILED_LINE_DIFF_CHARACTERS) return buildFallbackRows(before, after);
|
||||
|
||||
const changes = diffLines(before, after, { newlineIsToken: false });
|
||||
const rows: DoltTextDiffRow[] = [];
|
||||
const beforeLine = { value: 1 };
|
||||
const afterLine = { value: 1 };
|
||||
let index = 0;
|
||||
while (index < changes.length) {
|
||||
const change = changes[index];
|
||||
if (!change.added && !change.removed) {
|
||||
appendEqualRows(rows, linesFromChange(change), beforeLine, afterLine);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const removed: string[] = [];
|
||||
const added: string[] = [];
|
||||
while (index < changes.length && (changes[index].added || changes[index].removed)) {
|
||||
const changedLines = linesFromChange(changes[index]);
|
||||
if (changes[index].removed) removed.push(...changedLines);
|
||||
else added.push(...changedLines);
|
||||
index += 1;
|
||||
}
|
||||
appendChangedRows(rows, removed, added, beforeLine, afterLine);
|
||||
}
|
||||
|
||||
if (rows.length === 0) appendEqualRows(rows, [""], beforeLine, afterLine);
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function doltCellCopyText(target: DoltDiffCellTarget, side: DoltCellSide): string | null {
|
||||
if (doltCellValueState(target, side) !== "value") return null;
|
||||
const value = side === "before" ? target.beforeValue : target.afterValue;
|
||||
return value === null ? "" : String(value);
|
||||
}
|
||||
@@ -0,0 +1,631 @@
|
||||
import type { QueryResult } from "@/types/database";
|
||||
|
||||
export interface DoltRef {
|
||||
name: string;
|
||||
hash: string;
|
||||
kind: "branch" | "tag";
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export interface DoltCommit {
|
||||
hash: string;
|
||||
parents: string[];
|
||||
committer: string;
|
||||
email: string;
|
||||
date: string;
|
||||
message: string;
|
||||
refs: string[];
|
||||
}
|
||||
|
||||
export interface DoltTableChange {
|
||||
tableName: string;
|
||||
fromTableName: string;
|
||||
toTableName: string;
|
||||
diffType: string;
|
||||
dataChange: boolean;
|
||||
schemaChange: boolean;
|
||||
}
|
||||
|
||||
export type DoltTableChangeKind = "added" | "removed" | "modified" | "schema" | "mixed";
|
||||
export type DoltTableChangeFlag = "data" | "schema" | "metadata";
|
||||
|
||||
/** Matches Dolt's table-level change classification used by the reference UI. */
|
||||
export function doltTableChangeKind(change: Pick<DoltTableChange, "diffType" | "dataChange" | "schemaChange">): DoltTableChangeKind {
|
||||
const normalized = change.diffType.trim().toLowerCase();
|
||||
if (normalized.includes("add") || normalized.includes("create")) return "added";
|
||||
if (normalized.includes("drop") || normalized.includes("remove") || normalized.includes("delete")) return "removed";
|
||||
if (change.schemaChange && change.dataChange) return "mixed";
|
||||
if (change.schemaChange) return "schema";
|
||||
return "modified";
|
||||
}
|
||||
|
||||
export function doltTableChangeSymbol(change: Pick<DoltTableChange, "diffType" | "dataChange" | "schemaChange">): "+" | "-" | "*" {
|
||||
const kind = doltTableChangeKind(change);
|
||||
return kind === "added" ? "+" : kind === "removed" ? "-" : "*";
|
||||
}
|
||||
|
||||
export function doltTableChangeFlags(change: Pick<DoltTableChange, "diffType" | "dataChange" | "schemaChange">): DoltTableChangeFlag[] {
|
||||
const flags: DoltTableChangeFlag[] = [];
|
||||
if (change.dataChange) flags.push("data");
|
||||
if (change.schemaChange) flags.push("schema");
|
||||
if (flags.length === 0 && change.diffType.trim()) flags.push("metadata");
|
||||
return flags;
|
||||
}
|
||||
|
||||
export interface DoltWorkingChange {
|
||||
tableName: string;
|
||||
staged: boolean;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export type DoltRowChangeKind = "added" | "removed" | "modified";
|
||||
export type DoltDiffColumnKind = "unchanged" | "added" | "removed";
|
||||
|
||||
export interface DoltDiffRow {
|
||||
kind: DoltRowChangeKind;
|
||||
before: QueryResult["rows"][number];
|
||||
after: QueryResult["rows"][number];
|
||||
changedColumns: string[];
|
||||
}
|
||||
|
||||
export interface DoltParsedRowDiff {
|
||||
columns: string[];
|
||||
columnKinds: DoltDiffColumnKind[];
|
||||
rows: DoltDiffRow[];
|
||||
}
|
||||
|
||||
export interface DoltGraphLayout {
|
||||
lane: number;
|
||||
nodeRef: string | null;
|
||||
edges: DoltGraphEdge[];
|
||||
maxLane: number;
|
||||
}
|
||||
|
||||
export interface DoltGraphEdge {
|
||||
fromLane: number;
|
||||
toLane: number;
|
||||
colorLane: number;
|
||||
colorRef: string | null;
|
||||
}
|
||||
|
||||
export interface DoltClientSessionScope {
|
||||
connectionId: string;
|
||||
database: string;
|
||||
clientSessionId: string;
|
||||
}
|
||||
|
||||
export type DoltGraphEdgeRoute = "direct" | "fork" | "merge";
|
||||
const DOLT_GRAPH_DIAGONAL_HEIGHT = 30;
|
||||
|
||||
export function doltGraphEdgeRoute(parentLane: number, childLane: number, rowDistance: number, childParentCount: number): DoltGraphEdgeRoute {
|
||||
if (parentLane === childLane || rowDistance <= 1) return "direct";
|
||||
if (childParentCount > 1) return "merge";
|
||||
return "fork";
|
||||
}
|
||||
|
||||
export function doltGraphEdgePath(startX: number, startY: number, targetX: number, targetY: number, route: DoltGraphEdgeRoute = "direct"): string {
|
||||
if (startX === targetX || route === "direct") return `M ${startX} ${startY} L ${targetX} ${targetY}`;
|
||||
const availableHeight = Math.abs(targetY - startY);
|
||||
const diagonalHeight = DOLT_GRAPH_DIAGONAL_HEIGHT;
|
||||
if (diagonalHeight >= availableHeight) return `M ${startX} ${startY} L ${targetX} ${targetY}`;
|
||||
const direction = Math.sign(targetY - startY) || 1;
|
||||
if (route === "fork") return `M ${startX} ${startY} L ${targetX} ${startY + direction * diagonalHeight} L ${targetX} ${targetY}`;
|
||||
return `M ${startX} ${startY} L ${startX} ${targetY - direction * diagonalHeight} L ${targetX} ${targetY}`;
|
||||
}
|
||||
|
||||
export function doltClientSessionScope(connectionId: string, database: string): DoltClientSessionScope {
|
||||
return {
|
||||
connectionId,
|
||||
database,
|
||||
clientSessionId: `dolt-version-control:${connectionId}:${database}`,
|
||||
};
|
||||
}
|
||||
|
||||
export function doltSqlLiteral(value: string): string {
|
||||
return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "''")}'`;
|
||||
}
|
||||
|
||||
export function doltLogSql(revision: string, limit = 500): string {
|
||||
return `SELECT * FROM DOLT_LOG(${doltSqlLiteral(revision)}, '--parents', '--decorate', 'short') LIMIT ${Math.max(1, Math.floor(limit))}`;
|
||||
}
|
||||
|
||||
export function doltStatusSql(): string {
|
||||
return "SELECT table_name, staged, status FROM dolt_status ORDER BY table_name, staged DESC";
|
||||
}
|
||||
|
||||
export function doltAddAllSql(): string {
|
||||
return "CALL DOLT_ADD('.')";
|
||||
}
|
||||
|
||||
export function doltCommitSql(message: string): string {
|
||||
return `CALL DOLT_COMMIT('-m', ${doltSqlLiteral(message)})`;
|
||||
}
|
||||
|
||||
export function doltDiffSummarySql(fromRevision: string, toRevision: string): string {
|
||||
return `SELECT * FROM DOLT_DIFF_SUMMARY(${doltSqlLiteral(fromRevision)}, ${doltSqlLiteral(toRevision)})`;
|
||||
}
|
||||
|
||||
export function doltTableDiffSql(fromRevision: string, toRevision: string, tableName: string, limit = 200, offset = 0): string {
|
||||
const normalizedOffset = Math.max(0, Math.floor(offset));
|
||||
return `SELECT * FROM DOLT_DIFF(${doltSqlLiteral(fromRevision)}, ${doltSqlLiteral(toRevision)}, ${doltSqlLiteral(tableName)}) LIMIT ${Math.max(1, Math.floor(limit))}${normalizedOffset > 0 ? ` OFFSET ${normalizedOffset}` : ""}`;
|
||||
}
|
||||
|
||||
export function doltTableDiffCountSql(fromRevision: string, toRevision: string, tableName: string): string {
|
||||
return `SELECT COUNT(*) AS row_count FROM DOLT_DIFF(${doltSqlLiteral(fromRevision)}, ${doltSqlLiteral(toRevision)}, ${doltSqlLiteral(tableName)})`;
|
||||
}
|
||||
|
||||
export function doltCreateBranchSql(branchName: string, sourceRevision?: string): string {
|
||||
const source = sourceRevision?.trim();
|
||||
return source ? `CALL DOLT_BRANCH(${doltSqlLiteral(branchName)}, ${doltSqlLiteral(source)})` : `CALL DOLT_BRANCH(${doltSqlLiteral(branchName)})`;
|
||||
}
|
||||
|
||||
export function doltMergeBranchSql(branchName: string): string {
|
||||
return `CALL DOLT_MERGE(${doltSqlLiteral(branchName)})`;
|
||||
}
|
||||
|
||||
export function doltCheckoutBranchSql(branchName: string): string {
|
||||
return `CALL DOLT_CHECKOUT(${doltSqlLiteral(branchName)})`;
|
||||
}
|
||||
|
||||
export function doltRevertCommitSql(revision: string): string {
|
||||
return `CALL DOLT_REVERT(${doltSqlLiteral(revision)})`;
|
||||
}
|
||||
|
||||
export function doltHardResetSql(revision: string): string {
|
||||
return `CALL DOLT_RESET('--hard', ${doltSqlLiteral(revision)})`;
|
||||
}
|
||||
|
||||
export function doltDiscardWorkingTreeSql(): string {
|
||||
return doltHardResetSql("HEAD");
|
||||
}
|
||||
|
||||
export function doltCreateTagSql(tagName: string, sourceRevision?: string): string {
|
||||
const source = sourceRevision?.trim();
|
||||
return source ? `CALL DOLT_TAG(${doltSqlLiteral(tagName)}, ${doltSqlLiteral(source)})` : `CALL DOLT_TAG(${doltSqlLiteral(tagName)})`;
|
||||
}
|
||||
|
||||
export function doltDeleteTagSql(tagName: string): string {
|
||||
return `CALL DOLT_TAG('-d', ${doltSqlLiteral(tagName)})`;
|
||||
}
|
||||
|
||||
export function doltDeleteBranchSql(branchName: string): string {
|
||||
return `CALL DOLT_BRANCH('-d', ${doltSqlLiteral(branchName)})`;
|
||||
}
|
||||
|
||||
function normalizedColumnIndex(result: QueryResult): Map<string, number> {
|
||||
return new Map(result.columns.map((column, index) => [column.trim().toLowerCase(), index]));
|
||||
}
|
||||
|
||||
function valueFromRow(row: QueryResult["rows"][number], columns: Map<string, number>, names: string[]): string {
|
||||
for (const name of names) {
|
||||
const index = columns.get(name.toLowerCase());
|
||||
if (index !== undefined && row[index] !== null && row[index] !== undefined) return String(row[index]);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function booleanFromRow(row: QueryResult["rows"][number], columns: Map<string, number>, names: string[]): boolean {
|
||||
const value = valueFromRow(row, columns, names).trim().toLowerCase();
|
||||
return value === "1" || value === "true" || value === "yes";
|
||||
}
|
||||
|
||||
function parseParents(value: string): string[] {
|
||||
return value
|
||||
.replace(/[;,]/g, " ")
|
||||
.split(/\s+/)
|
||||
.map((parent) => parent.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function parseRefs(value: string): string[] {
|
||||
return value
|
||||
.split(/[,;]/)
|
||||
.map((ref) =>
|
||||
ref
|
||||
.trim()
|
||||
.replace(/^HEAD\s*->\s*/i, "")
|
||||
.replace(/^refs\/tags\//i, "tag: ")
|
||||
.replace(/^refs\/(?:heads|remotes)\//i, ""),
|
||||
)
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function decorationRef(decoration: string, hash: string): DoltRef | null {
|
||||
let name = decoration.trim();
|
||||
if (!name) return null;
|
||||
|
||||
name = name.replace(/^HEAD\s*->\s*/i, "").trim();
|
||||
if (!name || name.toUpperCase() === "HEAD") return null;
|
||||
|
||||
let kind: DoltRef["kind"] = "branch";
|
||||
if (/^(?:tag:\s*|refs\/tags\/)/i.test(name)) {
|
||||
kind = "tag";
|
||||
name = name.replace(/^(?:tag:\s*|refs\/tags\/)/i, "").trim();
|
||||
} else {
|
||||
name = name.replace(/^refs\/(?:heads|remotes)\//i, "").trim();
|
||||
}
|
||||
return name ? { name, hash, kind, active: false } : null;
|
||||
}
|
||||
|
||||
export function parseDoltCommits(result: QueryResult): DoltCommit[] {
|
||||
const columns = normalizedColumnIndex(result);
|
||||
return result.rows
|
||||
.map((row) => ({
|
||||
hash: valueFromRow(row, columns, ["commit_hash", "hash", "commit"]),
|
||||
parents: parseParents(valueFromRow(row, columns, ["parents", "parent_hashes", "parent"])),
|
||||
committer: valueFromRow(row, columns, ["committer", "commit_user", "author", "name"]),
|
||||
email: valueFromRow(row, columns, ["email", "committer_email", "author_email"]),
|
||||
date: valueFromRow(row, columns, ["date", "commit_date", "timestamp"]),
|
||||
message: valueFromRow(row, columns, ["message", "commit_message"]),
|
||||
refs: parseRefs(valueFromRow(row, columns, ["refs", "ref_names", "decorations", "decorate"])),
|
||||
}))
|
||||
.filter((commit) => commit.hash);
|
||||
}
|
||||
|
||||
export function parseDoltBranches(result: QueryResult, activeBranch: string): DoltRef[] {
|
||||
const columns = normalizedColumnIndex(result);
|
||||
return result.rows
|
||||
.map((row) => {
|
||||
const name = valueFromRow(row, columns, ["name", "branch"]);
|
||||
return {
|
||||
name,
|
||||
hash: valueFromRow(row, columns, ["hash", "commit_hash"]),
|
||||
kind: "branch" as const,
|
||||
active: name === activeBranch,
|
||||
};
|
||||
})
|
||||
.filter((ref) => ref.name);
|
||||
}
|
||||
|
||||
export function parseDoltTags(result: QueryResult): DoltRef[] {
|
||||
const columns = normalizedColumnIndex(result);
|
||||
return result.rows
|
||||
.map((row) => ({
|
||||
name: valueFromRow(row, columns, ["tag_name", "name", "tag"]),
|
||||
hash: valueFromRow(row, columns, ["tag_hash", "hash", "commit_hash"]),
|
||||
kind: "tag" as const,
|
||||
active: false,
|
||||
}))
|
||||
.filter((ref) => ref.name);
|
||||
}
|
||||
|
||||
export function parseDoltStatus(result: QueryResult): DoltWorkingChange[] {
|
||||
const columns = normalizedColumnIndex(result);
|
||||
return result.rows
|
||||
.map((row) => ({
|
||||
tableName: valueFromRow(row, columns, ["table_name", "name", "table"]),
|
||||
staged: booleanFromRow(row, columns, ["staged", "is_staged"]),
|
||||
status: valueFromRow(row, columns, ["status", "change_type"]),
|
||||
}))
|
||||
.filter((change) => change.tableName);
|
||||
}
|
||||
|
||||
export function parseDoltTableChanges(result: QueryResult): DoltTableChange[] {
|
||||
const columns = normalizedColumnIndex(result);
|
||||
return result.rows
|
||||
.map((row) => {
|
||||
const fromTableName = valueFromRow(row, columns, ["from_table_name", "from_table"]);
|
||||
const toTableName = valueFromRow(row, columns, ["to_table_name", "to_table"]);
|
||||
return {
|
||||
tableName: toTableName || fromTableName,
|
||||
fromTableName,
|
||||
toTableName,
|
||||
diffType: valueFromRow(row, columns, ["diff_type", "change_type"]) || "modified",
|
||||
dataChange: booleanFromRow(row, columns, ["data_change", "data_changed"]),
|
||||
schemaChange: booleanFromRow(row, columns, ["schema_change", "schema_changed"]),
|
||||
};
|
||||
})
|
||||
.filter((change) => change.tableName);
|
||||
}
|
||||
|
||||
const DOLT_DIFF_METADATA_COLUMNS = new Set(["commit", "commit_hash", "commit_date", "from_commit", "to_commit", "from_commit_hash", "to_commit_hash", "from_commit_date", "to_commit_date", "table_name", "from_table_name", "to_table_name", "diff_type", "conflict_type"]);
|
||||
|
||||
function diffValue(row: QueryResult["rows"][number], index: number | undefined): QueryResult["rows"][number][number] {
|
||||
return index === undefined ? null : (row[index] ?? null);
|
||||
}
|
||||
|
||||
function diffKind(value: unknown, hasBefore: boolean, hasAfter: boolean): DoltRowChangeKind {
|
||||
const normalized = String(value ?? "")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (normalized.includes("add") || normalized.includes("insert") || normalized === "new") return "added";
|
||||
if (normalized.includes("remove") || normalized.includes("delete") || normalized.includes("drop") || normalized === "old") return "removed";
|
||||
if (!hasBefore && hasAfter) return "added";
|
||||
if (hasBefore && !hasAfter) return "removed";
|
||||
return "modified";
|
||||
}
|
||||
|
||||
function normalizedDiffColumnName(column: string): string {
|
||||
const unqualified = column.trim().split(".").pop() ?? column;
|
||||
return unqualified.replace(/^[`"\x5b]|[`"\x5d]$/g, "").trim();
|
||||
}
|
||||
|
||||
function diffColumnSide(column: string): { side: "from" | "to"; field: string } | null {
|
||||
const name = normalizedDiffColumnName(column);
|
||||
const normalized = name.toLowerCase();
|
||||
if (normalized.startsWith("from_")) return { side: "from", field: name.slice(5) };
|
||||
if (normalized.startsWith("to_")) return { side: "to", field: name.slice(3) };
|
||||
if (normalized.endsWith("_from")) return { side: "from", field: name.slice(0, -5) };
|
||||
if (normalized.endsWith("_to")) return { side: "to", field: name.slice(0, -3) };
|
||||
return null;
|
||||
}
|
||||
|
||||
export function parseDoltRowDiff(result: QueryResult, schemaChange = false): DoltParsedRowDiff {
|
||||
const pairs = new Map<string, { name: string; fromIndex?: number; toIndex?: number }>();
|
||||
let diffTypeIndex: number | undefined;
|
||||
result.columns.forEach((column, index) => {
|
||||
const normalized = normalizedDiffColumnName(column).toLowerCase();
|
||||
if (normalized === "diff_type") diffTypeIndex = index;
|
||||
const descriptor = diffColumnSide(column);
|
||||
if (!descriptor || !descriptor.field || DOLT_DIFF_METADATA_COLUMNS.has(normalized)) return;
|
||||
const key = descriptor.field.toLowerCase();
|
||||
const pair = pairs.get(key) ?? { name: descriptor.field };
|
||||
if (descriptor.side === "from") pair.fromIndex = index;
|
||||
else pair.toIndex = index;
|
||||
pairs.set(key, pair);
|
||||
});
|
||||
|
||||
const columns = [...pairs.values()];
|
||||
const rows = result.rows.map((row) => {
|
||||
const before = columns.map((pair) => diffValue(row, pair.fromIndex));
|
||||
const after = columns.map((pair) => diffValue(row, pair.toIndex));
|
||||
const hasBefore = before.some((value) => value !== null);
|
||||
const hasAfter = after.some((value) => value !== null);
|
||||
const changedColumns = columns.filter((_, index) => before[index] !== after[index]).map((pair) => pair.name);
|
||||
return {
|
||||
kind: diffKind(diffValue(row, diffTypeIndex), hasBefore, hasAfter),
|
||||
before,
|
||||
after,
|
||||
changedColumns,
|
||||
};
|
||||
});
|
||||
|
||||
const columnKinds = columns.map((pair, index): DoltDiffColumnKind => {
|
||||
if (pair.fromIndex === undefined) return "added";
|
||||
if (pair.toIndex === undefined) return "removed";
|
||||
if (!schemaChange) return "unchanged";
|
||||
const hasBeforeValue = rows.some((row) => row.before[index] !== null && String(row.before[index]).trim() !== "");
|
||||
const hasAfterValue = rows.some((row) => row.after[index] !== null && String(row.after[index]).trim() !== "");
|
||||
if (!hasBeforeValue && hasAfterValue) return "added";
|
||||
if (hasBeforeValue && !hasAfterValue) return "removed";
|
||||
return "unchanged";
|
||||
});
|
||||
|
||||
return {
|
||||
columns: columns.map((pair) => pair.name),
|
||||
columnKinds,
|
||||
rows,
|
||||
};
|
||||
}
|
||||
|
||||
function matchingHash(hashes: Iterable<string>, candidate: string): string | undefined {
|
||||
for (const hash of hashes) {
|
||||
if (hash === candidate || hash.startsWith(candidate) || candidate.startsWith(hash)) return hash;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function doltRefsByCommit(commits: readonly DoltCommit[], refs: readonly DoltRef[]): Map<string, DoltRef[]> {
|
||||
const hashes = commits.map((commit) => commit.hash);
|
||||
const result = new Map<string, DoltRef[]>();
|
||||
const seenByHash = new Map<string, Set<string>>();
|
||||
const append = (hash: string, ref: DoltRef) => {
|
||||
const seen = seenByHash.get(hash) ?? new Set<string>();
|
||||
const key = `${ref.kind}:${ref.name}`;
|
||||
if (seen.has(key)) return;
|
||||
seen.add(key);
|
||||
seenByHash.set(hash, seen);
|
||||
const entries = result.get(hash) ?? [];
|
||||
entries.push(ref);
|
||||
result.set(hash, entries);
|
||||
};
|
||||
|
||||
for (const ref of refs) {
|
||||
const hash = matchingHash(hashes, ref.hash);
|
||||
if (!hash) continue;
|
||||
append(hash, ref);
|
||||
}
|
||||
for (const commit of commits) {
|
||||
for (const decoration of commit.refs) {
|
||||
const ref = decorationRef(decoration, commit.hash);
|
||||
if (ref) append(commit.hash, ref);
|
||||
}
|
||||
}
|
||||
for (const entries of result.values()) {
|
||||
entries.sort((left, right) => Number(right.active) - Number(left.active) || (left.kind === right.kind ? left.name.localeCompare(right.name) : left.kind === "branch" ? -1 : 1));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function doltRefColorIndexes(refs: Iterable<string>, colorCount: number): Map<string, number> {
|
||||
const normalizedColorCount = Math.max(1, Math.floor(colorCount));
|
||||
const names = [...new Set([...refs].map((ref) => ref.trim()).filter(Boolean))].sort();
|
||||
const result = new Map<string, number>();
|
||||
const used = new Set<number>();
|
||||
for (const name of names) {
|
||||
let hash = 0;
|
||||
for (let index = 0; index < name.length; index += 1) hash = (Math.imul(31, hash) + name.charCodeAt(index)) | 0;
|
||||
const preferred = ((hash % normalizedColorCount) + normalizedColorCount) % normalizedColorCount;
|
||||
let colorIndex = preferred;
|
||||
for (let offset = 0; offset < normalizedColorCount; offset += 1) {
|
||||
const candidate = (preferred + offset) % normalizedColorCount;
|
||||
if (!used.has(candidate)) {
|
||||
colorIndex = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
result.set(name, colorIndex);
|
||||
used.add(colorIndex);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function primaryGraphRef(refs: readonly DoltRef[], activeBranch: string): string | null {
|
||||
return refs.find((ref) => ref.kind === "branch" && (ref.active || ref.name === activeBranch))?.name ?? refs.find((ref) => ref.kind === "branch" && !ref.name.startsWith("origin/"))?.name ?? refs[0]?.name ?? null;
|
||||
}
|
||||
|
||||
export function layoutDoltCommitGraph(commits: readonly DoltCommit[], refs: readonly DoltRef[] = [], activeBranch = ""): { rows: DoltGraphLayout[]; laneCount: number } {
|
||||
const knownHashes = new Set(commits.map((commit) => commit.hash));
|
||||
const canonical = (hash: string) => matchingHash(knownHashes, hash) ?? hash;
|
||||
const commitIndexByHash = new Map<string, number>();
|
||||
commits.forEach((commit, index) => {
|
||||
commitIndexByHash.set(commit.hash, index);
|
||||
if (commit.hash.length > 8) commitIndexByHash.set(commit.hash.slice(0, 8), index);
|
||||
});
|
||||
const refByCommit = doltRefsByCommit(commits, refs);
|
||||
const refByHash = new Map<string, string>();
|
||||
for (const commit of commits) {
|
||||
const ref = primaryGraphRef(refByCommit.get(commit.hash) ?? [], activeBranch);
|
||||
if (ref) refByHash.set(commit.hash, ref);
|
||||
}
|
||||
|
||||
// Reserve lane 0 for the active branch's first-parent chain. Dolt returns
|
||||
// merge history in a topological order where side commits can appear between
|
||||
// mainline commits, so lane allocation must be driven by branch ancestry
|
||||
// rather than by the order in which rows happen to be returned.
|
||||
const commitByHash = new Map(commits.map((commit) => [commit.hash, commit]));
|
||||
const activeBranchRef = refs.find((ref) => ref.kind === "branch" && (ref.active || ref.name === activeBranch));
|
||||
let primaryHash = activeBranchRef ? canonical(activeBranchRef.hash) : undefined;
|
||||
if (!primaryHash && activeBranch) {
|
||||
primaryHash = commits.find((commit) => refByCommit.get(commit.hash)?.some((ref) => ref.kind === "branch" && ref.name === activeBranch))?.hash;
|
||||
}
|
||||
if (activeBranch && (!primaryHash || !commitByHash.has(primaryHash))) primaryHash = commits[0]?.hash;
|
||||
const primaryCommitHashes = new Set<string>();
|
||||
while (primaryHash && commitByHash.has(primaryHash) && !primaryCommitHashes.has(primaryHash)) {
|
||||
primaryCommitHashes.add(primaryHash);
|
||||
primaryHash = canonical(commitByHash.get(primaryHash)?.parents[0] ?? "");
|
||||
}
|
||||
|
||||
let lanes: Array<string | null> = [];
|
||||
let laneRefs: Array<string | null> = [];
|
||||
const rows: DoltGraphLayout[] = [];
|
||||
let laneCount = 1;
|
||||
|
||||
const setLane = (values: Array<string | null>, lane: number, value: string | null) => {
|
||||
while (values.length <= lane) values.push(null);
|
||||
values[lane] = value;
|
||||
};
|
||||
const firstEmptyLane = (values: Array<string | null>, startLane: number, blockedLane = -1) => {
|
||||
for (let lane = Math.max(0, startLane); lane < values.length; lane += 1) {
|
||||
if (lane !== blockedLane && values[lane] === null) return lane;
|
||||
}
|
||||
values.push(null);
|
||||
return values.length - 1;
|
||||
};
|
||||
|
||||
for (let rowIndex = 0; rowIndex < commits.length; rowIndex += 1) {
|
||||
const commit = commits[rowIndex];
|
||||
const isPrimaryCommit = primaryCommitHashes.has(commit.hash);
|
||||
let nodeLane = lanes.indexOf(commit.hash);
|
||||
if (isPrimaryCommit) {
|
||||
if (nodeLane > 0) {
|
||||
const laneZeroHash = lanes[0] ?? null;
|
||||
const laneZeroRef = laneRefs[0] ?? null;
|
||||
setLane(lanes, 0, commit.hash);
|
||||
setLane(laneRefs, 0, laneRefs[nodeLane] ?? null);
|
||||
setLane(lanes, nodeLane, laneZeroHash);
|
||||
setLane(laneRefs, nodeLane, laneZeroRef);
|
||||
} else if (nodeLane < 0) {
|
||||
if (lanes[0] && lanes[0] !== commit.hash) {
|
||||
const displacedLane = firstEmptyLane(lanes, 1);
|
||||
setLane(lanes, displacedLane, lanes[0]);
|
||||
setLane(laneRefs, displacedLane, laneRefs[0] ?? null);
|
||||
}
|
||||
nodeLane = 0;
|
||||
setLane(lanes, nodeLane, commit.hash);
|
||||
}
|
||||
nodeLane = 0;
|
||||
} else {
|
||||
if (nodeLane === 0 && primaryCommitHashes.size > 0) {
|
||||
const displacedLane = firstEmptyLane(lanes, 1);
|
||||
setLane(lanes, displacedLane, lanes[0] ?? null);
|
||||
setLane(laneRefs, displacedLane, laneRefs[0] ?? null);
|
||||
setLane(lanes, 0, null);
|
||||
setLane(laneRefs, 0, null);
|
||||
nodeLane = displacedLane;
|
||||
}
|
||||
if (nodeLane < 0) {
|
||||
nodeLane = firstEmptyLane(lanes, primaryCommitHashes.size > 0 ? 1 : rowIndex === 0 ? 0 : 1);
|
||||
setLane(lanes, nodeLane, commit.hash);
|
||||
}
|
||||
}
|
||||
const commitRef = refByHash.get(commit.hash) ?? laneRefs[nodeLane] ?? null;
|
||||
setLane(laneRefs, nodeLane, commitRef);
|
||||
|
||||
const edges: DoltGraphEdge[] = [];
|
||||
const visibleParents = commit.parents.map(canonical).filter((parent) => commitIndexByHash.has(parent));
|
||||
const nextLanes = [...lanes];
|
||||
const nextLaneRefs = [...laneRefs];
|
||||
if (visibleParents.length === 0) {
|
||||
setLane(nextLanes, nodeLane, null);
|
||||
setLane(nextLaneRefs, nodeLane, null);
|
||||
} else {
|
||||
visibleParents.forEach((parent, parentIndex) => {
|
||||
let parentLane: number;
|
||||
if (parentIndex === 0) {
|
||||
const existingParentLane = nextLanes.indexOf(parent);
|
||||
if (existingParentLane >= 0 && existingParentLane !== nodeLane) {
|
||||
parentLane = existingParentLane;
|
||||
} else {
|
||||
for (let lane = 0; lane < nextLanes.length; lane += 1) {
|
||||
if (nextLanes[lane] === parent) nextLanes[lane] = null;
|
||||
}
|
||||
parentLane = nodeLane;
|
||||
setLane(nextLanes, parentLane, parent);
|
||||
}
|
||||
} else {
|
||||
parentLane = nextLanes.indexOf(parent);
|
||||
if (parentLane < 0 || parentLane === nodeLane) {
|
||||
if (parentLane === nodeLane) setLane(nextLanes, parentLane, null);
|
||||
parentLane = firstEmptyLane(nextLanes, 0, nodeLane);
|
||||
}
|
||||
setLane(nextLanes, parentLane, parent);
|
||||
}
|
||||
let parentRef = refByHash.get(parent) ?? nextLaneRefs[parentLane] ?? null;
|
||||
if (parentIndex === 0 && !parentRef) parentRef = laneRefs[nodeLane] ?? null;
|
||||
setLane(nextLaneRefs, parentLane, parentRef);
|
||||
edges.push({ fromLane: nodeLane, toLane: parentLane, colorLane: parentIndex === 0 ? nodeLane : parentLane, colorRef: parentIndex === 0 ? (laneRefs[nodeLane] ?? null) : parentRef });
|
||||
});
|
||||
for (let lane = 0; lane < nextLanes.length; lane += 1) {
|
||||
if (nextLanes[lane] === commit.hash) nextLanes[lane] = null;
|
||||
}
|
||||
}
|
||||
|
||||
for (let lane = 0; lane < lanes.length; lane += 1) {
|
||||
const laneHash = lanes[lane];
|
||||
if (!laneHash || laneHash === commit.hash) continue;
|
||||
const targetLane = nextLanes.indexOf(laneHash);
|
||||
if (targetLane < 0) continue;
|
||||
const colorRef = laneRefs[lane] ?? null;
|
||||
setLane(nextLaneRefs, targetLane, colorRef);
|
||||
edges.push({ fromLane: lane, toLane: targetLane, colorLane: lane, colorRef });
|
||||
}
|
||||
|
||||
const maxLane = Math.max(
|
||||
0,
|
||||
lanes.reduce((maximum, hash, lane) => (hash ? Math.max(maximum, lane) : maximum), 0),
|
||||
nextLanes.reduce((maximum, hash, lane) => (hash ? Math.max(maximum, lane) : maximum), 0),
|
||||
);
|
||||
rows.push({ lane: nodeLane, nodeRef: laneRefs[nodeLane] ?? null, edges, maxLane });
|
||||
laneCount = Math.max(laneCount, maxLane + 1, nodeLane + 1);
|
||||
|
||||
const seen = new Set<string>();
|
||||
for (let lane = 0; lane < nextLanes.length; lane += 1) {
|
||||
const hash = nextLanes[lane];
|
||||
const targetIndex = hash ? commitIndexByHash.get(hash) : undefined;
|
||||
if (!hash || targetIndex === undefined || targetIndex < rowIndex + 1 || seen.has(hash)) {
|
||||
nextLanes[lane] = null;
|
||||
nextLaneRefs[lane] = null;
|
||||
} else {
|
||||
seen.add(hash);
|
||||
}
|
||||
}
|
||||
while (nextLanes.length > 0 && nextLanes[nextLanes.length - 1] === null) {
|
||||
nextLanes.pop();
|
||||
nextLaneRefs.pop();
|
||||
}
|
||||
lanes = nextLanes;
|
||||
laneRefs = nextLaneRefs.slice(0, nextLanes.length);
|
||||
}
|
||||
return { rows, laneCount };
|
||||
}
|
||||
@@ -134,6 +134,10 @@ export function tabDisplayTitle(tab: QueryTab, t: Translate): string {
|
||||
if (tab.mode === "mqtt") {
|
||||
return `${connectionDisplayName(tab.connectionId)} - ${t("connection.mqttConsoleTitle")}`;
|
||||
}
|
||||
if (tab.mode === "dolt-version-control") {
|
||||
const branch = tab.workspaceBranch?.trim();
|
||||
return `${connectionDisplayName(tab.connectionId)} VCS@${database}${branch ? `.${branch}` : ""}`;
|
||||
}
|
||||
if (tab.mode === "databases") {
|
||||
if (compact) return t("tabs.databases");
|
||||
return `${t("tabs.databases")}@${connectionDisplayName(tab.connectionId)}`;
|
||||
@@ -452,5 +456,6 @@ export function tabModeLabel(tab: QueryTab, t: Translate): string {
|
||||
if (tab.mode === "databases") return t("tabs.databases");
|
||||
if (tab.mode === "objects") return t("tabs.objects");
|
||||
if (tab.mode === "users") return t("tabs.users");
|
||||
if (tab.mode === "dolt-version-control") return t("doltVersionControl.title");
|
||||
return tab.mode;
|
||||
}
|
||||
Reference in new issue
Block a user