feat(sidebar): manage saved SQL by database

This commit is contained in:
zhangyc authored and GitHub committed 2026-08-13 15:26:45 +08:00
1 parent 1efb3de113
commit 5f60fbe196
40 files changed
+1631 -150

No files matched your search

@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import { nextSavedSqlCopyName, savedSqlClipboardFileIds, savedSqlPasteTargetForNode } from "@/lib/savedSql/savedSqlClipboard";
import { savedSqlExportFileName } from "@/lib/savedSql/savedSqlExport";
import type { TreeNode } from "@/types/database";
describe("saved SQL tree clipboard", () => {
it("collects unique saved SQL ids from tree rows", () => {
const nodes: TreeNode[] = [
{ id: "file-1", label: "report.sql", type: "saved-sql-file", savedSqlId: "sql-1" },
{ id: "file-1-copy", label: "report.sql", type: "saved-sql-file", savedSqlId: "sql-1" },
{ id: "table-1", label: "report", type: "table" },
];
expect(savedSqlClipboardFileIds(nodes)).toEqual(["sql-1"]);
});
it("resolves database scope from a Queries node or saved SQL row", () => {
expect(savedSqlPasteTargetForNode({ type: "saved-sql-root", connectionId: "conn-1", catalog: "hive", database: "app" })).toEqual({ connectionId: "conn-1", catalog: "hive", database: "app", schema: undefined });
expect(savedSqlPasteTargetForNode({ type: "saved-sql-file", connectionId: "conn-1", database: "app", schema: "public" })).toEqual({ connectionId: "conn-1", catalog: undefined, database: "app", schema: "public" });
expect(savedSqlPasteTargetForNode({ type: "schema", connectionId: "conn-1", database: "app", schema: "public" })).toBeNull();
});
it("uses Navicat-style incrementing copy suffixes", () => {
expect(nextSavedSqlCopyName("query.sql", new Set(["query.sql"]))).toBe("query_copy1.sql");
expect(nextSavedSqlCopyName("query.sql", new Set(["query.sql", "query_copy1.sql", "QUERY_COPY2.SQL"]))).toBe("query_copy3.sql");
expect(nextSavedSqlCopyName("query_copy1.sql", new Set(["query_copy1.sql"]))).toBe("query_copy2.sql");
});
it("sanitizes exported SQL file names", () => {
expect(savedSqlExportFileName("report<2026>:daily")).toBe("report_2026__daily.sql");
});
});
@@ -0,0 +1,98 @@
import { describe, expect, it } from "vitest";
import { buildDatabaseSavedSqlRootNode, decorateDatabaseSavedSqlTreeNodes, indexSavedSqlFilesByDatabase, savedSqlFilesForDatabase, stripDatabaseSavedSqlTreeNodes } from "@/lib/savedSql/savedSqlDatabaseTree";
import type { SavedSqlFile, TreeNode } from "@/types/database";
function file(input: Partial<SavedSqlFile> & Pick<SavedSqlFile, "id" | "name" | "connectionId" | "database">): SavedSqlFile {
return {
sql: "select 1",
createdAt: "2026-08-12T00:00:00.000Z",
updatedAt: "2026-08-12T00:00:00.000Z",
...input,
};
}
const files = [
file({ id: "orders-10", name: "orders-10.sql", connectionId: "conn-1", database: "app", folderId: "reports" }),
file({ id: "orders-2", name: "orders-2.sql", connectionId: "conn-1", database: "app" }),
file({ id: "analytics", name: "analytics.sql", connectionId: "conn-1", database: "analytics" }),
file({ id: "other-connection", name: "orders.sql", connectionId: "conn-2", database: "app" }),
];
describe("savedSqlFilesForDatabase", () => {
it("filters by the persisted connection and database association across all SQL library folders", () => {
expect(savedSqlFilesForDatabase(files, { connectionId: "conn-1", database: "app" }).map((item) => item.id)).toEqual(["orders-2", "orders-10"]);
});
it("keeps each original SQL before its naturally ordered copies", () => {
const copiedFiles = [
file({ id: "query-5-copy-10", name: "query_5_copy10.sql", connectionId: "conn-1", database: "app" }),
file({ id: "query-10", name: "query_10.sql", connectionId: "conn-1", database: "app" }),
file({ id: "query-5-copy-1", name: "query_5_copy1.sql", connectionId: "conn-1", database: "app" }),
file({ id: "query-2", name: "query_2.sql", connectionId: "conn-1", database: "app" }),
file({ id: "query-5", name: "query_5.sql", connectionId: "conn-1", database: "app" }),
file({ id: "query-5-copy-2", name: "query_5_copy2.sql", connectionId: "conn-1", database: "app" }),
];
expect(savedSqlFilesForDatabase(copiedFiles, { connectionId: "conn-1", database: "app" }).map((item) => item.name)).toEqual(["query_2.sql", "query_5.sql", "query_5_copy1.sql", "query_5_copy2.sql", "query_5_copy10.sql", "query_10.sql"]);
});
it("separates same-named databases by catalog and indexes all files once", () => {
const catalogFiles = [
file({ id: "default", name: "default.sql", connectionId: "conn-1", database: "analytics" }),
file({ id: "hive", name: "hive.sql", connectionId: "conn-1", catalog: "hive", database: "analytics" }),
file({ id: "iceberg", name: "iceberg.sql", connectionId: "conn-1", catalog: "iceberg", database: "analytics" }),
];
const index = indexSavedSqlFilesByDatabase(catalogFiles);
expect(savedSqlFilesForDatabase(index, { connectionId: "conn-1", database: "analytics" }).map((item) => item.id)).toEqual(["default"]);
expect(savedSqlFilesForDatabase(index, { connectionId: "conn-1", catalog: "hive", database: "analytics" }).map((item) => item.id)).toEqual(["hive"]);
expect(savedSqlFilesForDatabase(index, { connectionId: "conn-1", catalog: "iceberg", database: "analytics" }).map((item) => item.id)).toEqual(["iceberg"]);
});
});
describe("database saved SQL tree", () => {
const database: TreeNode = {
id: "conn-1:app",
label: "app",
type: "database",
connectionId: "conn-1",
database: "app",
children: [],
};
it("keeps a visible Queries node even when the database has no saved SQL", () => {
const root = buildDatabaseSavedSqlRootNode(database, []);
expect(root).toMatchObject({ id: "conn-1:app:__queries", label: "tree.queries", type: "saved-sql-root", children: [] });
});
it("adds Queries after database metadata and preserves its expansion state", () => {
const existingRoot = { ...buildDatabaseSavedSqlRootNode(database, files)!, isExpanded: false };
const decorated = decorateDatabaseSavedSqlTreeNodes(
[
{
...database,
children: [{ id: "conn-1:app:tables", label: "tree.tables", type: "group-tables" }],
},
],
files,
[{ ...database, children: [existingRoot] }],
);
expect(decorated[0].children?.map((child) => child.type)).toEqual(["group-tables", "saved-sql-root"]);
expect(decorated[0].children?.at(-1)).toMatchObject({ isExpanded: false, children: [{ savedSqlId: "orders-2" }, { savedSqlId: "orders-10" }] });
});
it("removes runtime saved SQL nodes before metadata is cached", () => {
const decorated = decorateDatabaseSavedSqlTreeNodes([database], files);
expect(stripDatabaseSavedSqlTreeNodes(decorated)).toEqual([{ ...database, children: [] }]);
});
it("renders a saved SQL only below its exact catalog database", () => {
const catalogFiles = [file({ id: "hive", name: "hive.sql", connectionId: "conn-1", catalog: "hive", database: "app" })];
const defaultRoot = buildDatabaseSavedSqlRootNode(database, catalogFiles);
const hiveRoot = buildDatabaseSavedSqlRootNode({ ...database, id: "conn-1:hive:app", catalog: "hive" }, catalogFiles);
expect(defaultRoot?.children).toEqual([]);
expect(hiveRoot).toMatchObject({ catalog: "hive", children: [{ catalog: "hive", savedSqlId: "hive" }] });
});
});
@@ -10,4 +10,15 @@ describe("sidebar active-tab targets", () => {
expect(matchesTarget({ id: "connection:pg-1", label: "Postgres", type: "connection", connectionId: "pg-1" } as TreeNode, target!)).toBe(true);
expect(matchesTarget({ id: "connection:pg-2", label: "Other", type: "connection", connectionId: "pg-2" } as TreeNode, target!)).toBe(false);
});
it("locates a query context only in its exact catalog", () => {
const target = activeTabSidebarTarget({ mode: "query", connectionId: "doris-1", catalog: "hive", database: "analytics" } as QueryTab);
const hiveDatabase = { id: "hive:analytics", label: "analytics", type: "database", connectionId: "doris-1", catalog: "hive", database: "analytics" } as TreeNode;
const icebergDatabase = { ...hiveDatabase, id: "iceberg:analytics", catalog: "iceberg" };
const defaultDatabase = { ...hiveDatabase, id: "default:analytics", catalog: undefined };
expect(matchesTarget(hiveDatabase, target!)).toBe(true);
expect(matchesTarget(icebergDatabase, target!)).toBe(false);
expect(matchesTarget(defaultDatabase, target!)).toBe(false);
});
});
@@ -38,6 +38,21 @@ describe("treeNodeLoadedChildrenContentPresent", () => {
expect(treeNodeLoadedChildrenContentPresent(databaseNode(), "simple")).toBe(true);
});
it("does not mistake the runtime Queries node for loaded database metadata", () => {
const node = databaseNode([
{
id: "conn:test1:__queries",
label: "tree.queries",
type: "saved-sql-root",
connectionId: "conn",
database: "test1",
children: [],
},
]);
expect(treeNodeLoadedChildrenContentPresent(node, "grouped")).toBe(false);
expect(simpleModeEmptyShellNeedsConfirmedLoad(node, "simple")).toBe(true);
});
it("accepts loaded object groups with zero items", () => {
const node: TreeNode = {
id: "conn:test1:__tables",
@@ -0,0 +1,35 @@
import { ensureSqlExtension, stripSqlExtension } from "@/lib/savedSql/savedSqlFileName";
import type { TreeNode } from "@/types/database";
export interface SavedSqlPasteTarget {
connectionId: string;
catalog?: string;
database: string;
schema?: string;
}
export function savedSqlClipboardFileIds(nodes: readonly TreeNode[]): string[] {
return [...new Set(nodes.filter((node) => node.type === "saved-sql-file" && !!node.savedSqlId).map((node) => node.savedSqlId!))];
}
export function savedSqlPasteTargetForNode(node: Pick<TreeNode, "type" | "connectionId" | "catalog" | "database" | "schema">): SavedSqlPasteTarget | null {
if (node.type !== "database" && node.type !== "saved-sql-root" && node.type !== "saved-sql-file") return null;
if (!node.connectionId || node.database === undefined) return null;
return {
connectionId: node.connectionId,
catalog: node.catalog,
database: node.database,
schema: node.schema,
};
}
export function nextSavedSqlCopyName(sourceName: string, takenNames: ReadonlySet<string>): string {
const normalizedSource = ensureSqlExtension(sourceName);
const sourceBase = stripSqlExtension(normalizedSource);
const copyBase = sourceBase.replace(/_copy\d+$/i, "") || sourceBase;
const normalizedTakenNames = new Set([...takenNames].map((name) => ensureSqlExtension(name).toLocaleLowerCase()));
let index = 1;
while (normalizedTakenNames.has(`${copyBase}_copy${index}.sql`.toLocaleLowerCase())) index++;
return `${copyBase}_copy${index}.sql`;
}
@@ -0,0 +1,118 @@
import type { SavedSqlFile, TreeNode } from "@/types/database";
import { stripSqlExtension } from "@/lib/savedSql/savedSqlFileName";
const savedSqlNameCollator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
function savedSqlCopySortKey(name: string): { base: string; copyIndex: number } {
const base = stripSqlExtension(name);
const copyMatch = base.match(/^(.*)_copy(\d+)$/i);
if (!copyMatch?.[1]) return { base, copyIndex: 0 };
return { base: copyMatch[1], copyIndex: Number(copyMatch[2]) };
}
function compareSavedSqlFiles(left: SavedSqlFile, right: SavedSqlFile): number {
const leftKey = savedSqlCopySortKey(left.name);
const rightKey = savedSqlCopySortKey(right.name);
return savedSqlNameCollator.compare(leftKey.base, rightKey.base) || leftKey.copyIndex - rightKey.copyIndex || savedSqlNameCollator.compare(left.name, right.name) || left.id.localeCompare(right.id);
}
export interface SavedSqlDatabaseScope {
connectionId: string;
catalog?: string;
database: string;
}
export type SavedSqlDatabaseIndex = ReadonlyMap<string, readonly SavedSqlFile[]>;
type SavedSqlDatabaseSource = readonly SavedSqlFile[] | SavedSqlDatabaseIndex;
export function savedSqlDatabaseScopeKey(scope: SavedSqlDatabaseScope): string {
// Null is deliberately a concrete built-in/default catalog scope, not a wildcard.
return JSON.stringify([scope.connectionId, scope.catalog || null, scope.database]);
}
export function indexSavedSqlFilesByDatabase(files: readonly SavedSqlFile[]): SavedSqlDatabaseIndex {
const index = new Map<string, SavedSqlFile[]>();
for (const file of files) {
const key = savedSqlDatabaseScopeKey(file);
const scopedFiles = index.get(key);
if (scopedFiles) scopedFiles.push(file);
else index.set(key, [file]);
}
for (const scopedFiles of index.values()) scopedFiles.sort(compareSavedSqlFiles);
return index;
}
export function savedSqlFilesForDatabase(source: SavedSqlDatabaseSource, scope: SavedSqlDatabaseScope): SavedSqlFile[] {
if (!Array.isArray(source)) return [...((source as SavedSqlDatabaseIndex).get(savedSqlDatabaseScopeKey(scope)) ?? [])];
return source.filter((file) => savedSqlDatabaseScopeKey(file) === savedSqlDatabaseScopeKey(scope)).sort(compareSavedSqlFiles);
}
function savedSqlFileNode(rootId: string, file: SavedSqlFile): TreeNode {
return {
id: `${rootId}:file:${file.id}`,
label: file.name,
type: "saved-sql-file",
connectionId: file.connectionId,
catalog: file.catalog,
database: file.database,
schema: file.schema,
savedSqlId: file.id,
};
}
export function buildDatabaseSavedSqlRootNode(databaseNode: Pick<TreeNode, "id" | "connectionId" | "catalog" | "database">, source: SavedSqlDatabaseSource, existingRoot?: TreeNode): TreeNode | null {
if (!databaseNode.connectionId || databaseNode.database === undefined) return null;
const id = `${databaseNode.id}:__queries`;
return {
id,
label: "tree.queries",
type: "saved-sql-root",
connectionId: databaseNode.connectionId,
catalog: databaseNode.catalog,
database: databaseNode.database,
isExpanded: existingRoot?.isExpanded ?? true,
children: savedSqlFilesForDatabase(source, {
connectionId: databaseNode.connectionId,
catalog: databaseNode.catalog,
database: databaseNode.database,
}).map((file) => savedSqlFileNode(id, file)),
};
}
export function withDatabaseSavedSqlRoot(databaseNode: Pick<TreeNode, "id" | "connectionId" | "catalog" | "database" | "children">, children: readonly TreeNode[], source: SavedSqlDatabaseSource): TreeNode[] {
const existingRoot = databaseNode.children?.find((child) => child.type === "saved-sql-root");
const root = buildDatabaseSavedSqlRootNode(databaseNode, source, existingRoot);
const metadataChildren = children.filter((child) => child.type !== "saved-sql-root");
return root ? [...metadataChildren, root] : metadataChildren;
}
export function decorateDatabaseSavedSqlTreeNodes(nodes: readonly TreeNode[], source: SavedSqlDatabaseSource, existingNodes: readonly TreeNode[] = []): TreeNode[] {
const existingById = new Map(existingNodes.map((node) => [node.id, node]));
return nodes.map((node) => {
const existing = existingById.get(node.id);
const children = decorateDatabaseSavedSqlTreeNodes(node.children ?? [], source, existing?.children ?? []);
if (node.type !== "database") {
return node.children === undefined ? node : { ...node, children };
}
const databaseNode = {
...node,
children: existing?.children ?? node.children,
};
return {
...node,
children: withDatabaseSavedSqlRoot(databaseNode, children, source),
};
});
}
export function stripDatabaseSavedSqlTreeNodes(nodes: readonly TreeNode[]): TreeNode[] {
return nodes.flatMap((node) => {
if (node.type === "saved-sql-root" || node.type === "saved-sql-file" || node.type === "saved-sql-folder") return [];
const children = node.children ? stripDatabaseSavedSqlTreeNodes(node.children) : undefined;
const hiddenChildren = node.hiddenChildren ? stripDatabaseSavedSqlTreeNodes(node.hiddenChildren) : undefined;
if (children === node.children && hiddenChildren === node.hiddenChildren) return [node];
return [{ ...node, children, hiddenChildren }];
});
}
@@ -0,0 +1,18 @@
interface SavedSqlErrorTranslator {
(key: string, params?: Record<string, unknown>): string;
}
interface SavedSqlNameConflictLike {
code?: unknown;
fileName?: unknown;
message?: unknown;
}
export function savedSqlErrorMessage(error: unknown, translate: SavedSqlErrorTranslator): string {
const candidate = error as SavedSqlNameConflictLike | null;
if (candidate?.code === "SAVED_SQL_NAME_CONFLICT" && typeof candidate.fileName === "string") {
return translate("savedSql.nameConflict", { name: candidate.fileName });
}
if (typeof candidate?.message === "string") return candidate.message;
return String(error);
}
@@ -0,0 +1,34 @@
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { ensureSqlExtension } from "@/lib/savedSql/savedSqlFileName";
export function savedSqlExportFileName(name: string): string {
return (
ensureSqlExtension(name)
.replace(/[<>:"/\\|?*\p{Cc}]/gu, "_")
.trim() || "untitled.sql"
);
}
export async function exportSavedSqlFileContent(sql: string, fileName: string): Promise<"saved" | "cancelled"> {
const defaultFileName = savedSqlExportFileName(fileName);
if (isTauriRuntime()) {
const { save } = await import("@tauri-apps/plugin-dialog");
const { writeTextFile } = await import("@tauri-apps/plugin-fs");
const path = await save({
defaultPath: defaultFileName,
filters: [{ name: "SQL", extensions: ["sql"] }],
});
if (!path) return "cancelled";
await writeTextFile(path, sql);
return "saved";
}
const blob = new Blob([sql], { type: "text/plain;charset=utf-8" });
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = defaultFileName;
anchor.click();
URL.revokeObjectURL(url);
return "saved";
}
@@ -5,6 +5,8 @@ const RECENCY_WINDOW_MS = 30 * DAY_MS;
export interface SavedSqlHistoryScope {
connectionId?: string;
/** Null explicitly selects the built-in/default catalog; undefined does not filter catalogs. */
catalog?: string | null;
database?: string;
schema?: string;
tableName?: string;
@@ -51,6 +53,7 @@ export function savedSqlHistoryScore(file: SavedSqlFile, now = Date.now()) {
export function savedSqlMatchesHistoryScope(file: SavedSqlFile, scope: SavedSqlHistoryScope) {
if (scope.connectionId && file.connectionId !== scope.connectionId) return false;
if (scope.catalog !== undefined && (file.catalog || null) !== scope.catalog) return false;
if (scope.database != null && file.database !== scope.database) return false;
if (scope.schema && file.schema && file.schema !== scope.schema) return false;
return true;
@@ -73,6 +73,7 @@ export type ActiveTabSidebarTarget =
| {
type: "query-context";
connectionId: string;
catalog?: string;
database: string;
schema?: string;
}
@@ -187,6 +188,7 @@ export function activeTabSidebarTarget(tab: QueryTab | undefined | null): Active
return {
type: "query-context",
connectionId: tab.connectionId,
catalog: tab.catalog,
database: tab.database,
schema: tab.schema,
};
@@ -231,6 +233,7 @@ export function matchesTarget(node: TreeNode, target: ActiveTabSidebarTarget): b
}
if (target.type === "query-context") {
if ((node.catalog || undefined) !== (target.catalog || undefined)) return false;
if (target.schema) {
return node.type === "schema" && node.connectionId === target.connectionId && node.database === target.database && node.label === target.schema;
}
@@ -7,7 +7,7 @@ const TABLE_STRUCTURE_GROUP_TYPES = new Set<TreeNode["type"]>(["group-columns",
/** Whether a node's in-memory children match a valid "loaded" marker (scheme A). */
export function treeNodeLoadedChildrenContentPresent(node: TreeNode, sidebarObjectDisplay: SidebarObjectDisplayMode): boolean {
const childCount = node.children?.length ?? 0;
const childCount = node.children?.filter((child) => child.type !== "saved-sql-root").length ?? 0;
if (node.type === "database" || node.type === "schema" || node.type === "linked-server-schema") {
if (childCount > 0) return true;
// Grouped mode always materializes object-group placeholders; empty means a stale shell.
@@ -23,5 +23,5 @@ export function treeNodeLoadedChildrenContentPresent(node: TreeNode, sidebarObje
export function simpleModeEmptyShellNeedsConfirmedLoad(node: TreeNode, sidebarObjectDisplay: SidebarObjectDisplayMode): boolean {
if (sidebarObjectDisplay !== "simple") return false;
if (node.type !== "database" && node.type !== "schema" && node.type !== "linked-server-schema") return false;
return (node.children?.length ?? 0) === 0;
return (node.children?.filter((child) => child.type !== "saved-sql-root").length ?? 0) === 0;
}
@@ -2,7 +2,7 @@ import type { DatabaseType, ObjectSourceKind, TreeNode, TreeNodeType } from "@/t
import { customTypeCapabilities, supportsTypeObjectSource } from "@/lib/database/databaseObjectCapabilities";
import { matchesShortcut, type ShortcutLikeEvent } from "@/lib/editor/keyboardShortcuts";
export type TreeNodeRowAction = "open-data" | "open-source" | "open-extension-details" | "toggle" | "none";
export type TreeNodeRowAction = "open-data" | "open-source" | "open-extension-details" | "open-saved-sql" | "toggle" | "none";
export type TreeNodeRowDoubleClickAction = "open-data" | "activate-data" | "open-database-browser" | "open-object-browser" | "open-object-browser-and-expand" | "open-source" | "open-extension-details" | "open-saved-sql" | "toggle" | "none";
export type SidebarSelectionCopyAction = "copy-name" | "none";
export type SidebarActivation = "single" | "double";
@@ -104,6 +104,7 @@ function canOpenTreeNodeSource(type: TreeNodeType, dbType?: DatabaseType): boole
export function treeNodeRowAction(type: TreeNodeType, canExpand: boolean, activation: SidebarActivation = "single", dbType?: DatabaseType): TreeNodeRowAction {
if (!shouldActivateTreeNodeOnSingleClick(type, activation)) return "none";
if (type === "extension") return "open-extension-details";
if (savedSqlNodeTypes.has(type)) return "open-saved-sql";
if (dataNodeTypes.has(type)) return "open-data";
// PostgreSQL-family custom types: open read-only details (toggle when expandable).
if (type === "type" && customTypeCapabilities(dbType).details) return canExpand ? "toggle" : "none";
@@ -142,6 +142,7 @@ export function queryContextTargetFromCandidate(tab: QueryTab | undefined | null
return {
type: "query-context",
connectionId: tab.connectionId,
catalog: tab.catalog,
database: candidate?.database || tab.database,
schema: candidate?.schema ?? tab.schema,
};