feat(editor): prefill new queries from focused tables

This commit is contained in:
Abeautifulsnow authored and GitHub committed 2026-07-13 16:15:09 +08:00
1 parent c2c4860a28
commit 9e1b0c478e
16 files changed
+421 -6

No files matched your search

@@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import { serializeOpenTabs, restoreOpenTabsPayload } from "@/lib/app/openTabsPersistence";
import type { QueryTab } from "@/types/database";
function queryTab(overrides: Partial<QueryTab>): QueryTab {
return {
id: "t1",
title: "query_1",
connectionId: "c1",
database: "db",
mode: "query",
sql: "",
isExecuting: false,
...overrides,
} as QueryTab;
}
function roundTrip(tabs: QueryTab[]) {
const saved = serializeOpenTabs(tabs);
return restoreOpenTabsPayload({ tabs: saved, activeTabId: tabs[0]?.id ?? null }).tabs;
}
describe("openTabsPersistence originalSql round-trip", () => {
it("restores a clean prefilled query tab as clean (sql === originalSql)", () => {
const sql = 'SELECT * FROM "public"."users"';
const [restored] = roundTrip([queryTab({ sql, originalSql: sql })]);
expect(restored.sql).toBe(sql);
expect(restored.originalSql).toBe(sql);
expect(restored.sql === restored.originalSql).toBe(true);
});
it("restores a user-edited scratch query tab as dirty (originalSql stays empty)", () => {
const [restored] = roundTrip([queryTab({ sql: "SELECT 1", originalSql: "" })]);
expect(restored.sql).toBe("SELECT 1");
expect(restored.originalSql).toBe("");
expect(restored.sql === restored.originalSql).toBe(false);
});
it("restores an empty new query tab as clean", () => {
const [restored] = roundTrip([queryTab({ sql: "", originalSql: "" })]);
expect(restored.sql).toBe("");
expect(restored.originalSql).toBe("");
});
it("falls back to empty originalSql for old saved state without the field (backward compat)", () => {
const [restored] = restoreOpenTabsPayload({
tabs: [{ id: "t1", title: "query_1", connectionId: "c1", database: "db", mode: "query", sql: "SELECT 1" }],
activeTabId: "t1",
}).tabs;
expect(restored.sql).toBe("SELECT 1");
expect(restored.originalSql).toBe("");
});
});
@@ -0,0 +1,215 @@
import { describe, expect, it } from "vitest";
import { buildSelectAllSql, isNewQueryPrefillSupported, resolveNewQueryInitialSql, resolveNewQueryTable, type ResolveNewQueryTableInput } from "@/lib/sql/newQueryContext";
import type { QueryTab, TreeNode } from "@/types/database";
function dataTab(overrides: Partial<Pick<QueryTab, "mode" | "connectionId" | "database" | "schema" | "tableMeta" | "structureTableName" | "title">> = {}): ResolveNewQueryTableInput["activeTab"] {
return {
mode: "data",
connectionId: "conn-1",
database: "app_db",
schema: "public",
title: "users",
tableMeta: { schema: "public", tableName: "users", columns: [], primaryKeys: [] },
...overrides,
};
}
function tableNode(overrides: Partial<Pick<TreeNode, "type" | "connectionId" | "database" | "schema" | "catalog" | "tableName" | "label">> = {}): ResolveNewQueryTableInput["selectedTreeNode"] {
return { type: "table", connectionId: "conn-1", database: "app_db", schema: "public", tableName: "orders", label: "orders", ...overrides };
}
describe("resolveNewQueryTable", () => {
it("resolves the table from an active data tab", () => {
const table = resolveNewQueryTable({ activeTab: dataTab(), preferredSource: "tab" });
expect(table).toEqual({ connectionId: "conn-1", database: "app_db", schema: "public", catalog: undefined, tableName: "users" });
});
it("returns null when a data tab has no loaded tableMeta (still loading or errored)", () => {
// A data tab's title is schema/catalog-qualified (e.g. "public.events"), so it must
// not be used as a bare table name - require the loaded tableMeta instead.
const table = resolveNewQueryTable({
activeTab: { mode: "data", connectionId: "conn-1", database: "app_db", schema: "public", title: "public.events" },
preferredSource: "tab",
});
expect(table).toBeNull();
});
it("resolves the table from an active structure tab", () => {
const table = resolveNewQueryTable({
activeTab: { mode: "structure", connectionId: "conn-1", database: "app_db", schema: "public", structureTableName: "users" },
preferredSource: "tab",
});
expect(table).toEqual({ connectionId: "conn-1", database: "app_db", schema: "public", catalog: undefined, tableName: "users" });
});
it("returns null for a query tab with no table context", () => {
const table = resolveNewQueryTable({
activeTab: { mode: "query", connectionId: "conn-1", database: "app_db", schema: "public", title: "query_1" },
preferredSource: "tab",
});
expect(table).toBeNull();
});
it("resolves the table from a selected sidebar table/view/materialized_view node", () => {
expect(resolveNewQueryTable({ selectedTreeNode: tableNode(), preferredSource: "sidebar" })?.tableName).toBe("orders");
expect(resolveNewQueryTable({ selectedTreeNode: tableNode({ type: "view" }), preferredSource: "sidebar" })?.tableName).toBe("orders");
expect(resolveNewQueryTable({ selectedTreeNode: tableNode({ type: "materialized_view" }), preferredSource: "sidebar" })?.tableName).toBe("orders");
});
it("uses the node label when tableName is absent", () => {
const table = resolveNewQueryTable({
selectedTreeNode: { type: "table", connectionId: "conn-1", database: "app_db", schema: "public", label: "by_label" },
preferredSource: "sidebar",
});
expect(table?.tableName).toBe("by_label");
});
it("ignores sidebar nodes that are not tables", () => {
const table = resolveNewQueryTable({
selectedTreeNode: { type: "schema", connectionId: "conn-1", label: "public" },
preferredSource: "sidebar",
});
expect(table).toBeNull();
});
it("prefers the active tab when preferredSource is 'tab'", () => {
const table = resolveNewQueryTable({ activeTab: dataTab(), selectedTreeNode: tableNode(), preferredSource: "tab" });
expect(table?.tableName).toBe("users");
});
it("prefers the sidebar node when preferredSource is 'sidebar'", () => {
const table = resolveNewQueryTable({ activeTab: dataTab(), selectedTreeNode: tableNode(), preferredSource: "sidebar" });
expect(table?.tableName).toBe("orders");
});
it("falls back to the secondary context when the primary has no table", () => {
const table = resolveNewQueryTable({
activeTab: { mode: "query", connectionId: "conn-1", database: "app_db", title: "query_1" },
selectedTreeNode: tableNode(),
preferredSource: "tab",
});
expect(table?.tableName).toBe("orders");
});
it("returns null when no context is available", () => {
expect(resolveNewQueryTable({})).toBeNull();
expect(resolveNewQueryTable({ activeTab: null, selectedTreeNode: null })).toBeNull();
});
});
describe("buildSelectAllSql", () => {
it("quotes a MySQL table with backticks", () => {
expect(buildSelectAllSql("mysql", { tableName: "users" })).toBe("SELECT * FROM `users`");
});
it("ignores the schema for non-schema-aware databases like MySQL", () => {
expect(buildSelectAllSql("mysql", { schema: "mydb", tableName: "users" })).toBe("SELECT * FROM `users`");
});
it("qualifies and quotes a PostgreSQL table with its schema", () => {
expect(buildSelectAllSql("postgres", { schema: "public", tableName: "users" })).toBe('SELECT * FROM "public"."users"');
});
it("bracket-quotes a SQL Server table", () => {
expect(buildSelectAllSql("sqlserver", { schema: "dbo", tableName: "users" })).toBe("SELECT * FROM [dbo].[users]");
expect(buildSelectAllSql("sqlserver", { tableName: "users" })).toBe("SELECT * FROM [users]");
});
it("escapes embedded quote characters", () => {
expect(buildSelectAllSql("mysql", { tableName: "a`b" })).toBe("SELECT * FROM `a``b`");
expect(buildSelectAllSql("postgres", { tableName: 'a"b' })).toBe('SELECT * FROM "a""b"');
});
});
describe("isNewQueryPrefillSupported", () => {
it("disables the prefill for Neo4j (Cypher, not SQL)", () => {
expect(isNewQueryPrefillSupported("neo4j")).toBe(false);
});
it("enables the prefill for standard SQL databases", () => {
expect(isNewQueryPrefillSupported("mysql")).toBe(true);
expect(isNewQueryPrefillSupported("postgres")).toBe(true);
expect(isNewQueryPrefillSupported("sqlserver")).toBe(true);
expect(isNewQueryPrefillSupported("sqlite")).toBe(true);
expect(isNewQueryPrefillSupported("clickhouse")).toBe(true);
});
it("enables the prefill when the database type is unknown", () => {
expect(isNewQueryPrefillSupported(undefined)).toBe(true);
});
});
describe("resolveNewQueryInitialSql", () => {
it("prefills SQL from the active table when enabled", () => {
expect(
resolveNewQueryInitialSql({
activeTab: dataTab(),
prefillEnabled: true,
targetConnectionId: "conn-1",
targetDatabase: "app_db",
databaseType: "postgres",
}),
).toBe('SELECT * FROM "public"."users"');
});
it("leaves new queries empty when the setting is disabled", () => {
expect(
resolveNewQueryInitialSql({
activeTab: dataTab(),
prefillEnabled: false,
targetConnectionId: "conn-1",
targetDatabase: "app_db",
databaseType: "postgres",
}),
).toBeUndefined();
});
it("does not prefill a table from another connection", () => {
expect(
resolveNewQueryInitialSql({
activeTab: dataTab({ connectionId: "conn-2" }),
prefillEnabled: true,
targetConnectionId: "conn-1",
targetDatabase: "app_db",
databaseType: "postgres",
}),
).toBeUndefined();
});
it("does not prefill a table from another database on the same connection", () => {
expect(
resolveNewQueryInitialSql({
activeTab: { mode: "query", connectionId: "conn-1", database: "db_a", title: "query_1" },
selectedTreeNode: tableNode({ database: "db_b" }),
preferredSource: "tab",
prefillEnabled: true,
targetConnectionId: "conn-1",
targetDatabase: "db_a",
databaseType: "mysql",
}),
).toBeUndefined();
});
it("leaves new queries empty without a table context", () => {
expect(
resolveNewQueryInitialSql({
prefillEnabled: true,
targetConnectionId: "conn-1",
targetDatabase: "app_db",
databaseType: "postgres",
}),
).toBeUndefined();
});
it("does not prefill for unsupported database types (e.g. Neo4j)", () => {
expect(
resolveNewQueryInitialSql({
activeTab: dataTab(),
prefillEnabled: true,
targetConnectionId: "conn-1",
targetDatabase: "app_db",
databaseType: "neo4j",
}),
).toBeUndefined();
});
});
@@ -22,6 +22,7 @@ export interface SavedOpenTab {
database: string;
schema?: string;
sql: string;
originalSql?: string;
savedSqlId?: string;
externalSqlPath?: string;
lastExecutedSql?: string;
@@ -69,6 +70,10 @@ function restoredOriginalSql(tab: SavedOpenTab, mode: QueryTab["mode"], sql: str
if (mode !== "query") return undefined;
if (tab.externalSqlPath) return sql;
if (tab.savedSqlId) return sql ? "" : undefined;
// Prefer the persisted originalSql so a clean prefilled query tab (sql === originalSql)
// restores clean instead of being marked dirty. Older saved state without this field
// falls through to "" (preserving prior behavior for user-edited scratch tabs).
if (tab.originalSql !== undefined) return tab.originalSql;
return "";
}
@@ -81,6 +86,10 @@ export function serializeOpenTabs(tabs: QueryTab[]): SavedOpenTab[] {
database: tab.database,
schema: tab.schema,
sql: shouldPersistTabSql(tab) ? tab.sql : "",
// Only round-trip originalSql for plain query tabs (no savedSqlId / externalSqlPath):
// saved-SQL and external-file tabs re-derive it on restore, and persisting it here
// would duplicate their (potentially large) SQL text in the open-tabs state.
...(tab.originalSql !== undefined && !tab.savedSqlId && !tab.externalSqlPath ? { originalSql: tab.originalSql } : {}),
savedSqlId: tab.savedSqlId,
externalSqlPath: tab.externalSqlPath,
...(tab.lastExecutedSql !== undefined ? { lastExecutedSql: tab.lastExecutedSql } : {}),
@@ -38,6 +38,7 @@ export const EDITOR_SETTINGS_DRAFT_KEYS = [
"openTabsRestoreMode",
"disconnectTabHandlingMode",
"reuseDataTab",
"prefillNewQueryWithSelect",
"updateNotificationsEnabled",
"sidebarHideTableComments",
"sidebarAllowHorizontalScroll",
+95 -1
View File
@@ -1,5 +1,6 @@
import { resolveDefaultDatabase } from "@/lib/database/defaultDatabase";
import type { ConnectionConfig, QueryTab, TreeNode } from "@/types/database";
import { qualifiedTableName } from "@/lib/table/tableSelectSql";
import type { ConnectionConfig, DatabaseType, QueryTab, TreeNode } from "@/types/database";
export interface NewQueryTarget {
connectionId: string;
@@ -59,3 +60,96 @@ function targetFromContext(context: Pick<QueryTab | TreeNode, "connectionId" | "
shouldRefreshDefaultDatabase: !context.database,
};
}
export interface NewQueryTable {
connectionId: string;
database: string;
schema?: string;
catalog?: string;
tableName: string;
}
export interface ResolveNewQueryTableInput {
activeTab?: Pick<QueryTab, "mode" | "connectionId" | "database" | "schema" | "tableMeta" | "structureTableName" | "title"> | null;
selectedTreeNode?: Pick<TreeNode, "type" | "connectionId" | "database" | "schema" | "catalog" | "tableName" | "label"> | null;
preferredSource?: NewQueryContextSource;
}
export interface ResolveNewQueryInitialSqlInput extends ResolveNewQueryTableInput {
prefillEnabled: boolean;
targetConnectionId: string;
targetDatabase: string;
databaseType?: DatabaseType;
}
// Database types whose "table" view does not use standard SQL `SELECT * FROM <table>`
// (e.g. Neo4j uses Cypher). The new-query prefill is skipped for these.
const NEW_QUERY_PREFILL_DISABLED_TYPES: ReadonlySet<DatabaseType | undefined> = new Set<DatabaseType | undefined>(["neo4j"]);
export function isNewQueryPrefillSupported(databaseType: DatabaseType | undefined): boolean {
return !NEW_QUERY_PREFILL_DISABLED_TYPES.has(databaseType);
}
function tableFromTab(tab: ResolveNewQueryTableInput["activeTab"]): NewQueryTable | null {
if (!tab?.connectionId) return null;
if (tab.mode === "data") {
// Require the loaded tableMeta: a data tab's title is schema/catalog-qualified
// (e.g. "public.users"), so using it as a bare table name while tableMeta is
// still loading or errored would yield an invalid double-qualified reference.
const meta = tab.tableMeta;
const tableName = meta?.tableName?.trim();
if (!tableName) return null;
return { connectionId: tab.connectionId, database: tab.database, schema: meta?.schema ?? tab.schema, catalog: meta?.catalog, tableName };
}
if (tab.mode === "structure") {
const tableName = (tab.structureTableName || "").trim();
if (!tableName) return null;
return { connectionId: tab.connectionId, database: tab.database, schema: tab.schema, tableName };
}
return null;
}
function tableFromNode(node: ResolveNewQueryTableInput["selectedTreeNode"]): NewQueryTable | null {
if (!node?.connectionId) return null;
if (node.type !== "table" && node.type !== "view" && node.type !== "materialized_view") return null;
const tableName = (node.tableName || node.label || "").trim();
if (!tableName) return null;
return { connectionId: node.connectionId, database: node.database || "", schema: node.schema, catalog: node.catalog, tableName };
}
/**
* Resolves the "focused table" for a new query, mirroring the primary/secondary
* selection of {@link resolveNewQueryTarget}: when `preferredSource` is `"sidebar"`
* the selected tree node wins, otherwise the active tab wins; the other is the
* fallback. Returns null when no table context is available.
*/
export function resolveNewQueryTable(input: ResolveNewQueryTableInput): NewQueryTable | null {
const tabFirst = input.preferredSource !== "sidebar";
const primary = tabFirst ? tableFromTab(input.activeTab) : tableFromNode(input.selectedTreeNode);
if (primary) return primary;
return tabFirst ? tableFromNode(input.selectedTreeNode) : tableFromTab(input.activeTab);
}
/**
* Builds a `SELECT * FROM <table>` statement for the new-query prefill, reusing
* the same per-dialect identifier quoting and schema/catalog qualification used
* by the table-data view.
*/
export function buildSelectAllSql(databaseType: DatabaseType | undefined, table: Pick<NewQueryTable, "schema" | "catalog" | "tableName">): string {
const ref = qualifiedTableName({ databaseType, schema: table.schema, catalog: table.catalog, tableName: table.tableName });
return `SELECT * FROM ${ref}`;
}
/**
* Resolves the optional initial SQL for a new query tab. A table from another
* connection or database is intentionally ignored because it cannot safely run
* in the execution context selected for the new tab.
*/
export function resolveNewQueryInitialSql(input: ResolveNewQueryInitialSqlInput): string | undefined {
if (!input.prefillEnabled || !isNewQueryPrefillSupported(input.databaseType)) return undefined;
const table = resolveNewQueryTable(input);
if (!table || table.connectionId !== input.targetConnectionId || table.database !== input.targetDatabase) return undefined;
return buildSelectAllSql(input.databaseType, table);
}