Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: data explore mode (#21207)

ecmadao38ade279e081
diff --git a/frontend/src/app/router/routes.test.tsx b/frontend/src/app/router/routes.test.tsx
index 52e4b37f37..183232c18d 100644
--- a/frontend/src/app/router/routes.test.tsx
+++ b/frontend/src/app/router/routes.test.tsx
@@ -5,6 +5,7 @@ import {
WORKSPACE_ROUTE_404,
} from "@/app/router/handles";
import { routes } from "./routes";
+import { sqlEditorRoutes } from "./routes/sqlEditor";
// Guardrail for the "blank body" route bug class. During the Vue→React router
// migration, several leaf routes were ported as bare `{ path, handle }` objects
@@ -85,6 +86,15 @@ describe("workspace root", () => {
});
describe("react route table reachability", () => {
+ it("marks SQL Editor layout leaves with an explicit null element", () => {
+ const children = sqlEditorRoutes[0].children ?? [];
+
+ expect(children.length).toBeGreaterThan(0);
+ for (const route of children) {
+ expect(route).toHaveProperty("element", null);
+ }
+ });
+
it("every leaf route renders something or redirects (no blank-body bare leaves)", () => {
expect(collectBareLeaves(routes)).toEqual([]);
});
diff --git a/frontend/src/app/router/routes/sqlEditor.tsx b/frontend/src/app/router/routes/sqlEditor.tsx
index aec8aa3cde..ce4f90a6ea 100644
--- a/frontend/src/app/router/routes/sqlEditor.tsx
+++ b/frontend/src/app/router/routes/sqlEditor.tsx
@@ -13,9 +13,10 @@ import type { Permission } from "@/types";
// `SQLEditorLayout` is a "layout as a page": the React component inspects the
// current route itself and decides what to render. It does NOT render an
// `<Outlet/>`, so we wrap it in a small layout-route component that renders
-// the layout alongside an `<Outlet/>`. The child routes carry no element of
-// their own — they exist only so navigation by route name resolves to a path,
-// matching the original vue `NoopRouteComponent` children.
+// the layout alongside an `<Outlet/>`. The child routes use an explicit null
+// element — they exist only so navigation by route name resolves to a path,
+// matching the original vue `NoopRouteComponent` children. Explicit null also
+// prevents React Router from warning that the matched leaf has no element.
const SQLEditorLayout = lazy(() =>
import("@/modules/sql-editor/components/SQLEditorLayout").then((m) => ({
default: m.SQLEditorLayout,
@@ -53,26 +54,32 @@ export const sqlEditorRoutes: RouteObject[] = [
children: [
{
index: true,
+ element: null,
handle: { name: SQL_EDITOR_HOME_MODULE },
},
{
path: "projects/:project",
+ element: null,
handle: { name: SQL_EDITOR_PROJECT_MODULE },
},
{
path: "projects/:project/instances/:instance/databases/:database",
+ element: null,
handle: { name: SQL_EDITOR_DATABASE_MODULE },
},
{
path: "projects/:project/instances/:instance",
+ element: null,
handle: { name: SQL_EDITOR_INSTANCE_MODULE },
},
{
path: "projects/:project/savedQueries/:savedQuery",
+ element: null,
handle: { name: SQL_EDITOR_SAVED_QUERY_MODULE },
},
{
path: "projects/:project/queryHistories/:queryHistory",
+ element: null,
handle: { name: SQL_EDITOR_QUERY_HISTORY_MODULE },
},
],
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index aedc5e6261..730f46d07f 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -437,6 +437,7 @@
"search": "Search",
"search-for-more": "Search for more",
"search-no-result": "No matching result found",
+ "search-results": "Search results",
"select": "Please Select",
"select-all": "Select all",
"selected": "selected",
@@ -3002,6 +3003,10 @@
"copy-selected-rows-as-csv": "Copy selected rows as CSV",
"copy-selected-rows-as-sql": "Copy selected rows as SQL",
"copy-url": "Copy URL",
+ "data-explorer-elasticsearch-filter-placeholder": "Enter a query expression, e.g. status:active",
+ "data-explorer-filter-placeholder": "Enter a query predicate, e.g. WHERE c.id = \"1\"",
+ "data-explorer-mongodb-filter-placeholder": "Enter a filter document, e.g. { \"status\": \"active\" }",
+ "data-explorer-sql-filter-placeholder": "Enter a query predicate, e.g. WHERE id = 1",
"ddl-dml-requires-data-change-plan": "To execute DDL/DML statements in <environment></environment>, please submit a Data Change Plan for approval.",
"download-as-file": "Download as {{file}}",
"duration-day": "{{days}} day",
@@ -3013,6 +3018,7 @@
"expire-at": "Expire at {{time}}",
"expire-in": "Expire in {{time}}",
"expired": "Expired",
+ "explore-data": "Explore data",
"export-available-via-issue": "Export available via issue \"{{title}}\"",
"export-available-via-n-grants": "Export available via {{count}} access grants:",
"export-enabled-by-grant": "Export enabled by access grant",
@@ -3046,7 +3052,6 @@
"open-in-new-tab": "Open in new tab",
"opened-from-link": "Opened from link",
"pending-query": "Pending query",
- "preview-table-data": "Preview table data",
"previous-row": "Previous Row",
"query-context": {
"admin-data-source-is-disallowed-to-query": "Admin data source is disallowed to query."
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 0516eaf844..c3d2a7a245 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -437,6 +437,7 @@
"search": "Buscar",
"search-for-more": "Buscar más",
"search-no-result": "No se encontraron resultados coincidentes",
+ "search-results": "Buscar resultados",
"select": "Seleccionar",
"select-all": "Seleccionar todo",
"selected": "seleccionado",
@@ -3002,6 +3003,10 @@
"copy-selected-rows-as-csv": "Copiar las filas seleccionadas como CSV",
"copy-selected-rows-as-sql": "Copiar las filas seleccionadas como SQL",
"copy-url": "Copiar URL",
+ "data-explorer-elasticsearch-filter-placeholder": "Introduce una expresión de consulta, p. ej. status:active",
+ "data-explorer-filter-placeholder": "Introduce un predicado de consulta, p. ej. WHERE c.id = \"1\"",
+ "data-explorer-mongodb-filter-placeholder": "Introduce un documento de filtro, p. ej. { \"status\": \"active\" }",
+ "data-explorer-sql-filter-placeholder": "Introduce un predicado de consulta, p. ej. WHERE id = 1",
"ddl-dml-requires-data-change-plan": "Para ejecutar sentencias DDL/DML en <environment></environment>, envíe un Plan de Cambio de Datos para su aprobación.",
"download-as-file": "Descargar como {{file}}",
"duration-day": "{{days}} día",
@@ -3013,6 +3018,7 @@
"expire-at": "Expira el {{time}}",
"expire-in": "Expira en {{time}}",
"expired": "Expirado",
+ "explore-data": "Explorar datos",
"export-available-via-issue": "Exportación disponible vía issue \"{{title}}\"",
"export-available-via-n-grants": "Exportación disponible vía {{count}} concesiones de acceso:",
"export-enabled-by-grant": "Exportación habilitada por la concesión de acceso",
@@ -3046,7 +3052,6 @@
"open-in-new-tab": "Abrir en nueva pestaña",
"opened-from-link": "Abierto desde enlace",
"pending-query": "Consulta pendiente",
- "preview-table-data": "Vista previa de datos de la tabla",
"previous-row": "Fila anterior",
"query-context": {
"admin-data-source-is-disallowed-to-query": "No se permite realizar consultas a la fuente de datos del administrador."
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 2ea98a25ce..96cd516dea 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -437,6 +437,7 @@
"search": "検索",
"search-for-more": "さらに検索",
"search-no-result": "一致する結果が見つかりません",
+ "search-results": "結果を検索",
"select": "選択してください",
"select-all": "すべて選択",
"selected": "選択済み",
@@ -3002,6 +3003,10 @@
"copy-selected-rows-as-csv": "選択した行を CSV としてコピー",
"copy-selected-rows-as-sql": "選択した行を SQL としてコピー",
"copy-url": "URLをコピー",
+ "data-explorer-elasticsearch-filter-placeholder": "クエリ式を入力(例: status:active)",
+ "data-explorer-filter-placeholder": "クエリ条件を入力(例: WHERE c.id = \"1\")",
+ "data-explorer-mongodb-filter-placeholder": "フィルタードキュメントを入力(例: { \"status\": \"active\" })",
+ "data-explorer-sql-filter-placeholder": "クエリ条件を入力(例: WHERE id = 1)",
"ddl-dml-requires-data-change-plan": "<environment></environment> で DDL/DML ステートメントを実行するには、承認のためデータ変更プランを送信してください。",
"download-as-file": "{{file}} 形式でダウンロード",
"duration-day": "{{days}} 日",
@@ -3013,6 +3018,7 @@
"expire-at": "{{time}} に期限切れ",
"expire-in": "{{time}} 後に期限切れ",
"expired": "期限切れ",
+ "explore-data": "データを探索",
"export-available-via-issue": "Issue「{{title}}」によりエクスポート可能",
"export-available-via-n-grants": "{{count}} 件のアクセス付与によりエクスポート可能:",
"export-enabled-by-grant": "アクセス付与により有効になっています",
@@ -3046,7 +3052,6 @@
"open-in-new-tab": "新しいタブで開く",
"opened-from-link": "リンクから開く",
"pending-query": "保留中のクエリ",
- "preview-table-data": "テーブルデータのプレビュー",
"previous-row": "前の行",
"query-context": {
"admin-data-source-is-disallowed-to-query": "管理者データ ソースはクエリできません。"
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index abb0682945..6f2110a382 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -437,6 +437,7 @@
"search": "Tìm kiếm",
"search-for-more": "Tìm kiếm thêm",
"search-no-result": "Không tìm thấy kết quả phù hợp",
+ "search-results": "Tìm kiếm kết quả",
"select": "Vui lòng chọn",
"select-all": "Chọn tất cả",
"selected": "đã chọn",
@@ -3002,6 +3003,10 @@
"copy-selected-rows-as-csv": "Sao chép các hàng đã chọn dưới dạng CSV",
"copy-selected-rows-as-sql": "Sao chép các hàng đã chọn dưới dạng SQL",
"copy-url": "Sao chép URL",
+ "data-explorer-elasticsearch-filter-placeholder": "Nhập biểu thức truy vấn, ví dụ status:active",
+ "data-explorer-filter-placeholder": "Nhập điều kiện truy vấn, ví dụ WHERE c.id = \"1\"",
+ "data-explorer-mongodb-filter-placeholder": "Nhập tài liệu bộ lọc, ví dụ { \"status\": \"active\" }",
+ "data-explorer-sql-filter-placeholder": "Nhập điều kiện truy vấn, ví dụ WHERE id = 1",
"ddl-dml-requires-data-change-plan": "Để thực thi câu lệnh DDL/DML trong <environment></environment>, vui lòng gửi Kế hoạch Thay đổi Dữ liệu để được phê duyệt.",
"download-as-file": "Tải xuống dưới dạng {{file}}",
"duration-day": "{{days}} ngày",
@@ -3013,6 +3018,7 @@
"expire-at": "Hết hạn lúc {{time}}",
"expire-in": "Hết hạn sau {{time}}",
"expired": "Đã hết hạn",
+ "explore-data": "Khám phá dữ liệu",
"export-available-via-issue": "Xuất khả dụng qua issue \"{{title}}\"",
"export-available-via-n-grants": "Xuất khả dụng qua {{count}} cấp quyền truy cập:",
"export-enabled-by-grant": "Xuất được kích hoạt bởi cấp quyền truy cập",
@@ -3046,7 +3052,6 @@
"open-in-new-tab": "Mở trong tab mới",
"opened-from-link": "Mở từ liên kết",
"pending-query": "Đang chờ truy vấn",
- "preview-table-data": "Xem trước dữ liệu bảng",
"previous-row": "Dòng trước",
"query-context": {
"admin-data-source-is-disallowed-to-query": "Nguồn dữ liệu quản trị không được phép truy vấn."
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 566c9d2479..02f82a6b1e 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -437,6 +437,7 @@
"search": "搜索",
"search-for-more": "搜索更多",
"search-no-result": "未找到匹配的结果",
+ "search-results": "搜索结果",
"select": "请选择",
"select-all": "全选",
"selected": "已选择",
@@ -3002,6 +3003,10 @@
"copy-selected-rows-as-csv": "将选定行复制为 CSV",
"copy-selected-rows-as-sql": "将选定行复制为 SQL",
"copy-url": "复制 URL",
+ "data-explorer-elasticsearch-filter-placeholder": "输入查询表达式,例如 status:active",
+ "data-explorer-filter-placeholder": "输入查询条件,例如 WHERE c.id = \"1\"",
+ "data-explorer-mongodb-filter-placeholder": "输入筛选文档,例如 { \"status\": \"active\" }",
+ "data-explorer-sql-filter-placeholder": "输入查询条件,例如 WHERE id = 1",
"ddl-dml-requires-data-change-plan": "如需在 <environment></environment> 中执行 DDL/DML 语句,请创建变更计划以获得审批。",
"download-as-file": "下载为 {{file}} 格式",
"duration-day": "{{days}} 天",
@@ -3013,6 +3018,7 @@
"expire-at": "{{time}} 过期",
"expire-in": "{{time}} 后过期",
"expired": "已过期",
+ "explore-data": "浏览数据",
"export-available-via-issue": "通过工单 \"{{title}}\" 可导出",
"export-available-via-n-grants": "通过 {{count}} 个访问授权可导出:",
"export-enabled-by-grant": "由访问授权启用导出",
@@ -3046,7 +3052,6 @@
"open-in-new-tab": "在新选项卡中打开",
"opened-from-link": "从链接打开",
"pending-query": "待处理查询",
- "preview-table-data": "预览表数据",
"previous-row": "上一行",
"query-context": {
"admin-data-source-is-disallowed-to-query": "禁止查询主数据源。"
diff --git a/frontend/src/modules/sql-editor/components/ConnectionPane/actions.test.tsx b/frontend/src/modules/sql-editor/components/ConnectionPane/actions.test.tsx
index 7b34da2b2e..180726a6ae 100644
--- a/frontend/src/modules/sql-editor/components/ConnectionPane/actions.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ConnectionPane/actions.test.tsx
@@ -16,6 +16,8 @@ const mocks = vi.hoisted(() => ({
maybeUpdateSavedQuery: vi.fn().mockResolvedValue(undefined),
canCreateSavedQueryInProject: vi.fn(() => true),
addTab: vi.fn(() => ({ id: "local-tab" })),
+ tabsById: new Map<string, { id: string; mode: string }>(),
+ currentTabId: "",
}));
vi.mock("react-i18next", () => ({
@@ -68,8 +70,8 @@ vi.mock("@/modules/sql-editor/model/events", () => ({
vi.mock("@/modules/sql-editor/store/tab", () => ({
getSQLEditorTabsState: () => ({
- tabsById: new Map(),
- currentTabId: "",
+ tabsById: mocks.tabsById,
+ currentTabId: mocks.currentTabId,
addTab: mocks.addTab,
updateTab: vi.fn(),
}),
@@ -168,6 +170,8 @@ beforeEach(async () => {
mocks.canCreateSavedQueryInProject.mockReturnValue(true);
mocks.addTab.mockReturnValue({ id: "local-tab" });
mocks.createSavedQuery.mockResolvedValue(undefined);
+ mocks.tabsById.clear();
+ mocks.currentTabId = "";
({ useConnectionMenu } = await import("./actions"));
});
@@ -205,6 +209,27 @@ describe("setConnection", () => {
expect(mocks.createSavedQuery).toHaveBeenCalled();
expect(mocks.addTab).not.toHaveBeenCalled();
});
+
+ test("does not replace a data explorer tab", async () => {
+ mocks.currentTabId = "data-explorer";
+ mocks.tabsById.set("data-explorer", {
+ id: "data-explorer",
+ mode: "DATA_EXPLORER",
+ });
+ const { setConnection } = await import("./actions");
+
+ await act(async () => {
+ setConnection({
+ database: { name: "instances/prod/databases/db1" } as never,
+ mode: "DATA_EXPLORER",
+ newTab: false,
+ });
+ await Promise.resolve();
+ });
+
+ expect(mocks.maybeUpdateSavedQuery).not.toHaveBeenCalled();
+ expect(mocks.createSavedQuery).toHaveBeenCalled();
+ });
});
describe("useConnectionMenu", () => {
diff --git a/frontend/src/modules/sql-editor/components/ConnectionPane/actions.tsx b/frontend/src/modules/sql-editor/components/ConnectionPane/actions.tsx
index 73f50072e6..ec285f4d44 100644
--- a/frontend/src/modules/sql-editor/components/ConnectionPane/actions.tsx
+++ b/frontend/src/modules/sql-editor/components/ConnectionPane/actions.tsx
@@ -72,6 +72,8 @@ export function setConnection(options: {
const tabsState = getSQLEditorTabsState();
const currentTab = tabsState.tabsById.get(tabsState.currentTabId);
+ const nextMode = mode === "DATA_EXPLORER" ? DEFAULT_TAB_MODE : mode;
+ const shouldCreateNewTab = newTab || currentTab?.mode === "DATA_EXPLORER";
const { maybeUpdateSavedQuery, createSavedQuery } =
useSQLEditorStore.getState();
@@ -82,7 +84,7 @@ export function setConnection(options: {
);
const createOrUpdate = () => {
- if (!newTab && currentTab) {
+ if (!shouldCreateNewTab && currentTab) {
return maybeUpdateSavedQuery({
tabId: currentTab.id,
savedQuery: currentTab.savedQuery,
@@ -103,7 +105,10 @@ export function setConnection(options: {
void createOrUpdate().then((tab) => {
if (tab) {
- getSQLEditorTabsState().updateTab(tab.id, { mode, batchQueryContext });
+ getSQLEditorTabsState().updateTab(tab.id, {
+ mode: nextMode,
+ batchQueryContext,
+ });
useSQLEditorStore.getState().setAsidePanelTab("SCHEMA");
}
});
diff --git a/frontend/src/modules/sql-editor/components/DataExplorer/DataExplorerPanel.test.tsx b/frontend/src/modules/sql-editor/components/DataExplorer/DataExplorerPanel.test.tsx
new file mode 100644
index 0000000000..fc7d2b1837
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/DataExplorer/DataExplorerPanel.test.tsx
@@ -0,0 +1,176 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import { DataExplorerPanel } from "./DataExplorerPanel";
+
+const mocks = vi.hoisted(() => {
+ const tab = {
+ id: "explorer",
+ mode: "DATA_EXPLORER",
+ connection: {
+ instance: "instances/i",
+ database: "instances/i/databases/db",
+ schema: "",
+ table: "users",
+ },
+ editorState: { selection: null },
+ dataExplorer: { filter: "", initialized: false },
+ databaseQueryContexts: new Map(),
+ };
+ return {
+ tab,
+ engine: 23 as Engine,
+ resultRowsLimit: 500,
+ execute: vi.fn().mockResolvedValue(undefined),
+ updateTab: vi.fn((_: string, patch: Record<string, unknown>) => {
+ Object.assign(tab, patch);
+ return tab;
+ }),
+ deleteDatabaseQueryContext: vi.fn(),
+ };
+});
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => undefined },
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/hooks/useExecuteSQL", () => ({
+ useExecuteSQL: () => ({ execute: mocks.execute }),
+}));
+
+vi.mock("@/modules/sql-editor/hooks/useSQLEditorState", () => ({
+ useConnectionOfCurrentSQLEditorTab: () => ({
+ connection: mocks.tab.connection,
+ database: { name: mocks.tab.connection.database },
+ instance: { engine: mocks.engine },
+ }),
+}));
+
+vi.mock("@/modules/sql-editor/store/editor", () => ({
+ useSQLEditorEditorState: (selector: (value: unknown) => unknown) =>
+ selector({ resultRowsLimit: mocks.resultRowsLimit }),
+}));
+
+vi.mock("@/modules/sql-editor/store/tab", () => {
+ const state = {
+ currentTabId: "explorer",
+ tabsById: new Map([["explorer", mocks.tab]]),
+ };
+ return {
+ useSQLEditorTabState: (selector: (value: typeof state) => unknown) =>
+ selector(state),
+ getSQLEditorTabsState: () => ({
+ ...state,
+ updateTab: mocks.updateTab,
+ deleteDatabaseQueryContext: mocks.deleteDatabaseQueryContext,
+ }),
+ };
+});
+
+vi.mock(
+ "@/modules/sql-editor/components/ResultPanel/DatabaseQueryContext",
+ () => ({ DatabaseQueryContext: () => null })
+);
+
+vi.mock("@/modules/sql-editor/components/QueryContextSettingPopover", () => ({
+ QueryContextSettingPopover: ({ disabled }: { disabled?: boolean }) => (
+ <div
+ data-testid="query-context-setting-popover"
+ data-disabled={String(disabled)}
+ />
+ ),
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.tab.dataExplorer = { filter: "", initialized: false };
+ mocks.tab.databaseQueryContexts = new Map();
+ mocks.tab.connection.schema = "";
+ mocks.tab.connection.table = "users";
+ mocks.engine = Engine.COSMOSDB;
+ mocks.resultRowsLimit = 500;
+});
+
+describe("DataExplorerPanel", () => {
+ test("runs the default CosmosDB query once on first open", async () => {
+ render(<DataExplorerPanel />);
+
+ await waitFor(() => {
+ expect(mocks.execute).toHaveBeenCalledWith({
+ connection: mocks.tab.connection,
+ statement: "SELECT * FROM c",
+ engine: Engine.COSMOSDB,
+ explain: false,
+ limit: 500,
+ selection: null,
+ });
+ });
+ expect(mocks.tab.dataExplorer.initialized).toBe(true);
+ });
+
+ test("joins the filter and runs it from the shared Run button", async () => {
+ mocks.tab.dataExplorer = { filter: "", initialized: true };
+ render(<DataExplorerPanel />);
+
+ fireEvent.change(
+ screen.getByLabelText("sql-editor.data-explorer-filter-placeholder"),
+ { target: { value: "WHERE c.active = true" } }
+ );
+ fireEvent.click(
+ screen.getByRole("button", { name: /\(limit\s*500\)/ })
+ );
+
+ await waitFor(() => {
+ expect(mocks.execute).toHaveBeenCalledWith(
+ expect.objectContaining({
+ statement: "SELECT * FROM c WHERE c.active = true",
+ limit: 500,
+ })
+ );
+ });
+ });
+
+ test("builds a qualified relational preview query", async () => {
+ mocks.engine = Engine.POSTGRES;
+ mocks.tab.connection.schema = "public";
+ mocks.tab.connection.table = "users";
+
+ render(<DataExplorerPanel />);
+
+ await waitFor(() => {
+ expect(mocks.execute).toHaveBeenCalledWith(
+ expect.objectContaining({
+ statement: 'SELECT * FROM "public"."users";',
+ engine: Engine.POSTGRES,
+ limit: 500,
+ })
+ );
+ });
+ expect(
+ screen.getByLabelText(
+ "sql-editor.data-explorer-sql-filter-placeholder"
+ )
+ ).toBeInTheDocument();
+ });
+
+ test("disables the filter controls while the query is running", () => {
+ mocks.tab.dataExplorer = { filter: "", initialized: true };
+ mocks.tab.databaseQueryContexts = new Map([
+ [mocks.tab.connection.database, [{ status: "EXECUTING" }]],
+ ]);
+
+ render(<DataExplorerPanel />);
+
+ expect(
+ screen.getByLabelText("sql-editor.data-explorer-filter-placeholder")
+ ).toBeDisabled();
+ expect(
+ screen.getByRole("button", { name: /\(limit\s*500\)/ })
+ ).toBeDisabled();
+ expect(screen.getByTestId("query-context-setting-popover")).toHaveAttribute(
+ "data-disabled",
+ "true"
+ );
+ });
+});
diff --git a/frontend/src/modules/sql-editor/components/DataExplorer/DataExplorerPanel.tsx b/frontend/src/modules/sql-editor/components/DataExplorer/DataExplorerPanel.tsx
new file mode 100644
index 0000000000..216cde8eec
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/DataExplorer/DataExplorerPanel.tsx
@@ -0,0 +1,170 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Input } from "@/components/ui/input";
+import { useExecuteSQL } from "@/hooks/useExecuteSQL";
+import { DatabaseQueryContext } from "@/modules/sql-editor/components/ResultPanel/DatabaseQueryContext";
+import { RunQueryButton } from "@/modules/sql-editor/components/RunQueryButton";
+import { useConnectionOfCurrentSQLEditorTab } from "@/modules/sql-editor/hooks/useSQLEditorState";
+import { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";
+import {
+ getSQLEditorTabsState,
+ useSQLEditorTabState,
+} from "@/modules/sql-editor/store/tab";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import { getDataExplorerQueryPrefix, getDataExplorerStatement } from "./query";
+
+export function DataExplorerPanel() {
+ const { t } = useTranslation();
+ const { connection, database, instance } =
+ useConnectionOfCurrentSQLEditorTab();
+ const { execute } = useExecuteSQL();
+ const resultRowsLimit = useSQLEditorEditorState((s) => s.resultRowsLimit);
+ const tab = useSQLEditorTabState((state) =>
+ state.tabsById.get(state.currentTabId)
+ );
+ const context = useSQLEditorTabState(
+ (state) =>
+ state.tabsById
+ .get(state.currentTabId)
+ ?.databaseQueryContexts?.get(database.name)?.[0]
+ );
+ const [filter, setFilter] = useState(tab?.dataExplorer?.filter ?? "");
+ const initializedRef = useRef(false);
+ const queryTarget = useMemo(
+ () => ({
+ engine: instance.engine,
+ schema: connection.schema ?? "",
+ table: connection.table ?? "",
+ }),
+ [connection.schema, connection.table, instance.engine]
+ );
+ const prefix = getDataExplorerQueryPrefix(queryTarget);
+ const filterPlaceholder = (() => {
+ switch (instance.engine) {
+ case Engine.COSMOSDB:
+ return t("sql-editor.data-explorer-filter-placeholder");
+ case Engine.MONGODB:
+ return t("sql-editor.data-explorer-mongodb-filter-placeholder");
+ case Engine.ELASTICSEARCH:
+ return t("sql-editor.data-explorer-elasticsearch-filter-placeholder");
+ default:
+ return t("sql-editor.data-explorer-sql-filter-placeholder");
+ }
+ })();
+ const isExecuting = context?.status === "EXECUTING";
+
+ const updateExplorerState = useCallback(
+ (patch: { filter?: string; initialized?: boolean; resetRow?: boolean }) => {
+ if (!tab?.dataExplorer) return;
+ getSQLEditorTabsState().updateTab(tab.id, {
+ dataExplorer: {
+ ...tab.dataExplorer,
+ ...(patch.filter !== undefined ? { filter: patch.filter } : {}),
+ ...(patch.initialized !== undefined
+ ? { initialized: patch.initialized }
+ : {}),
+ ...(patch.resetRow ? { selectedRowKey: undefined } : {}),
+ },
+ });
+ },
+ [tab]
+ );
+
+ const run = useCallback(
+ async (suffix: string) => {
+ const statement = getDataExplorerStatement(
+ queryTarget,
+ suffix,
+ resultRowsLimit
+ );
+ if (!tab || !statement) return;
+
+ const tabsState = getSQLEditorTabsState();
+ for (const existing of tab.databaseQueryContexts?.get(database.name) ??
+ []) {
+ existing.abortController?.abort();
+ }
+ tabsState.deleteDatabaseQueryContext(database.name);
+ updateExplorerState({
+ filter: suffix,
+ initialized: true,
+ resetRow: true,
+ });
+ await execute({
+ connection,
+ statement,
+ engine: instance.engine,
+ explain: false,
+ limit: resultRowsLimit,
+ selection: tab.editorState.selection,
+ });
+ },
+ [
+ connection,
+ database.name,
+ execute,
+ instance.engine,
+ queryTarget,
+ resultRowsLimit,
+ tab,
+ updateExplorerState,
+ ]
+ );
+
+ useEffect(() => {
+ if (!tab?.dataExplorer || tab.dataExplorer.initialized) return;
+ if (!prefix) return;
+ if (initializedRef.current) return;
+ initializedRef.current = true;
+ void run(tab.dataExplorer.filter);
+ }, [prefix, run, tab]);
+
+ const handleFilterChange = (value: string) => {
+ setFilter(value);
+ updateExplorerState({ filter: value });
+ };
+
+ if (!tab || !prefix) return null;
+
+ return (
+ <div className="h-full min-h-0 flex flex-col bg-background">
+ <form
+ className="shrink-0 flex items-center gap-x-2 border-b border-block-border p-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ if (isExecuting) return;
+ void run(filter);
+ }}
+ >
+ <code className="shrink-0 whitespace-nowrap text-sm text-main">
+ {prefix}
+ </code>
+ <Input
+ size="md"
+ className="min-w-0 flex-1"
+ autoComplete="off"
+ value={filter}
+ disabled={isExecuting}
+ aria-label={filterPlaceholder}
+ placeholder={filterPlaceholder}
+ onChange={(event) => handleFilterChange(event.target.value)}
+ />
+ <RunQueryButton
+ type="submit"
+ size="md"
+ disabled={isExecuting}
+ settingsDisabled={isExecuting}
+ />
+ </form>
+ <div className="flex-1 min-h-0 overflow-hidden">
+ {context && (
+ <DatabaseQueryContext
+ database={database}
+ context={context}
+ presentation="DATA_EXPLORER"
+ />
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/modules/sql-editor/components/DataExplorer/query.test.ts b/frontend/src/modules/sql-editor/components/DataExplorer/query.test.ts
new file mode 100644
index 0000000000..d37e31bc4a
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/DataExplorer/query.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, test } from "vitest";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import {
+ type DataExplorerQueryTarget,
+ getDataExplorerQueryPrefix,
+ getDataExplorerStatement,
+} from "./query";
+
+const target = (
+ engine: Engine,
+ schema = "public",
+ table = "users"
+): DataExplorerQueryTarget => ({ engine, schema, table });
+
+describe("data explorer query", () => {
+ test("builds a CosmosDB query with an optional predicate", () => {
+ const cosmos = target(Engine.COSMOSDB, "", "users");
+ expect(getDataExplorerQueryPrefix(cosmos)).toBe("SELECT * FROM c");
+ expect(getDataExplorerStatement(cosmos, "", 500)).toBe("SELECT * FROM c");
+ expect(getDataExplorerStatement(cosmos, " WHERE c.id = '1'; ", 500)).toBe(
+ "SELECT * FROM c WHERE c.id = '1'"
+ );
+ });
+
+ test("quotes relational targets and leaves row limiting to the request", () => {
+ const postgres = target(Engine.POSTGRES);
+ expect(getDataExplorerQueryPrefix(postgres)).toBe(
+ 'SELECT * FROM "public"."users"'
+ );
+ expect(getDataExplorerStatement(postgres, "WHERE active = true", 500)).toBe(
+ 'SELECT * FROM "public"."users" WHERE active = true;'
+ );
+
+ const mssql = target(Engine.MSSQL, "dbo");
+ expect(getDataExplorerStatement(mssql, "WHERE active = 1", 500)).toBe(
+ "SELECT * FROM [dbo].[users] WHERE active = 1;"
+ );
+
+ const oracle = target(Engine.ORACLE, "APP");
+ expect(getDataExplorerStatement(oracle, "WHERE active = 1", 500)).toBe(
+ 'SELECT * FROM "APP"."users" WHERE active = 1;'
+ );
+ });
+
+ test("builds MongoDB and Elasticsearch queries from their filter syntax", () => {
+ const mongodb = target(Engine.MONGODB, "", 'user"events');
+ expect(getDataExplorerQueryPrefix(mongodb)).toBe(
+ 'db["user\\"events"].find('
+ );
+ expect(getDataExplorerStatement(mongodb, '{ "active": true }', 500)).toBe(
+ 'db["user\\"events"].find({ "active": true });'
+ );
+
+ const elasticsearch = target(Engine.ELASTICSEARCH, "", "events");
+ expect(getDataExplorerStatement(elasticsearch, "", 500)).toBe(
+ "GET events/_search?q=*&size=500"
+ );
+ expect(getDataExplorerStatement(elasticsearch, "status:active", 500)).toBe(
+ "GET events/_search?q=status:active&size=500"
+ );
+ });
+
+ test("rejects engines without table previews", () => {
+ expect(getDataExplorerQueryPrefix(target(Engine.REDIS))).toBeUndefined();
+ expect(
+ getDataExplorerStatement(target(Engine.ENGINE_UNSPECIFIED), "", 500)
+ ).toBeUndefined();
+ });
+});
diff --git a/frontend/src/modules/sql-editor/components/DataExplorer/query.ts b/frontend/src/modules/sql-editor/components/DataExplorer/query.ts
new file mode 100644
index 0000000000..50f5ff1abf
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/DataExplorer/query.ts
@@ -0,0 +1,53 @@
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import {
+ escapeMongoDBCollectionName,
+ generateSchemaAndTableNameInSQL,
+} from "@/utils/v1/sql";
+
+export interface DataExplorerQueryTarget {
+ engine: Engine;
+ schema: string;
+ table: string;
+}
+
+export const getDataExplorerQueryPrefix = ({
+ engine,
+ schema,
+ table,
+}: DataExplorerQueryTarget): string | undefined => {
+ if (!table && engine !== Engine.COSMOSDB) return undefined;
+ switch (engine) {
+ case Engine.ENGINE_UNSPECIFIED:
+ case Engine.REDIS:
+ return undefined;
+ case Engine.COSMOSDB:
+ return "SELECT * FROM c";
+ case Engine.MONGODB:
+ return `db["${escapeMongoDBCollectionName(table)}"].find(`;
+ case Engine.ELASTICSEARCH:
+ return `GET ${table}/_search?q=`;
+ default:
+ return `SELECT * FROM ${generateSchemaAndTableNameInSQL(engine, schema, table)}`;
+ }
+};
+
+export const getDataExplorerStatement = (
+ target: DataExplorerQueryTarget,
+ filter: string,
+ limit: number
+): string | undefined => {
+ const prefix = getDataExplorerQueryPrefix(target);
+ if (!prefix) return undefined;
+ const suffix = filter.trim().replace(/;$/, "");
+
+ switch (target.engine) {
+ case Engine.COSMOSDB:
+ return suffix ? `${prefix} ${suffix}` : prefix;
+ case Engine.MONGODB:
+ return `${prefix}${suffix});`;
+ case Engine.ELASTICSEARCH:
+ return `${prefix}${suffix || "*"}&size=${limit}`;
+ default:
+ return suffix ? `${prefix} ${suffix};` : `${prefix};`;
+ }
+};
diff --git a/frontend/src/modules/sql-editor/components/EditorAction.tsx b/frontend/src/modules/sql-editor/components/EditorAction.tsx
index 657838f6a4..958e82e93f 100644
--- a/frontend/src/modules/sql-editor/components/EditorAction.tsx
+++ b/frontend/src/modules/sql-editor/components/EditorAction.tsx
@@ -1,4 +1,4 @@
-import { ChevronLeft, Play, Save, Share2 } from "lucide-react";
+import { ChevronLeft, Save, Share2 } from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
@@ -9,7 +9,6 @@ import {
} from "@/components/ui/popover";
import { Tooltip } from "@/components/ui/tooltip";
import { useSavedQueryAndTab } from "@/hooks/useSavedQueryAndTab";
-import { cn } from "@/lib/utils";
import { useConnectionOfCurrentSQLEditorTab } from "@/modules/sql-editor/hooks/useSQLEditorState";
import { sqlEditorEvents } from "@/modules/sql-editor/model/events";
import { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";
@@ -32,6 +31,7 @@ import { ChooserGroup } from "./ChooserGroup";
import { ContainerChooser } from "./ContainerChooser";
import { OpenAIButton } from "./OpenAIButton";
import { QueryContextSettingPopover } from "./QueryContextSettingPopover";
+import { RunQueryButton } from "./RunQueryButton";
import { SharePopoverBody } from "./SharePopoverBody";
type Props = {
@@ -74,7 +74,6 @@ export function EditorAction({ onExecute }: Props) {
(s) => s.tabsById.get(s.currentTabId)?.connection.table ?? ""
);
const isDisconnected = useIsDisconnected();
- const resultRowsLimit = useSQLEditorEditorState((s) => s.resultRowsLimit);
const project = useSQLEditorEditorState((s) => s.project);
const isAdminMode = tabMode === "ADMIN";
@@ -168,31 +167,21 @@ export function EditorAction({ onExecute }: Props) {
</Button>
)}
- {!isAdminMode && (
- <div className="inline-flex">
- {isCosmosDBWithoutContainer ? (
+ {!isAdminMode &&
+ (isCosmosDBWithoutContainer ? (
+ <div className="inline-flex">
<ContainerChooser variant="run" />
- ) : (
- <Tooltip content="" side="bottom">
- <Button
- variant="default"
- size="sm"
- className={cn("h-7 px-1.5 gap-1 rounded-r-none text-sm")}
- disabled={!allowQuery}
- onClick={handleRunQuery}
- >
- <Play className="size-4 fill-current" />
- <span className="inline-flex items-center">
- (limit&nbsp;{resultRowsLimit})
- </span>
- </Button>
- </Tooltip>
- )}
- <QueryContextSettingPopover
- disabled={!showQueryContextSettingPopover}
+ <QueryContextSettingPopover
+ disabled={!showQueryContextSettingPopover}
+ />
+ </div>
+ ) : (
+ <RunQueryButton
+ disabled={!allowQuery}
+ settingsDisabled={!showQueryContextSettingPopover}
+ onClick={handleRunQuery}
/>
- </div>
- )}
+ ))}
<AdminModeButton size="sm" hideText />
diff --git a/frontend/src/modules/sql-editor/components/Panels/Panels.tsx b/frontend/src/modules/sql-editor/components/Panels/Panels.tsx
index dcf9178656..e86c38feb3 100644
--- a/frontend/src/modules/sql-editor/components/Panels/Panels.tsx
+++ b/frontend/src/modules/sql-editor/components/Panels/Panels.tsx
@@ -14,6 +14,7 @@ import { AIChatToSQL, AIContextProvider } from "@/modules/ai/components";
import { aiContextEvents } from "@/modules/ai/logic";
import { resizeHandleClass } from "@/modules/schema-editor/resize";
import { DatabaseChooser } from "@/modules/sql-editor/components/DatabaseChooser";
+import { DataExplorerPanel } from "@/modules/sql-editor/components/DataExplorer/DataExplorerPanel";
import { DiagramPanel } from "@/modules/sql-editor/components/DiagramPanel";
import { ExternalTablesPanel } from "@/modules/sql-editor/components/ExternalTablesPanel";
import { FunctionsPanel } from "@/modules/sql-editor/components/FunctionsPanel";
@@ -99,6 +100,7 @@ export function Panels() {
const editorPanelSize = useSQLEditorStore(useShallow(selectEditorPanelSize));
const showAIPaneAlongsidePanel = showAIPanel && isShowingCode;
+ const effectiveView = tabMode === "DATA_EXPLORER" ? "CODE" : view;
const { setSchema, updateViewState } = useViewStateNav();
const { execute } = useExecuteSQL();
@@ -169,6 +171,9 @@ export function Panels() {
if (tabMode === "ADMIN") {
return <TerminalPanel key={`terminal-${tab.id}`} />;
}
+ if (tabMode === "DATA_EXPLORER") {
+ return <DataExplorerPanel key={`data-explorer-${tab.id}`} />;
+ }
return (
<Alert variant="error" className="m-2" key={`no-permission-${tab.id}`}>
<ShieldAlert className="size-5 shrink-0 mt-0.5" />
@@ -177,7 +182,9 @@ export function Panels() {
);
}, [tab, tabMode, t]);
- const subPanel = view ? renderSubPanel(view, tab?.id) : null;
+ const subPanel = effectiveView
+ ? renderSubPanel(effectiveView, tab?.id)
+ : null;
const handleAiResize = (sizePct: number) => {
if (!Number.isFinite(sizePct)) return;
@@ -187,8 +194,8 @@ export function Panels() {
return (
<div className="flex-1 flex items-stretch overflow-hidden">
<div className="flex-1 overflow-y-hidden overflow-x-auto">
- {(!view || view === "CODE") && codePanel}
- {view && view !== "CODE" && (
+ {(!effectiveView || effectiveView === "CODE") && codePanel}
+ {effectiveView && effectiveView !== "CODE" && (
<div className="h-full flex flex-col">
<div className="py-2 px-2 w-full flex flex-row gap-x-2 justify-between items-center">
<div className="flex items-center justify-start gap-2">
diff --git a/frontend/src/modules/sql-editor/components/QueryContextSettingPopover.tsx b/frontend/src/modules/sql-editor/components/QueryContextSettingPopover.tsx
index d9de2ea7da..c9da96f610 100644
--- a/frontend/src/modules/sql-editor/components/QueryContextSettingPopover.tsx
+++ b/frontend/src/modules/sql-editor/components/QueryContextSettingPopover.tsx
@@ -35,13 +35,17 @@ import { getInstanceResource, readableDataSourceType } from "@/utils";
type Props = {
readonly disabled?: boolean;
+ readonly size?: "sm" | "md";
};
/**
* Replaces frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue.
* Popover for selecting query data source, Redis command mode, and max row count.
*/
-export function QueryContextSettingPopover({ disabled = false }: Props) {
+export function QueryContextSettingPopover({
+ disabled = false,
+ size = "sm",
+}: Props) {
const { t } = useTranslation();
const { database, connection: connectionRef } =
useConnectionOfCurrentSQLEditorTab();
@@ -119,9 +123,12 @@ export function QueryContextSettingPopover({ disabled = false }: Props) {
render={
<Button
variant="default"
- size="sm"
+ size={size}
disabled={disabled}
- className={cn("h-7 px-1 gap-0", "rounded-none rounded-r-xs")}
+ className={cn(
+ "px-1 gap-0 rounded-none rounded-r-xs",
+ size === "sm" && "h-7"
+ )}
/>
}
>
diff --git a/frontend/src/modules/sql-editor/components/ResultPanel/DatabaseQueryContext.tsx b/frontend/src/modules/sql-editor/components/ResultPanel/DatabaseQueryContext.tsx
index 547a411764..5fb4fb1251 100644
--- a/frontend/src/modules/sql-editor/components/ResultPanel/DatabaseQueryContext.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultPanel/DatabaseQueryContext.tsx
@@ -3,6 +3,7 @@ import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { useExecuteSQL } from "@/hooks/useExecuteSQL";
+import type { ResultViewPresentation } from "@/modules/sql-editor/components/ResultView";
import { ResultView } from "@/modules/sql-editor/components/ResultView";
import { getSQLEditorTabsState } from "@/modules/sql-editor/store/tab";
import type {
@@ -14,6 +15,7 @@ import type { Database } from "@/types/proto-es/v1/database_service_pb";
export interface DatabaseQueryContextProps {
database: Database;
context: SQLEditorDatabaseQueryContext;
+ presentation?: ResultViewPresentation;
}
/**
@@ -29,6 +31,7 @@ export interface DatabaseQueryContextProps {
export function DatabaseQueryContext({
database,
context,
+ presentation = "STANDARD",
}: DatabaseQueryContextProps) {
const { t } = useTranslation();
const { runQuery } = useExecuteSQL();
@@ -107,6 +110,7 @@ export function DatabaseQueryContext({
executeParams={context.params}
database={database}
resultSet={context.resultSet}
+ presentation={presentation}
/>
);
}
diff --git a/frontend/src/modules/sql-editor/components/ResultView/CopyAllButton.tsx b/frontend/src/modules/sql-editor/components/ResultView/CopyAllButton.tsx
new file mode 100644
index 0000000000..bafad27e25
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/ResultView/CopyAllButton.tsx
@@ -0,0 +1,64 @@
+import { ChevronDownIcon, CopyIcon } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { useSelectionContext } from "./context";
+import { formatAsCSV, formatAsSQL, formatAsText } from "./copy-formats";
+
+export function CopyAllButton() {
+ const { t } = useTranslation();
+ const { copy, canCopyAsInsert } = useSelectionContext();
+
+ return (
+ <div className="flex items-center">
+ <Button
+ size="sm"
+ appearance="outline"
+ className="h-7 px-2 rounded-r-none border-r-0 text-control border-control-border hover:bg-control-bg-hover"
+ onClick={() => copy("all", formatAsText)}
+ >
+ <CopyIcon className="size-4" />
+ {t("common.copy-all")}
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ openOnHover
+ delay={100}
+ render={
+ <Button
+ size="sm"
+ appearance="outline"
+ aria-label={t("common.copy")}
+ className="h-7 w-6 px-0 rounded-l-none text-control border-control-border hover:bg-control-bg-hover"
+ >
+ <ChevronDownIcon className="size-4" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end" className="min-w-0">
+ <DropdownMenuItem
+ onClick={() => copy("all", formatAsCSV)}
+ className="px-2 py-1 text-xs gap-x-1.5"
+ >
+ <CopyIcon className="size-3" />
+ {t("sql-editor.copy-all-rows-as-csv")}
+ </DropdownMenuItem>
+ {canCopyAsInsert && (
+ <DropdownMenuItem
+ onClick={() => copy("all", formatAsSQL)}
+ className="px-2 py-1 text-xs gap-x-1.5"
+ >
+ <CopyIcon className="size-3" />
+ {t("sql-editor.copy-all-rows-as-sql")}
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ );
+}
diff --git a/frontend/src/modules/sql-editor/components/ResultView/DataExplorerResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/DataExplorerResultView.test.tsx
new file mode 100644
index 0000000000..3e83520274
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/ResultView/DataExplorerResultView.test.tsx
@@ -0,0 +1,285 @@
+import { create } from "@bufbuild/protobuf";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import {
+ QueryResultSchema,
+ QueryRowSchema,
+ RowValueSchema,
+} from "@/types/proto-es/v1/sql_service_pb";
+import { SQLResultViewProvider, useSQLResultViewContext } from "./context";
+import { DataExplorerResultView } from "./DataExplorerResultView";
+import type { ResultTableColumn, ResultTableRow } from "./types";
+
+const mocks = vi.hoisted(() => {
+ const tab = {
+ id: "explorer",
+ dataExplorer: {
+ filter: "",
+ initialized: true,
+ selectedRowKey: undefined as number | undefined,
+ },
+ };
+ return {
+ tab,
+ t: (key: string) => key,
+ writeTextToClipboard: vi.fn().mockResolvedValue(true),
+ updateTab: vi.fn(
+ (_: string, patch: { dataExplorer?: typeof tab.dataExplorer }) => {
+ if (patch.dataExplorer) tab.dataExplorer = patch.dataExplorer;
+ }
+ ),
+ };
+});
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => undefined },
+ useTranslation: () => ({ t: mocks.t }),
+}));
+
+vi.mock("react-resizable-panels", () => ({
+ Group: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ Panel: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ Separator: () => <hr />,
+}));
+
+vi.mock("@/components/AdvancedSearch", () => ({
+ AdvancedSearch: ({
+ onParamsChange,
+ placeholder,
+ }: {
+ onParamsChange: (params: { query: string; scopes: [] }) => void;
+ placeholder: string;
+ }) => (
+ <div>
+ <span data-testid="search-placeholder">{placeholder}</span>
+ <button
+ type="button"
+ onClick={() => onParamsChange({ query: "2", scopes: [] })}
+ >
+ search second row
+ </button>
+ </div>
+ ),
+}));
+
+vi.mock("@/lib/clipboard", () => ({
+ writeTextToClipboard: mocks.writeTextToClipboard,
+}));
+
+vi.mock("@/modules/schema-editor/resize", () => ({
+ resizeHandleClass: () => "resize-handle",
+}));
+
+vi.mock("@/modules/sql-editor/store/tab", () => {
+ const state = {
+ currentTabId: "explorer",
+ tabsById: new Map([["explorer", mocks.tab]]),
+ };
+ return {
+ useSQLEditorTabState: (selector: (value: typeof state) => unknown) =>
+ selector(state),
+ getSQLEditorTabsState: () => ({
+ ...state,
+ updateTab: mocks.updateTab,
+ }),
+ };
+});
+
+vi.mock("@/stores/app", () => {
+ const state = { notify: vi.fn() };
+ return {
+ useAppStore: Object.assign(
+ (selector: (value: typeof state) => unknown) => selector(state),
+ { getState: () => state }
+ ),
+ };
+});
+
+vi.mock("./VirtualDataTable", () => ({
+ VirtualDataTable: ({
+ activeRowIndex,
+ onRowClick,
+ }: {
+ activeRowIndex: number;
+ onRowClick: (row: number) => void;
+ }) => (
+ <div>
+ <span data-testid="active-row">{activeRowIndex}</span>
+ <button type="button" onClick={() => onRowClick(1)}>
+ second row
+ </button>
+ </div>
+ ),
+}));
+
+vi.mock("./DetailPanel", async () => {
+ const context = await import("./context");
+ return {
+ DetailPanel: () => {
+ const { detail } = context.useSQLResultViewContext();
+ return (
+ <div data-testid="detail">
+ {detail ? `${detail.row}:${detail.view}` : "empty"}
+ </div>
+ );
+ },
+ };
+});
+
+vi.mock("./ResultStatusBar", () => ({
+ formatQueryTime: () => "25 ms",
+ ResultStatusBar: ({
+ statement,
+ queryTime,
+ }: {
+ statement: string;
+ queryTime: string;
+ }) => <div data-testid="status-bar">{`${statement} ${queryTime}`}</div>,
+}));
+
+const columns: ResultTableColumn[] = [
+ { id: "id", name: "id", columnType: "TEXT" },
+];
+const rows: ResultTableRow[] = [0, 1].map((key) => ({
+ key,
+ item: create(QueryRowSchema, {
+ values: [
+ create(RowValueSchema, {
+ kind: { case: "stringValue", value: String(key + 1) },
+ }),
+ ],
+ }),
+}));
+const database = {
+ name: "instances/i/databases/db",
+ instanceResource: { engine: Engine.COSMOSDB },
+} as Database;
+const result = create(QueryResultSchema, {
+ statement: "SELECT * FROM c",
+ columnNames: ["document"],
+ columnTypeNames: ["JSON"],
+ rows: rows.map((row) => row.item),
+});
+
+function DetailProbe() {
+ const { detail } = useSQLResultViewContext();
+ return <span>{detail?.row}</span>;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.tab.dataExplorer.selectedRowKey = undefined;
+});
+
+describe("DataExplorerResultView", () => {
+ test("selects the first row, then follows a clicked row", async () => {
+ render(
+ <SQLResultViewProvider
+ engine={Engine.COSMOSDB}
+ rows={rows}
+ columns={columns}
+ >
+ <DataExplorerResultView
+ rows={rows}
+ columns={columns}
+ database={database}
+ result={result}
+ onToggleSort={() => undefined}
+ />
+ <DetailProbe />
+ </SQLResultViewProvider>
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId("detail")).toHaveTextContent("0:row");
+ });
+ expect(screen.getByTestId("status-bar")).toHaveTextContent(
+ "SELECT * FROM c 25 ms"
+ );
+ expect(screen.getByTestId("search-placeholder")).toHaveTextContent(
+ "common.search-results"
+ );
+ expect(
+ screen.getByRole("button", { name: "common.copy-all" })
+ ).toBeVisible();
+ fireEvent.click(screen.getByRole("button", { name: "common.copy-all" }));
+ await waitFor(() => {
+ expect(mocks.writeTextToClipboard).toHaveBeenCalledWith(
+ "index\tid\n0\t1\n1\t2"
+ );
+ });
+
+ fireEvent.click(screen.getByRole("button", { name: "second row" }));
+
+ await waitFor(() => {
+ expect(screen.getByTestId("detail")).toHaveTextContent("1:row");
+ expect(screen.getByTestId("active-row")).toHaveTextContent("1");
+ });
+ expect(mocks.tab.dataExplorer.selectedRowKey).toBe(1);
+ });
+
+ test("selects the active search result in the table and detail panel", async () => {
+ render(
+ <SQLResultViewProvider
+ engine={Engine.COSMOSDB}
+ rows={rows}
+ columns={columns}
+ >
+ <DataExplorerResultView
+ rows={rows}
+ columns={columns}
+ database={database}
+ result={result}
+ onToggleSort={() => undefined}
+ />
+ </SQLResultViewProvider>
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId("detail")).toHaveTextContent("0:row");
+ });
+
+ fireEvent.click(
+ screen.getByRole("button", { name: "search second row" })
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId("detail")).toHaveTextContent("1:row");
+ expect(screen.getByTestId("active-row")).toHaveTextContent("1");
+ });
+ });
+
+ test("preserves the selected row when sorting changes its index", async () => {
+ const renderView = (viewRows: ResultTableRow[]) => (
+ <SQLResultViewProvider
+ engine={Engine.COSMOSDB}
+ rows={viewRows}
+ columns={columns}
+ >
+ <DataExplorerResultView
+ rows={viewRows}
+ columns={columns}
+ database={database}
+ result={result}
+ onToggleSort={() => undefined}
+ />
+ </SQLResultViewProvider>
+ );
+ const { rerender } = render(renderView(rows));
+
+ fireEvent.click(screen.getByRole("button", { name: "second row" }));
+ await waitFor(() => {
+ expect(screen.getByTestId("detail")).toHaveTextContent("1:row");
+ expect(mocks.tab.dataExplorer.selectedRowKey).toBe(1);
+ });
+
+ rerender(renderView([rows[1], rows[0]]));
+
+ await waitFor(() => {
+ expect(screen.getByTestId("detail")).toHaveTextContent("0:row");
+ expect(mocks.tab.dataExplorer.selectedRowKey).toBe(1);
+ });
+ });
+});
diff --git a/frontend/src/modules/sql-editor/components/ResultView/DataExplorerResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/DataExplorerResultView.tsx
new file mode 100644
index 0000000000..34fe2cd2bc
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/ResultView/DataExplorerResultView.tsx
@@ -0,0 +1,212 @@
+import { ArrowDownIcon, ArrowUpIcon, XIcon } from "lucide-react";
+import { useCallback, useEffect, useRef } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ Panel,
+ Group as PanelGroup,
+ Separator as PanelResizeHandle,
+} from "react-resizable-panels";
+import { AdvancedSearch } from "@/components/AdvancedSearch";
+import { Button } from "@/components/ui/button";
+import { resizeHandleClass } from "@/modules/schema-editor/resize";
+import {
+ getSQLEditorTabsState,
+ useSQLEditorTabState,
+} from "@/modules/sql-editor/store/tab";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";
+import { CopyAllButton } from "./CopyAllButton";
+import { useSQLResultViewContext } from "./context";
+import { DetailPanel } from "./DetailPanel";
+import { formatQueryTime, ResultStatusBar } from "./ResultStatusBar";
+import type { ResultTableColumn, ResultTableRow, SortState } from "./types";
+import { useResultTableSearch } from "./useResultTableSearch";
+import {
+ VirtualDataTable,
+ type VirtualDataTableHandle,
+} from "./VirtualDataTable";
+
+interface DataExplorerResultViewProps {
+ rows: ResultTableRow[];
+ columns: ResultTableColumn[];
+ database: Database;
+ result: QueryResult;
+ sortState?: SortState;
+ onToggleSort: (columnIndex: number) => void;
+}
+
+export function DataExplorerResultView({
+ rows,
+ columns,
+ database,
+ result,
+ sortState,
+ onToggleSort,
+}: DataExplorerResultViewProps) {
+ const { t } = useTranslation();
+ const { detail, disallowCopyingData, setDetail } = useSQLResultViewContext();
+ const dataTableRef = useRef<VirtualDataTableHandle>(null);
+ const rowsRef = useRef(rows);
+ rowsRef.current = rows;
+ const search = useResultTableSearch(rows, columns, result);
+ const tabId = useSQLEditorTabState((state) => state.currentTabId);
+ const selectedRowKey = useSQLEditorTabState(
+ (state) =>
+ state.tabsById.get(state.currentTabId)?.dataExplorer?.selectedRowKey
+ );
+
+ useEffect(() => {
+ if (rows.length === 0) {
+ setDetail(undefined);
+ return;
+ }
+ const selectedIndex = rows.findIndex((row) => row.key === selectedRowKey);
+ const rowIndex = selectedIndex >= 0 ? selectedIndex : 0;
+ setDetail({ row: rowIndex, col: 0, view: "row" });
+ }, [rows, selectedRowKey, setDetail]);
+
+ useEffect(() => {
+ if (detail?.view !== "row") return;
+ const rowKey = rowsRef.current[detail.row]?.key;
+ if (rowKey === undefined) return;
+ const tabsState = getSQLEditorTabsState();
+ const tab = tabsState.tabsById.get(tabId);
+ if (!tab?.dataExplorer || rowKey === tab.dataExplorer.selectedRowKey) {
+ return;
+ }
+ tabsState.updateTab(tabId, {
+ dataExplorer: { ...tab.dataExplorer, selectedRowKey: rowKey },
+ });
+ }, [detail, tabId]);
+
+ const handleRowClick = useCallback(
+ (rowIndex: number) => {
+ const rowKey = rows[rowIndex]?.key;
+ const tabsState = getSQLEditorTabsState();
+ const tab = tabsState.tabsById.get(tabId);
+ if (rowKey !== undefined && tab?.dataExplorer) {
+ tabsState.updateTab(tabId, {
+ dataExplorer: { ...tab.dataExplorer, selectedRowKey: rowKey },
+ });
+ }
+ setDetail({ row: rowIndex, col: 0, view: "row" });
+ },
+ [rows, setDetail, tabId]
+ );
+
+ useEffect(() => {
+ if (search.activeRowIndex < 0) return;
+ handleRowClick(search.activeRowIndex);
+ requestAnimationFrame(() => {
+ dataTableRef.current?.scrollTo(search.activeRowIndex);
+ });
+ }, [handleRowClick, search.activeRowIndex]);
+
+ return (
+ <div className="h-full min-h-0 w-full flex flex-col">
+ <div className="result-toolbar relative mx-2 mt-2 mb-1 shrink-0 flex items-center justify-between gap-x-4">
+ <div className="flex min-w-0 flex-1 items-center gap-x-2">
+ <AdvancedSearch
+ params={search.params}
+ scopeOptions={search.scopeOptions}
+ placeholder={t("common.search-results")}
+ onParamsChange={search.setParams}
+ onEnter={search.next}
+ />
+ <span className="whitespace-nowrap text-sm text-control-light">
+ {rows.length} {t("sql-editor.rows.self")}
+ </span>
+ </div>
+ {!disallowCopyingData && rows.length > 0 && (
+ <div className="shrink-0">
+ <CopyAllButton />
+ </div>
+ )}
+ </div>
+ <div className="flex-1 min-h-0">
+ <PanelGroup orientation="horizontal" className="h-full min-h-0 w-full">
+ <Panel defaultSize="45%" minSize="30%">
+ <div className="relative h-full min-h-0 p-2 pr-1 flex flex-col">
+ <VirtualDataTable
+ ref={dataTableRef}
+ rows={rows}
+ columns={columns}
+ database={database}
+ statement={result.statement}
+ activeRowIndex={
+ search.activeRowIndex >= 0
+ ? search.activeRowIndex
+ : detail?.view === "row"
+ ? detail.row
+ : -1
+ }
+ search={search.params}
+ sortState={sortState}
+ onToggleSort={onToggleSort}
+ onRowClick={handleRowClick}
+ showRowDetailAction={false}
+ showCellDetailAction={false}
+ allowSelection={false}
+ activeRowHighlight="strong"
+ />
+ {search.candidateRowIndexes.length > 0 && (
+ <div className="absolute bottom-4 right-3 z-1 flex gap-x-2 border shadow rounded bg-background py-1 px-2">
+ <Button
+ size="sm"
+ appearance="secondary"
+ disabled={search.candidateActiveIndex <= 0}
+ onClick={search.previous}
+ >
+ <ArrowUpIcon className="size-4" />
+ {t("sql-editor.previous-row")}
+ </Button>
+ <Button
+ size="sm"
+ appearance="secondary"
+ disabled={
+ search.candidateActiveIndex >=
+ search.candidateRowIndexes.length - 1
+ }
+ onClick={search.next}
+ >
+ <ArrowDownIcon className="size-4" />
+ {t("sql-editor.next-row")}
+ </Button>
+ <Button
+ size="sm"
+ appearance="secondary"
+ className="size-7 p-0"
+ aria-label={t("common.close")}
+ onClick={search.clear}
+ >
+ <XIcon className="size-4" />
+ </Button>
+ </div>
+ )}
+ </div>
+ </Panel>
+ <PanelResizeHandle
+ className={resizeHandleClass("vertical", "w-0.5")}
+ />
+ <Panel defaultSize="55%" minSize="30%">
+ <DetailPanel
+ presentation="embedded"
+ rows={rows}
+ columns={columns}
+ database={database}
+ result={result}
+ statement={result.statement}
+ />
+ </Panel>
+ </PanelGroup>
+ </div>
+ <div className="shrink-0 px-2 pb-1">
+ <ResultStatusBar
+ database={database}
+ statement={result.statement ?? ""}
+ queryTime={formatQueryTime(result.latency)}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/modules/sql-editor/components/ResultView/DetailPanel.tsx b/frontend/src/modules/sql-editor/components/ResultView/DetailPanel.tsx
index 639cee6174..48302ad836 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/DetailPanel.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/DetailPanel.tsx
@@ -55,6 +55,7 @@ interface DetailPanelProps {
result: QueryResult;
statement?: string;
getMaskingReason?: (index: number) => MaskingReason | undefined;
+ presentation?: "sheet" | "embedded";
}
function useLocalStorageBoolean(
@@ -105,6 +106,7 @@ export function DetailPanel({
result,
statement,
getMaskingReason,
+ presentation = "sheet",
}: DetailPanelProps) {
const { t } = useTranslation();
const { detail, disallowCopyingData, setDetail } = useSQLResultViewContext();
@@ -334,6 +336,182 @@ export function DetailPanel({
const selectedColumnName =
detail?.view === "cell" ? columns[detail.col]?.name : undefined;
+ const body = detail ? (
+ <div
+ className={cn(
+ // `flex-1 min-h-0` instead of `h-full` so the wrapper absorbs
+ // the space remaining after `SheetHeader` (not 100vh). The
+ // `min-h-0` lets the inner `flex-1 overflow-auto` block
+ // actually clip and scroll — without it, the scroll region
+ // expands to fit its content and the bottom rows render past
+ // the viewport.
+ // Match `SheetBody`'s `px-6 py-4` so the toolbar buttons
+ // and the content code block don't bleed to the sheet's
+ // raw edges.
+ "flex-1 min-h-0 flex flex-col gap-y-2",
+ presentation === "sheet" ? "px-6 py-4" : "p-2",
+ "text-main"
+ )}
+ >
+ <div
+ className={cn(
+ "flex items-center justify-between gap-x-4",
+ presentation === "embedded" && "flex-wrap gap-y-2"
+ )}
+ >
+ <div className="flex items-center gap-x-2">
+ <Tooltip content={t("sql-editor.previous-row")} delayDuration={500}>
+ <Button
+ size="sm"
+ appearance="outline"
+ disabled={detail.row === 0}
+ onClick={() => move(-1)}
+ >
+ <ChevronUpIcon className="size-4" />
+ </Button>
+ </Tooltip>
+ <Tooltip content={t("sql-editor.next-row")} delayDuration={500}>
+ <Button
+ size="sm"
+ appearance="outline"
+ disabled={detail.row === totalCount - 1}
+ onClick={() => move(1)}
+ >
+ <ChevronDownIcon className="size-4" />
+ </Button>
+ </Tooltip>
+ <div className="text-xs text-control-light flex items-center gap-x-1">
+ <span>{detail.row + 1}</span>
+ <span>/</span>
+ <span>{totalCount}</span>
+ <span>{t("sql-editor.rows.self")}</span>
+ </div>
+ </div>
+
+ <div className="flex min-w-0 items-center gap-x-2">
+ <TextSearchControl
+ query={searchQuery}
+ activeMatchIndex={activeMatchIndex}
+ matchCount={matchCount}
+ onQueryChange={setSearchQuery}
+ onMove={moveSearchMatch}
+ label={t("sql-editor.result-detail.search")}
+ className={cn(
+ presentation === "sheet" ? "w-80 flex-none" : "flex-1"
+ )}
+ />
+
+ <div className="flex shrink-0 items-center gap-1">
+ {guessedIsJSON && detailContent?.kind === "cell" && (
+ <Tooltip content={t("sql-editor.format")}>
+ <Button
+ size="sm"
+ appearance={format ? "solid" : "outline"}
+ className="h-7 px-1.5"
+ onClick={() => setFormat(!format)}
+ >
+ <BracesIcon className="size-4" />
+ </Button>
+ </Tooltip>
+ )}
+
+ {detailContent?.kind === "cell" &&
+ detailContent.value?.kind?.case === "bytesValue" && (
+ <BinaryFormatButton
+ format={detailContent.binaryFormat}
+ onFormatChange={(next) =>
+ setBinaryFormat({
+ rowIndex: detail.row,
+ colIndex: detail.col,
+ format: next,
+ })
+ }
+ />
+ )}
+
+ {!disallowCopyingData && (
+ <Tooltip content={t("common.copy")}>
+ <Button
+ size="sm"
+ appearance="secondary"
+ className="size-7 p-0"
+ onClick={handleCopy}
+ >
+ {copied ? (
+ <CheckIcon className="size-4" />
+ ) : (
+ <CopyIcon className="size-4" />
+ )}
+ </Button>
+ </Tooltip>
+ )}
+ </div>
+ </div>
+ </div>
+
+ <div
+ ref={contentRef}
+ className={cn(
+ "flex-1 overflow-auto text-sm font-mono border p-2 relative",
+ disallowCopyingData ? "select-none" : "select-text",
+ showFormattedJSON && !wrap ? "whitespace-pre" : "whitespace-pre-wrap"
+ )}
+ onClick={stopSelectionClickPropagation}
+ >
+ {detailContent?.kind === "row" ? (
+ <RowDataBlock
+ columns={columns}
+ database={database.name}
+ statement={statement}
+ getMaskingReason={getMaskingReason}
+ renderColumnName={(_, columnIndex) =>
+ rowSearchFields[columnIndex]?.columnName
+ }
+ renderValue={(_, columnIndex) => (
+ <div className="px-2 py-1">
+ <PlainCellValue
+ value={detailContent.fields[columnIndex]?.value}
+ >
+ {rowSearchFields[columnIndex]?.value}
+ </PlainCellValue>
+ </div>
+ )}
+ />
+ ) : showFormattedJSON ? (
+ <>
+ <div className="absolute right-2 top-2 flex justify-end items-center gap-1">
+ <Tooltip content={t("common.text-wrap")}>
+ <Button
+ size="sm"
+ appearance={wrap ? "solid" : "outline"}
+ className="h-6 px-1"
+ onClick={() => setWrap(!wrap)}
+ >
+ <WrapTextIcon className="size-3" />
+ </Button>
+ </Tooltip>
+ </div>
+ <PrettyJSON
+ content={content ?? ""}
+ searchQuery={searchQuery}
+ activeMatchIndex={activeMatchIndex}
+ onMatchCountChange={setFormattedMatchCount}
+ onHighlightedContentChange={handleHighlightedContentChange}
+ />
+ </>
+ ) : content && content.length > 0 ? (
+ <>{searchResult.kind === "plain" ? searchResult.nodes : null}</>
+ ) : (
+ <br style={{ minWidth: "1rem", display: "inline-flex" }} />
+ )}
+ </div>
+ </div>
+ ) : null;
+
+ if (presentation === "embedded") {
+ return <div className="h-full min-h-0 flex flex-col">{body}</div>;
+ }
+
return (
<Sheet open={isOpen} onOpenChange={handleOpenChange}>
<SheetContent width="standard">
@@ -354,174 +532,7 @@ export function DetailPanel({
</SheetDescription>
)}
</SheetHeader>
- {detail && (
- <div
- className={cn(
- // `flex-1 min-h-0` instead of `h-full` so the wrapper absorbs
- // the space remaining after `SheetHeader` (not 100vh). The
- // `min-h-0` lets the inner `flex-1 overflow-auto` block
- // actually clip and scroll — without it, the scroll region
- // expands to fit its content and the bottom rows render past
- // the viewport.
- // Match `SheetBody`'s `px-6 py-4` so the toolbar buttons
- // and the content code block don't bleed to the sheet's
- // raw edges.
- "flex-1 min-h-0 flex flex-col gap-y-2 px-6 py-4",
- "text-main"
- )}
- >
- <div className="flex items-center justify-between gap-x-4">
- <div className="flex items-center gap-x-2">
- <Tooltip
- content={t("sql-editor.previous-row")}
- delayDuration={500}
- >
- <Button
- size="sm"
- appearance="outline"
- disabled={detail.row === 0}
- onClick={() => move(-1)}
- >
- <ChevronUpIcon className="size-4" />
- </Button>
- </Tooltip>
- <Tooltip content={t("sql-editor.next-row")} delayDuration={500}>
- <Button
- size="sm"
- appearance="outline"
- disabled={detail.row === totalCount - 1}
- onClick={() => move(1)}
- >
- <ChevronDownIcon className="size-4" />
- </Button>
- </Tooltip>
- <div className="text-xs text-control-light flex items-center gap-x-1">
- <span>{detail.row + 1}</span>
- <span>/</span>
- <span>{totalCount}</span>
- <span>{t("sql-editor.rows.self")}</span>
- </div>
- </div>
-
- <div className="flex min-w-0 items-center gap-x-2">
- <TextSearchControl
- query={searchQuery}
- activeMatchIndex={activeMatchIndex}
- matchCount={matchCount}
- onQueryChange={setSearchQuery}
- onMove={moveSearchMatch}
- label={t("sql-editor.result-detail.search")}
- className="w-80 flex-none"
- />
-
- <div className="flex shrink-0 items-center gap-1">
- {guessedIsJSON && detailContent?.kind === "cell" && (
- <Tooltip content={t("sql-editor.format")}>
- <Button
- size="sm"
- appearance={format ? "solid" : "outline"}
- className="h-7 px-1.5"
- onClick={() => setFormat(!format)}
- >
- <BracesIcon className="size-4" />
- </Button>
- </Tooltip>
- )}
-
- {detailContent?.kind === "cell" &&
- detailContent.value?.kind?.case === "bytesValue" && (
- <BinaryFormatButton
- format={detailContent.binaryFormat}
- onFormatChange={(next) =>
- setBinaryFormat({
- rowIndex: detail.row,
- colIndex: detail.col,
- format: next,
- })
- }
- />
- )}
-
- {!disallowCopyingData && (
- <Tooltip content={t("common.copy")}>
- <Button
- size="sm"
- appearance="secondary"
- className="size-7 p-0"
- onClick={handleCopy}
- >
- {copied ? (
- <CheckIcon className="size-4" />
- ) : (
- <CopyIcon className="size-4" />
- )}
- </Button>
- </Tooltip>
- )}
- </div>
- </div>
- </div>
-
- <div
- ref={contentRef}
- className={cn(
- "flex-1 overflow-auto text-sm font-mono border p-2 relative",
- disallowCopyingData ? "select-none" : "select-text",
- showFormattedJSON && !wrap
- ? "whitespace-pre"
- : "whitespace-pre-wrap"
- )}
- onClick={stopSelectionClickPropagation}
- >
- {detailContent?.kind === "row" ? (
- <RowDataBlock
- columns={columns}
- database={database.name}
- statement={statement}
- getMaskingReason={getMaskingReason}
- renderColumnName={(_, columnIndex) =>
- rowSearchFields[columnIndex]?.columnName
- }
- renderValue={(_, columnIndex) => (
- <div className="px-2 py-1">
- <PlainCellValue
- value={detailContent.fields[columnIndex]?.value}
- >
- {rowSearchFields[columnIndex]?.value}
- </PlainCellValue>
- </div>
- )}
- />
- ) : showFormattedJSON ? (
- <>
- <div className="absolute right-2 top-2 flex justify-end items-center gap-1">
- <Tooltip content={t("common.text-wrap")}>
- <Button
- size="sm"
- appearance={wrap ? "solid" : "outline"}
- className="h-6 px-1"
- onClick={() => setWrap(!wrap)}
- >
- <WrapTextIcon className="size-3" />
- </Button>
- </Tooltip>
- </div>
- <PrettyJSON
- content={content ?? ""}
- searchQuery={searchQuery}
- activeMatchIndex={activeMatchIndex}
- onMatchCountChange={setFormattedMatchCount}
- onHighlightedContentChange={handleHighlightedContentChange}
- />
- </>
- ) : content && content.length > 0 ? (
- <>{searchResult.kind === "plain" ? searchResult.nodes : null}</>
- ) : (
- <br style={{ minWidth: "1rem", display: "inline-flex" }} />
- )}
- </div>
- </div>
- )}
+ {body}
</SheetContent>
</Sheet>
);
diff --git a/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.test.tsx
index c8451de49f..78f6e673b3 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.test.tsx
@@ -2,7 +2,7 @@ import { render, screen } from "@testing-library/react";
import { act } from "react";
import { beforeEach, describe, expect, test, vi } from "vitest";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
-import { ResultStatusBar } from "./ResultStatusBar";
+import { formatQueryTime, ResultStatusBar } from "./ResultStatusBar";
vi.mock("react-i18next", () => ({
initReactI18next: {
@@ -76,6 +76,16 @@ describe("ResultStatusBar", () => {
resizeCallbacks = [];
});
+ test("formats query latency", () => {
+ expect(formatQueryTime(undefined)).toBe("-");
+ expect(formatQueryTime({ seconds: 0n, nanos: 250_000_000 } as never)).toBe(
+ "250 ms"
+ );
+ expect(formatQueryTime({ seconds: 2n, nanos: 500_000_000 } as never)).toBe(
+ "2.50 s"
+ );
+ });
+
test("lets the database label shrink while the statement truncates", () => {
render(
<ResultStatusBar
diff --git a/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.tsx b/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.tsx
index 2e4e3cb9e4..e0ce7d8cd4 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/ResultStatusBar.tsx
@@ -6,6 +6,16 @@ import { CopyButton } from "@/components/ui/copy-button";
import { EllipsisText } from "@/components/ui/ellipsis-text";
import { cn } from "@/lib/utils";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";
+
+export const formatQueryTime = (latency: QueryResult["latency"]): string => {
+ if (!latency) return "-";
+ const totalSeconds = Number(latency.seconds) + latency.nanos / 1e9;
+ if (totalSeconds < 1) {
+ return `${Math.round(totalSeconds * 1000)} ms`;
+ }
+ return `${totalSeconds.toFixed(2)} s`;
+};
type ResultStatusBarProps = Readonly<{
database: Database;
diff --git a/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx
index 0921aede71..16e6589a77 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/ResultView.tsx
@@ -37,6 +37,7 @@ import {
import { EmptyView } from "./EmptyView";
import { ErrorView } from "./ErrorView";
import { SingleResultView } from "./SingleResultView";
+import type { ResultViewPresentation } from "./types";
export interface ResultViewProps {
executeParams: SQLEditorQueryParams;
@@ -46,6 +47,7 @@ export interface ResultViewProps {
// Compact layout (fixed-height result body) for the terminal / admin panel.
// The saved query panel leaves this false to keep the flex-grow layout.
compact?: boolean;
+ presentation?: ResultViewPresentation;
}
type ViewMode = "SINGLE-RESULT" | "MULTI-RESULT" | "EMPTY" | "ERROR";
@@ -63,6 +65,7 @@ export function ResultView({
resultSet,
loading,
compact = false,
+ presentation = "STANDARD",
}: ResultViewProps) {
const { t } = useTranslation();
const project = useSQLEditorEditorState((s) => s.project);
@@ -262,6 +265,7 @@ export function ResultView({
!showExport ? requestExportButton : undefined
}
compact={compact}
+ presentation={presentation}
/>
))}
@@ -334,6 +338,7 @@ export function ResultView({
maximumExportCount={queryDataPolicy?.maximumResultRows}
onExport={handleExport}
compact={compact}
+ presentation={presentation}
/>
)}
</TabsPanel>
diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx
index ba9c03570e..a882106fae 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx
@@ -248,6 +248,7 @@ vi.mock("./ErrorView", () => ({
}));
vi.mock("./ResultStatusBar", () => ({
+ formatQueryTime: () => "-",
ResultStatusBar: () => <div data-testid="result-status" />,
}));
diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx
index 6dd2993e4d..62e7b09764 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx
@@ -4,7 +4,6 @@ import {
ArrowDownIcon,
ArrowUpIcon,
BracesIcon,
- ChevronDownIcon,
CopyIcon,
InfoIcon,
Table2Icon,
@@ -20,11 +19,7 @@ import {
} from "react";
import { useTranslation } from "react-i18next";
import { v4 as uuidv4 } from "uuid";
-import {
- AdvancedSearch,
- type ScopeOption,
- type SearchParams,
-} from "@/components/AdvancedSearch";
+import { AdvancedSearch } from "@/components/AdvancedSearch";
import { DatabaseTargetDisplay } from "@/components/DatabaseTargetDisplay";
import {
DataExportButton,
@@ -32,12 +27,6 @@ import {
} from "@/components/DataExportButton";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
import { SegmentedControl } from "@/components/ui/segmented-control";
import { Switch } from "@/components/ui/switch";
import { Tooltip } from "@/components/ui/tooltip";
@@ -47,7 +36,6 @@ import { cn } from "@/lib/utils";
import { useSQLEditorQueryDataPolicy } from "@/modules/sql-editor/hooks/useSQLEditorState";
import { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";
import { useSQLEditorTabState } from "@/modules/sql-editor/store/tab";
-import { useAppStore } from "@/stores/app";
import type {
SQLEditorDatabaseQueryContext,
SQLEditorQueryParams,
@@ -58,7 +46,6 @@ import {
QueryOption_MSSQLExplainFormat,
QueryOptionSchema,
type QueryResult,
- type RowValue,
} from "@/types/proto-es/v1/sql_service_pb";
import { createExplainToken } from "@/utils/pev2";
import {
@@ -68,19 +55,25 @@ import {
isNoSQLQueryResult,
} from "@/utils/sqlResult";
import { STORAGE_KEY_SQL_EDITOR_NOSQL_TABLE_VIEW } from "@/utils/storage-keys";
-import { isNullOrUndefined } from "@/utils/util";
import { getInstanceResource } from "@/utils/v1/database";
import { compareQueryRowValues, extractSQLRowValuePlain } from "@/utils/v1/sql";
-import { SQLResultViewProvider, useSelectionContext } from "./context";
-import { formatAsCSV, formatAsSQL, formatAsText } from "./copy-formats";
+import { CopyAllButton } from "./CopyAllButton";
+import { SQLResultViewProvider } from "./context";
+import { DataExplorerResultView } from "./DataExplorerResultView";
import { DetailPanel } from "./DetailPanel";
import { DocumentJSONView } from "./DocumentJSONView";
import { EmptyView } from "./EmptyView";
import { ErrorView } from "./ErrorView";
-import { ResultStatusBar } from "./ResultStatusBar";
+import { formatQueryTime, ResultStatusBar } from "./ResultStatusBar";
import { SelectionCopyTooltips } from "./SelectionCopyTooltips";
import { TextSearchControl } from "./TextSearchControl";
-import type { ResultTableColumn, ResultTableRow, SortState } from "./types";
+import type {
+ ResultTableColumn,
+ ResultTableRow,
+ ResultViewPresentation,
+ SortState,
+} from "./types";
+import { useResultTableSearch } from "./useResultTableSearch";
import {
VirtualDataBlock,
type VirtualDataBlockHandle,
@@ -107,6 +100,7 @@ export interface SingleResultViewProps {
// Compact layout (fixed-height, non-growing body) used by the terminal /
// admin result panel. Defaults to the flex-grow saved query layout.
compact?: boolean;
+ presentation?: ResultViewPresentation;
}
type ViewMode = "RESULT" | "EMPTY" | "AFFECTED-ROWS" | "ERROR";
@@ -144,9 +138,12 @@ export function SingleResultView(props: SingleResultViewProps) {
() => isDocumentEngine && isNoSQLQueryResult(result),
[isDocumentEngine, result]
);
- const activeDocumentViewMode = supportsDocumentJSONView
- ? documentViewMode
- : "TABLE";
+ const activeDocumentViewMode =
+ props.presentation === "DATA_EXPLORER"
+ ? "TABLE"
+ : supportsDocumentJSONView
+ ? documentViewMode
+ : "TABLE";
const flattened = useMemo(() => {
if (engine === Engine.ELASTICSEARCH) {
return flattenElasticsearchSearchResult(result);
@@ -225,21 +222,32 @@ export function SingleResultView(props: SingleResultViewProps) {
rows={rows}
columns={columns}
>
- <SingleResultViewInner
- {...props}
- engine={engine}
- columns={columns}
- rows={rows}
- sortState={sortState}
- toggleSort={toggleSort}
- flattenedTableView={flattenedTableView}
- supportsTableViewToggle={supportsTableViewToggle}
- noSQLTableView={noSQLTableView}
- setNoSQLTableView={setNoSQLTableView}
- supportsDocumentJSONView={supportsDocumentJSONView}
- documentViewMode={activeDocumentViewMode}
- setDocumentViewMode={setDocumentViewMode}
- />
+ {props.presentation === "DATA_EXPLORER" ? (
+ <DataExplorerResultView
+ rows={rows}
+ columns={columns}
+ database={database}
+ result={result}
+ sortState={sortState}
+ onToggleSort={toggleSort}
+ />
+ ) : (
+ <SingleResultViewInner
+ {...props}
+ engine={engine}
+ columns={columns}
+ rows={rows}
+ sortState={sortState}
+ toggleSort={toggleSort}
+ flattenedTableView={flattenedTableView}
+ supportsTableViewToggle={supportsTableViewToggle}
+ noSQLTableView={noSQLTableView}
+ setNoSQLTableView={setNoSQLTableView}
+ supportsDocumentJSONView={supportsDocumentJSONView}
+ documentViewMode={activeDocumentViewMode}
+ setDocumentViewMode={setDocumentViewMode}
+ />
+ )}
</SQLResultViewProvider>
);
}
@@ -292,7 +300,6 @@ function SingleResultViewInner({
const resultRowsLimit = useSQLEditorEditorState((s) => s.resultRowsLimit);
const policyMaxRows = queryDataPolicy.maximumResultRows;
const { runQuery } = useExecuteSQL();
- const { copy, canCopyAsInsert } = useSelectionContext();
const supportFormats = useMemo(
() => [
@@ -309,15 +316,17 @@ function SingleResultViewInner({
>(null);
const [vertical, setVertical] = useState(false);
- const [searchParams, setSearchParams] = useState<SearchParams>({
- query: "",
- scopes: [],
- });
- const [searchCandidateActiveIndex, setSearchCandidateActiveIndex] =
- useState(-1);
- const [searchCandidateRowIndexs, setSearchCandidateRowIndexs] = useState<
- number[]
- >([]);
+ const {
+ params: searchParams,
+ setParams: setSearchParams,
+ scopeOptions: searchScopeOptions,
+ candidateActiveIndex: searchCandidateActiveIndex,
+ candidateRowIndexes: searchCandidateRowIndexes,
+ activeRowIndex,
+ next: scrollToNextCandidate,
+ previous: scrollToPreviousCandidate,
+ clear: clearSearchCandidate,
+ } = useResultTableSearch(rows, columns, noSQLTableView);
const [documentSearchQuery, setDocumentSearchQuery] = useState("");
const [documentSearchActiveIndex, setDocumentSearchActiveIndex] = useState(0);
const [documentSearchMatchCount, setDocumentSearchMatchCount] = useState(0);
@@ -341,14 +350,6 @@ function SingleResultViewInner({
});
}, [documentSearchMatchCount]);
- // Reset search state when toggling NoSQL table view (sort reset is
- // handled by the wrapper, where sortState lives).
- useEffect(() => {
- setSearchParams({ query: "", scopes: [] });
- setSearchCandidateActiveIndex(-1);
- setSearchCandidateRowIndexs([]);
- }, [noSQLTableView]);
-
const viewMode: ViewMode = useMemo(() => {
if (result.error && rows.length === 0) return "ERROR";
const columnNames = result.columnNames;
@@ -359,97 +360,6 @@ function SingleResultViewInner({
return "RESULT";
}, [result, rows.length]);
- const searchScopeOptions: ScopeOption[] = useMemo(() => {
- const opts: ScopeOption[] = [
- {
- id: "row-number",
- title: t("sql-editor.search-scope-row-number-title"),
- description: t("sql-editor.search-scope-row-number-description"),
- },
- ];
- for (const column of columns) {
- opts.push({
- id: column.id,
- title: column.name,
- description: t("sql-editor.search-scope-column-description", {
- type: column.columnType,
- }),
- });
- }
- return opts;
- }, [columns, t]);
-
- // Recompute candidates when search params change.
- const cellValueMatches = useCallback(
- (cell: RowValue, query: string): boolean => {
- const value = extractSQLRowValuePlain(cell);
- if (isNullOrUndefined(value)) return false;
- return String(value).toLowerCase().includes(query.toLowerCase());
- },
- []
- );
-
- const getNextCandidateRowIndex = useCallback(
- (from: number, sp: SearchParams): number => {
- if (sp.scopes.length === 0 && !sp.query) return -1;
- for (let i = from; i < rows.length; i++) {
- const row = rows[i];
- const scopeOk = sp.scopes.every((scope) => {
- if (!scope.value) return false;
- if (scope.id === "row-number") {
- return i + 1 === Number.parseInt(scope.value, 10);
- }
- const columnIndex = columns.findIndex((c) => c.name === scope.id);
- if (columnIndex < 0) return false;
- return cellValueMatches(row.item.values[columnIndex], scope.value);
- });
- if (!scopeOk) continue;
- if (sp.query) {
- const queryOk = row.item.values.some((cell) =>
- cellValueMatches(cell, sp.query)
- );
- if (!queryOk) continue;
- }
- return i;
- }
- return -1;
- },
- [rows, columns, cellValueMatches]
- );
-
- // Tracks whether the previous searchParams already resolved to the
- // "active search, zero matches" state. Used to fire the no-results
- // notification only on the transition into that state — typing extra
- // characters that keep the match set empty must not re-notify.
- const wasInNoResultsRef = useRef(false);
-
- useEffect(() => {
- const next = getNextCandidateRowIndex(0, searchParams);
- const indexes: number[] = [];
- if (next >= 0) {
- indexes.push(next);
- const another = getNextCandidateRowIndex(next + 1, searchParams);
- if (another >= 0) indexes.push(another);
- }
- setSearchCandidateRowIndexs(indexes);
- setSearchCandidateActiveIndex(0);
-
- const searchActive =
- searchParams.query.trim().length > 0 || searchParams.scopes.length > 0;
- const isNoResults = searchActive && indexes.length === 0;
- if (isNoResults && !wasInNoResultsRef.current) {
- useAppStore.getState().notify({
- module: "bytebase",
- style: "INFO",
- title: t("sql-editor.search-no-result"),
- });
- }
- wasInNoResultsRef.current = isNoResults;
- }, [searchParams, getNextCandidateRowIndex, t]);
-
- const activeRowIndex =
- searchCandidateRowIndexs[searchCandidateActiveIndex] ?? -1;
-
const scrollToRow = useCallback((index: number | undefined) => {
if (index === undefined || index < 0) return;
requestAnimationFrame(() => dataTableRef.current?.scrollTo(index));
@@ -460,30 +370,6 @@ function SingleResultViewInner({
scrollToRow(activeRowIndex);
}, [activeRowIndex, vertical, scrollToRow]);
- const scrollToNextCandidate = () => {
- if (searchCandidateActiveIndex >= searchCandidateRowIndexs.length - 1) {
- return;
- }
- const next = searchCandidateActiveIndex + 1;
- setSearchCandidateActiveIndex(next);
- if (next === searchCandidateRowIndexs.length - 1) {
- const cur = searchCandidateRowIndexs[next];
- const more = getNextCandidateRowIndex(cur + 1, searchParams);
- if (more >= 0) {
- setSearchCandidateRowIndexs((prev) => [...prev, more]);
- }
- }
- };
-
- const scrollToPreviousCandidate = () => {
- if (searchCandidateActiveIndex <= 0) return;
- setSearchCandidateActiveIndex(searchCandidateActiveIndex - 1);
- };
-
- const clearSearchCandidate = () => {
- setSearchParams({ query: "", scopes: [] });
- };
-
const reachQueryLimit =
currentTabMode !== "ADMIN" &&
(rows.length === resultRowsLimit || rows.length === policyMaxRows);
@@ -522,15 +408,7 @@ function SingleResultViewInner({
}
};
- const queryTime = useMemo(() => {
- const { latency } = result;
- if (!latency) return "-";
- const totalSeconds = Number(latency.seconds) + latency.nanos / 1e9;
- if (totalSeconds < 1) {
- return `${Math.round(totalSeconds * 1000)} ms`;
- }
- return `${totalSeconds.toFixed(2)} s`;
- }, [result]);
+ const queryTime = formatQueryTime(result.latency);
const resultRowsText = `${rows.length} ${t("sql-editor.rows.self")}`;
const isJSONView = supportsDocumentJSONView && documentViewMode === "JSON";
@@ -705,53 +583,7 @@ function SingleResultViewInner({
</Button>
)}
{!disallowCopyingData && rows.length > 0 && !isJSONView && (
- // Split button: the main action copies as plain text (TSV); the
- // dropdown caret (hover) offers CSV and, for SQL engines, SQL.
- <div className="flex items-center">
- <Button
- size="sm"
- appearance="outline"
- className="h-7 px-2 rounded-r-none border-r-0 text-control border-control-border hover:bg-control-bg-hover"
- onClick={() => copy("all", formatAsText)}
- >
- <CopyIcon className="size-4" />
- {t("common.copy-all")}
- </Button>
- <DropdownMenu>
- <DropdownMenuTrigger
- openOnHover
- delay={100}
- render={
- <Button
- size="sm"
- appearance="outline"
- aria-label={t("common.copy")}
- className="h-7 w-6 px-0 rounded-l-none text-control border-control-border hover:bg-control-bg-hover"
- >
- <ChevronDownIcon className="size-4" />
- </Button>
- }
- />
- <DropdownMenuContent align="end" className="min-w-0">
- <DropdownMenuItem
- onClick={() => copy("all", formatAsCSV)}
- className="px-2 py-1 text-xs gap-x-1.5"
- >
- <CopyIcon className="size-3" />
- {t("sql-editor.copy-all-rows-as-csv")}
- </DropdownMenuItem>
- {canCopyAsInsert && (
- <DropdownMenuItem
- onClick={() => copy("all", formatAsSQL)}
- className="px-2 py-1 text-xs gap-x-1.5"
- >
- <CopyIcon className="size-3" />
- {t("sql-editor.copy-all-rows-as-sql")}
- </DropdownMenuItem>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
+ <CopyAllButton />
)}
{showExport ? (
<DataExportButton
@@ -819,7 +651,7 @@ function SingleResultViewInner({
{/* Floating buttons */}
<div className="absolute bottom-2 right-4 flex items-end gap-x-2">
- {searchCandidateRowIndexs.length > 0 && (
+ {searchCandidateRowIndexes.length > 0 && (
<div className="flex flex-row gap-x-2 border shadow rounded bg-background py-1 px-2">
<Button
size="sm"
@@ -835,7 +667,7 @@ function SingleResultViewInner({
appearance="secondary"
disabled={
searchCandidateActiveIndex >=
- searchCandidateRowIndexs.length - 1
+ searchCandidateRowIndexes.length - 1
}
onClick={scrollToNextCandidate}
>
diff --git a/frontend/src/modules/sql-editor/components/ResultView/TableCell.tsx b/frontend/src/modules/sql-editor/components/ResultView/TableCell.tsx
index 681d406cb8..a497688967 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/TableCell.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/TableCell.tsx
@@ -23,6 +23,7 @@ interface TableCellProps {
columnType: string;
scope?: SearchScope;
keyword: string;
+ showDetailAction?: boolean;
}
export function TableCell({
@@ -33,6 +34,7 @@ export function TableCell({
columnType,
scope,
keyword,
+ showDetailAction = true,
}: TableCellProps) {
const { setDetail } = useSQLResultViewContext();
const { getBinaryFormat, setBinaryFormat } = useBinaryFormatContext();
@@ -126,8 +128,12 @@ export function TableCell({
ref={wrapperRef}
className={cn(
"font-mono text-start whitespace-pre line-clamp-3",
- (hasByteData || clickable) && "max-w-[calc(100%-1.5rem)]",
- hasByteData && clickable && "max-w-[calc(100%-3.25rem)]"
+ (hasByteData || (clickable && showDetailAction)) &&
+ "max-w-[calc(100%-1.5rem)]",
+ hasByteData &&
+ clickable &&
+ showDetailAction &&
+ "max-w-[calc(100%-3.25rem)]"
)}
>
{inner}
@@ -141,7 +147,7 @@ export function TableCell({
}
/>
)}
- {clickable && (
+ {clickable && showDetailAction && (
<Button
size="sm"
appearance="outline"
diff --git a/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.test.tsx
index 4e997ca9b9..bd8f2c9b55 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.test.tsx
@@ -156,6 +156,65 @@ describe("VirtualDataTable row detail action", () => {
expect(screen.getByTestId("detail-state")).toHaveTextContent("0:0:row");
});
+ test("releases row detail action focus after pointer activation", () => {
+ render(
+ <SQLResultViewProvider
+ engine={Engine.COSMOSDB}
+ rows={rows}
+ columns={columns}
+ >
+ <VirtualDataTable
+ rows={rows}
+ columns={columns}
+ activeRowIndex={-1}
+ database={database}
+ search={{ query: "", scopes: [] }}
+ onToggleSort={() => undefined}
+ />
+ <DetailProbe />
+ </SQLResultViewProvider>
+ );
+
+ const action = screen.getByRole("button", {
+ name: "sql-editor.view-detail",
+ });
+ action.focus();
+ expect(action).toHaveFocus();
+
+ fireEvent.click(action, { detail: 1 });
+
+ expect(action).not.toHaveFocus();
+ expect(screen.getByTestId("detail-state")).toHaveTextContent("0:0:row");
+ });
+
+ test("keeps row detail action focus after keyboard activation", () => {
+ render(
+ <SQLResultViewProvider
+ engine={Engine.COSMOSDB}
+ rows={rows}
+ columns={columns}
+ >
+ <VirtualDataTable
+ rows={rows}
+ columns={columns}
+ activeRowIndex={-1}
+ database={database}
+ search={{ query: "", scopes: [] }}
+ onToggleSort={() => undefined}
+ />
+ </SQLResultViewProvider>
+ );
+
+ const action = screen.getByRole("button", {
+ name: "sql-editor.view-detail",
+ });
+ action.focus();
+
+ fireEvent.click(action, { detail: 0 });
+
+ expect(action).toHaveFocus();
+ });
+
test("opens the entire relational row when a data cell is double-clicked", () => {
const { container } = render(
<SQLResultViewProvider
@@ -184,4 +243,77 @@ describe("VirtualDataTable row detail action", () => {
fireEvent.doubleClick(cellValue);
expect(screen.getByTestId("detail-state")).toHaveTextContent("0:0:row");
});
+
+ test("supports selecting a row without the row detail action", () => {
+ const onRowClick = vi.fn();
+ const { container } = render(
+ <SQLResultViewProvider
+ engine={Engine.COSMOSDB}
+ rows={rows}
+ columns={columns}
+ >
+ <VirtualDataTable
+ rows={rows}
+ columns={columns}
+ activeRowIndex={0}
+ database={database}
+ search={{ query: "", scopes: [] }}
+ onToggleSort={() => undefined}
+ onRowClick={onRowClick}
+ showRowDetailAction={false}
+ />
+ </SQLResultViewProvider>
+ );
+
+ fireEvent.click(
+ container.querySelector(
+ '[data-row-index="0"] [data-col-index="1"]'
+ )!
+ );
+
+ expect(onRowClick).toHaveBeenCalledWith(0);
+ expect(
+ screen.queryByRole("button", { name: "sql-editor.view-detail" })
+ ).not.toBeInTheDocument();
+ expect(container.querySelector(".textinfolabel")).not.toHaveClass(
+ "group-hover:opacity-0"
+ );
+ });
+
+ test("activates a row without creating a copy selection", () => {
+ const onRowClick = vi.fn();
+ const { container } = render(
+ <SQLResultViewProvider
+ engine={Engine.COSMOSDB}
+ rows={rows}
+ columns={columns}
+ >
+ <VirtualDataTable
+ rows={rows}
+ columns={columns}
+ activeRowIndex={0}
+ database={database}
+ search={{ query: "", scopes: [] }}
+ onToggleSort={() => undefined}
+ onRowClick={onRowClick}
+ showRowDetailAction={false}
+ allowSelection={false}
+ activeRowHighlight="strong"
+ />
+ </SQLResultViewProvider>
+ );
+
+ fireEvent.click(screen.getByText("one"));
+
+ expect(onRowClick).toHaveBeenCalledWith(0);
+ expect(
+ screen.queryByRole("button", { name: "Select row 1" })
+ ).not.toBeInTheDocument();
+ expect(
+ container.querySelector('[data-col-index="1"] > div')
+ ).not.toHaveClass("cursor-pointer");
+ expect(container.querySelector('[data-col-index="1"]')).toHaveClass(
+ "bg-accent/20!"
+ );
+ });
});
diff --git a/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.tsx b/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.tsx
index b4a1ac47c3..d0ed9301bf 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.tsx
@@ -58,6 +58,11 @@ export interface VirtualDataTableProps {
sortState?: SortState;
search: SearchParams;
onToggleSort: (columnIndex: number) => void;
+ onRowClick?: (rowIndex: number) => void;
+ showRowDetailAction?: boolean;
+ showCellDetailAction?: boolean;
+ allowSelection?: boolean;
+ activeRowHighlight?: "subtle" | "strong";
}
/**
@@ -81,6 +86,11 @@ export const VirtualDataTable = forwardRef<
sortState,
search,
onToggleSort,
+ onRowClick,
+ showRowDetailAction = true,
+ showCellDetailAction = true,
+ allowSelection = true,
+ activeRowHighlight = "subtle",
},
ref
) {
@@ -109,6 +119,7 @@ export const VirtualDataTable = forwardRef<
const { getBinaryFormat, setBinaryFormat } = useBinaryFormatContext();
const { setDetail } = useSQLResultViewContext();
+ const selectionEnabled = allowSelection && !selectionDisabled;
const getColumnTypeByIndex = useCallback(
(columnIndex: number) => columns[columnIndex]?.columnType ?? "",
@@ -293,7 +304,7 @@ export const VirtualDataTable = forwardRef<
<div
className={cn(
"textinfolabel pr-1 opacity-0",
- selectionDisabled ? "pl-1" : "pl-4"
+ selectionEnabled ? "pl-4" : "pl-1"
)}
>
{totalRows}
@@ -316,10 +327,14 @@ export const VirtualDataTable = forwardRef<
onResizeStart={(e) =>
tableResize.onResizeStart(columnIndex + 1, e)
}
- onClick={(e) => handleSelectColumn(e, columnIndex)}
+ onClick={
+ selectionEnabled
+ ? (e) => handleSelectColumn(e, columnIndex)
+ : undefined
+ }
className={cn(
"px-3 py-1.5 min-w-8 text-left text-xs font-medium text-control-light tracking-wider",
- !selectionDisabled &&
+ selectionEnabled &&
"cursor-pointer hover:bg-control-bg-hover",
// NOTE: opacity may need visual tuning on dark themes
isSelected && "bg-accent/10!"
@@ -387,6 +402,8 @@ export const VirtualDataTable = forwardRef<
const row = rows[rowIndex];
if (!row) return null;
const isActive = activeRowIndex === rowIndex;
+ const hasStrongActiveHighlight =
+ isActive && activeRowHighlight === "strong";
const rowSelected =
selectionState.columns.length === 0 &&
selectionState.rows.includes(rowIndex);
@@ -395,6 +412,9 @@ export const VirtualDataTable = forwardRef<
key={virtualRow.key}
data-row-index={rowIndex}
className="flex absolute inset-x-0 group"
+ onClickCapture={
+ onRowClick ? () => onRowClick(rowIndex) : undefined
+ }
onDoubleClick={() =>
setDetail({ row: rowIndex, col: 0, view: "row" })
}
@@ -410,7 +430,10 @@ export const VirtualDataTable = forwardRef<
className={cn(
"relative flex items-center shrink-0 text-sm text-control leading-5 whitespace-nowrap break-all border-block-border border-r border-b group-even:bg-control-bg/40",
// NOTE: opacity may need visual tuning on dark themes
- isActive && "bg-accent/10!",
+ isActive &&
+ (hasStrongActiveHighlight
+ ? "bg-accent/20! text-accent font-medium"
+ : "bg-accent/10!"),
rowSelected && "bg-accent/20!"
)}
data-col-index={0}
@@ -419,32 +442,41 @@ export const VirtualDataTable = forwardRef<
width: `${indexColWidth}px`,
}}
>
- <div className="absolute left-3 top-1/2 size-6 -translate-y-1/2 opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto group-focus-within:opacity-100 group-focus-within:pointer-events-auto">
- <Tooltip content={t("sql-editor.view-detail")} side="right">
- <Button
- size="sm"
- appearance="outline"
- className="size-6 rounded-full p-0 shadow"
- aria-label={t("sql-editor.view-detail")}
- onClick={(event) => {
- event.stopPropagation();
- setDetail({ row: rowIndex, col: 0, view: "row" });
- }}
+ {showRowDetailAction && (
+ <div className="absolute left-3 top-1/2 size-6 -translate-y-1/2 opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto group-focus-within:opacity-100 group-focus-within:pointer-events-auto">
+ <Tooltip
+ content={t("sql-editor.view-detail")}
+ side="right"
>
- <ExpandIcon className="size-3" />
- </Button>
- </Tooltip>
- </div>
+ <Button
+ size="sm"
+ appearance="outline"
+ className="size-6 rounded-full p-0 shadow"
+ aria-label={t("sql-editor.view-detail")}
+ onClick={(event) => {
+ event.stopPropagation();
+ if (event.detail > 0) {
+ event.currentTarget.blur();
+ }
+ setDetail({ row: rowIndex, col: 0, view: "row" });
+ }}
+ >
+ <ExpandIcon className="size-3" />
+ </Button>
+ </Tooltip>
+ </div>
+ )}
<span
className={cn(
"textinfolabel pr-1 truncate",
- selectionDisabled ? "pl-1" : "pl-4",
- "group-hover:opacity-0 group-hover:pointer-events-none group-focus-within:opacity-0 group-focus-within:pointer-events-none"
+ selectionEnabled ? "pl-4" : "pl-1",
+ showRowDetailAction &&
+ "group-hover:opacity-0 group-hover:pointer-events-none group-focus-within:opacity-0 group-focus-within:pointer-events-none"
)}
>
{rowIndex + 1}
</span>
- {!selectionDisabled && (
+ {selectionEnabled && (
<button
type="button"
aria-label={`Select row ${rowIndex + 1}`}
@@ -472,7 +504,10 @@ export const VirtualDataTable = forwardRef<
// highlights every cell in that row, not just the index
// column.
// NOTE: opacity may need visual tuning on dark themes
- isActive && "bg-accent/10!"
+ isActive &&
+ (hasStrongActiveHighlight
+ ? "bg-accent/20!"
+ : "bg-accent/10!")
)}
data-col-index={columnIndex + 1}
style={{
@@ -489,8 +524,9 @@ export const VirtualDataTable = forwardRef<
)}
rowIndex={rowIndex}
colIndex={columnIndex}
- allowSelect
+ allowSelect={selectionEnabled}
columnType={getColumnTypeByIndex(columnIndex)}
+ showDetailAction={showCellDetailAction}
/>
</div>
</div>
diff --git a/frontend/src/modules/sql-editor/components/ResultView/index.ts b/frontend/src/modules/sql-editor/components/ResultView/index.ts
index ce57ec4785..bd1406896a 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/index.ts
+++ b/frontend/src/modules/sql-editor/components/ResultView/index.ts
@@ -26,6 +26,7 @@ export { getPlainValue } from "./cell-value";
export type {
ResultTableColumn,
ResultTableRow,
+ ResultViewPresentation,
SortDirection,
SortState,
} from "./types";
diff --git a/frontend/src/modules/sql-editor/components/ResultView/types.ts b/frontend/src/modules/sql-editor/components/ResultView/types.ts
index 74f700d404..02968945c8 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/types.ts
+++ b/frontend/src/modules/sql-editor/components/ResultView/types.ts
@@ -17,3 +17,5 @@ export interface SortState {
columnIndex: number;
direction: SortDirection;
}
+
+export type ResultViewPresentation = "STANDARD" | "DATA_EXPLORER";
diff --git a/frontend/src/modules/sql-editor/components/ResultView/useResultTableSearch.ts b/frontend/src/modules/sql-editor/components/ResultView/useResultTableSearch.ts
new file mode 100644
index 0000000000..37c3b6b7e2
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/ResultView/useResultTableSearch.ts
@@ -0,0 +1,142 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { ScopeOption, SearchParams } from "@/components/AdvancedSearch";
+import { useAppStore } from "@/stores/app";
+import type { RowValue } from "@/types/proto-es/v1/sql_service_pb";
+import { isNullOrUndefined } from "@/utils/util";
+import { extractSQLRowValuePlain } from "@/utils/v1/sql";
+import type { ResultTableColumn, ResultTableRow } from "./types";
+
+const EMPTY_SEARCH: SearchParams = { query: "", scopes: [] };
+
+export const useResultTableSearch = (
+ rows: ResultTableRow[],
+ columns: ResultTableColumn[],
+ resetKey?: unknown
+) => {
+ const { t } = useTranslation();
+ const [params, setParams] = useState<SearchParams>(EMPTY_SEARCH);
+ const [candidateActiveIndex, setCandidateActiveIndex] = useState(-1);
+ const [candidateRowIndexes, setCandidateRowIndexes] = useState<number[]>([]);
+ const wasInNoResultsRef = useRef(false);
+
+ const scopeOptions: ScopeOption[] = useMemo(() => {
+ return [
+ {
+ id: "row-number",
+ title: t("sql-editor.search-scope-row-number-title"),
+ description: t("sql-editor.search-scope-row-number-description"),
+ },
+ ...columns.map((column) => ({
+ id: column.id,
+ title: column.name,
+ description: t("sql-editor.search-scope-column-description", {
+ type: column.columnType,
+ }),
+ })),
+ ];
+ }, [columns, t]);
+
+ const cellValueMatches = useCallback((cell: RowValue, query: string) => {
+ const value = extractSQLRowValuePlain(cell);
+ if (isNullOrUndefined(value)) return false;
+ return String(value).toLowerCase().includes(query.toLowerCase());
+ }, []);
+
+ const getNextCandidateRowIndex = useCallback(
+ (from: number, search: SearchParams): number => {
+ if (search.scopes.length === 0 && !search.query) return -1;
+ for (let index = from; index < rows.length; index++) {
+ const row = rows[index];
+ const scopeMatches = search.scopes.every((scope) => {
+ if (!scope.value) return false;
+ if (scope.id === "row-number") {
+ return index + 1 === Number.parseInt(scope.value, 10);
+ }
+ const columnIndex = columns.findIndex(
+ (column) => column.name === scope.id
+ );
+ if (columnIndex < 0) return false;
+ return cellValueMatches(row.item.values[columnIndex], scope.value);
+ });
+ if (!scopeMatches) continue;
+ if (
+ search.query &&
+ !row.item.values.some((cell) => cellValueMatches(cell, search.query))
+ ) {
+ continue;
+ }
+ return index;
+ }
+ return -1;
+ },
+ [cellValueMatches, columns, rows]
+ );
+
+ useEffect(() => {
+ const first = getNextCandidateRowIndex(0, params);
+ const indexes: number[] = [];
+ if (first >= 0) {
+ indexes.push(first);
+ const second = getNextCandidateRowIndex(first + 1, params);
+ if (second >= 0) indexes.push(second);
+ }
+ setCandidateRowIndexes(indexes);
+ setCandidateActiveIndex(0);
+
+ const searchActive =
+ params.query.trim().length > 0 || params.scopes.length > 0;
+ const hasNoResults = searchActive && indexes.length === 0;
+ if (hasNoResults && !wasInNoResultsRef.current) {
+ useAppStore.getState().notify({
+ module: "bytebase",
+ style: "INFO",
+ title: t("sql-editor.search-no-result"),
+ });
+ }
+ wasInNoResultsRef.current = hasNoResults;
+ }, [getNextCandidateRowIndex, params, t]);
+
+ useEffect(() => {
+ setParams(EMPTY_SEARCH);
+ setCandidateActiveIndex(-1);
+ setCandidateRowIndexes([]);
+ }, [resetKey]);
+
+ const next = useCallback(() => {
+ if (candidateActiveIndex >= candidateRowIndexes.length - 1) return;
+ const nextIndex = candidateActiveIndex + 1;
+ setCandidateActiveIndex(nextIndex);
+ if (nextIndex === candidateRowIndexes.length - 1) {
+ const currentRow = candidateRowIndexes[nextIndex];
+ const more = getNextCandidateRowIndex(currentRow + 1, params);
+ if (more >= 0) {
+ setCandidateRowIndexes((current) => [...current, more]);
+ }
+ }
+ }, [
+ candidateActiveIndex,
+ candidateRowIndexes,
+ getNextCandidateRowIndex,
+ params,
+ ]);
+
+ const previous = useCallback(() => {
+ if (candidateActiveIndex <= 0) return;
+ setCandidateActiveIndex((current) => current - 1);
+ }, [candidateActiveIndex]);
+
+ const clear = useCallback(() => setParams(EMPTY_SEARCH), []);
+
+ return {
+ params,
+ setParams,
+ scopeOptions,
+ candidateActiveIndex,
+ candidateRowIndexes,
+ activeRowIndex: candidateRowIndexes[candidateActiveIndex] ?? -1,
+ next,
+ previous,
+ clear,
+ };
+};
diff --git a/frontend/src/modules/sql-editor/components/RunQueryButton.tsx b/frontend/src/modules/sql-editor/components/RunQueryButton.tsx
new file mode 100644
index 0000000000..89d9825d61
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/RunQueryButton.tsx
@@ -0,0 +1,49 @@
+import { Play } from "lucide-react";
+import type { ComponentProps } from "react";
+import { Button } from "@/components/ui/button";
+import { Tooltip } from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";
+import { QueryContextSettingPopover } from "./QueryContextSettingPopover";
+
+type Props = {
+ readonly disabled?: boolean;
+ readonly settingsDisabled?: boolean;
+ readonly size?: "sm" | "md";
+ readonly type?: ComponentProps<typeof Button>["type"];
+ readonly onClick?: ComponentProps<typeof Button>["onClick"];
+};
+
+export function RunQueryButton({
+ disabled = false,
+ settingsDisabled = disabled,
+ size = "sm",
+ type = "button",
+ onClick,
+}: Props) {
+ const resultRowsLimit = useSQLEditorEditorState((s) => s.resultRowsLimit);
+
+ return (
+ <div className="inline-flex">
+ <Tooltip content="" side="bottom">
+ <Button
+ type={type}
+ variant="default"
+ size={size}
+ className={cn(
+ "px-1.5 gap-1 rounded-r-none text-sm",
+ size === "sm" && "h-7"
+ )}
+ disabled={disabled}
+ onClick={onClick}
+ >
+ <Play className="size-4 fill-current" />
+ <span className="inline-flex items-center">
+ (limit&nbsp;{resultRowsLimit})
+ </span>
+ </Button>
+ </Tooltip>
+ <QueryContextSettingPopover disabled={settingsDisabled} size={size} />
+ </div>
+ );
+}
diff --git a/frontend/src/modules/sql-editor/components/SchemaPane/SchemaPane.test.tsx b/frontend/src/modules/sql-editor/components/SchemaPane/SchemaPane.test.tsx
index df0fe15d07..04da4b52da 100644
--- a/frontend/src/modules/sql-editor/components/SchemaPane/SchemaPane.test.tsx
+++ b/frontend/src/modules/sql-editor/components/SchemaPane/SchemaPane.test.tsx
@@ -23,6 +23,9 @@ const mocks = vi.hoisted(() => ({
},
instanceRefValue: { engine: 1 },
currentTab: null as unknown,
+ currentTabId: "",
+ databaseMetadata: undefined as unknown,
+ updateTab: vi.fn(),
getOrFetchDatabaseMetadata: vi
.fn()
.mockResolvedValue({ name: "instances/i/databases/db", schemas: [] }),
@@ -55,9 +58,9 @@ vi.mock("@/stores/app", () => {
syncDatabase: vi.fn(),
fetchDatabases: vi.fn(async () => ({ databases: [], nextPageToken: "" })),
databasesByName: {} as Record<string, unknown>,
- // SchemaPane reads cached metadata reactively via this getter; return
- // undefined so the tree stays empty unless a test seeds the cache.
- getCachedDatabaseMetadata: () => undefined,
+ // SchemaPane reads cached metadata reactively via this getter. Tests can
+ // seed the cache through databaseMetadata when they need a rendered tree.
+ getCachedDatabaseMetadata: () => mocks.databaseMetadata,
getOrFetchDatabaseMetadata: mocks.getOrFetchDatabaseMetadata,
};
return {
@@ -80,15 +83,15 @@ vi.mock("@/modules/sql-editor/hooks/useSQLEditorState", () => ({
// state built from `mocks.currentTab`; the imperative getter exposes the
// same shape plus the mutators SchemaPane invokes.
const tabsState = () => ({
- currentTabId: mocks.currentTab ? "t1" : "",
+ currentTabId: mocks.currentTabId,
tabsById: new Map<string, unknown>(
- mocks.currentTab ? [["t1", mocks.currentTab]] : []
+ mocks.currentTab ? [[mocks.currentTabId, mocks.currentTab]] : []
),
openTmpTabList: [],
addTab: vi.fn(),
setCurrentTabId: vi.fn(),
updateCurrentTab: vi.fn(),
- updateTab: vi.fn(),
+ updateTab: mocks.updateTab,
});
vi.mock("@/modules/sql-editor/store/tab", () => ({
@@ -268,7 +271,8 @@ const renderInto = (element: ReactElement) => {
const root = createRoot(container);
return {
container,
- render: () => act(() => root.render(element)),
+ render: (nextElement = element) =>
+ act(() => root.render(nextElement)),
unmount: () => {
act(() => root.unmount());
container.remove();
@@ -280,6 +284,8 @@ beforeEach(async () => {
vi.clearAllMocks();
mocks.databaseRefValue = { name: "" };
mocks.currentTab = null;
+ mocks.currentTabId = "";
+ mocks.databaseMetadata = undefined;
mocks.isValidDatabaseName.mockReturnValue(false);
({ SchemaPane } = await import("./SchemaPane"));
});
@@ -329,4 +335,76 @@ describe("SchemaPane shell", () => {
});
unmount();
});
+
+ test("initializes tree state when switching tabs for the same database", async () => {
+ const requestAnimationFrame = vi
+ .spyOn(window, "requestAnimationFrame")
+ .mockImplementation((callback) => {
+ callback(0);
+ return 1;
+ });
+ const database = "instances/i/databases/db";
+ mocks.isValidDatabaseName.mockReturnValue(true);
+ mocks.databaseRefValue = { name: database };
+ mocks.databaseMetadata = {
+ schemas: [
+ {
+ name: "",
+ tables: [
+ {
+ name: "users",
+ columns: [],
+ indexes: [],
+ foreignKeys: [],
+ triggers: [],
+ checkConstraints: [],
+ partitions: [],
+ },
+ ],
+ externalTables: [],
+ views: [],
+ procedures: [],
+ packages: [],
+ functions: [],
+ sequences: [],
+ },
+ ],
+ };
+ mocks.currentTabId = "editor";
+ mocks.currentTab = {
+ id: "editor",
+ connection: { database, schema: "" },
+ treeState: { database, keys: [] },
+ viewState: { view: "CODE" },
+ };
+ const { container, render, unmount } = renderInto(<SchemaPane />);
+ render();
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(container.querySelector("[data-testid='tree']")).not.toBeNull();
+ mocks.updateTab.mockClear();
+
+ mocks.currentTabId = "explorer";
+ mocks.currentTab = {
+ id: "explorer",
+ connection: { database, schema: "", table: "users" },
+ treeState: { database: "", keys: [] },
+ viewState: { view: "CODE" },
+ mode: "DATA_EXPLORER",
+ };
+ render(<SchemaPane />);
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ });
+
+ expect(mocks.updateTab).toHaveBeenCalledWith("explorer", {
+ treeState: {
+ database,
+ keys: expect.arrayContaining([expect.stringContaining("table")]),
+ },
+ });
+ unmount();
+ requestAnimationFrame.mockRestore();
+ });
});
diff --git a/frontend/src/modules/sql-editor/components/SchemaPane/SchemaPane.tsx b/frontend/src/modules/sql-editor/components/SchemaPane/SchemaPane.tsx
index 11c07a3946..de9951393c 100644
--- a/frontend/src/modules/sql-editor/components/SchemaPane/SchemaPane.tsx
+++ b/frontend/src/modules/sql-editor/components/SchemaPane/SchemaPane.tsx
@@ -158,40 +158,52 @@ function SchemaPaneInner() {
// Build the tree via requestAnimationFrame so the heavy walk doesn't
// block the metadata-fetch teardown's transition. Mirrors Vue's
// `requestAnimationFrame(() => { tree.value = buildDatabaseSchemaTree(...) })`.
- const [tree, setTree] = useState<SchemaTreeNode[] | undefined>(undefined);
+ const [treeResult, setTreeResult] = useState<
+ { database: string; tree: SchemaTreeNode[] } | undefined
+ >(undefined);
+ const tree =
+ treeResult?.database === database.name ? treeResult.tree : undefined;
useEffect(() => {
if (isFetching || !metadata) {
- setTree(undefined);
+ setTreeResult(undefined);
return;
}
if (totalTableCount > FLAT_TABLE_THRESHOLD) {
- setTree(undefined);
+ setTreeResult(undefined);
return;
}
let raf = 0;
raf = requestAnimationFrame(() => {
const built = buildDatabaseSchemaTree(database, metadata);
- setTree(built);
- // First-mount default expand: seed treeState.keys so the user
- // sees database/schema/Tables/Views opened by default. The Vue
- // version seeds when `treeStateDb !== connectionDb && connectionDb`.
- const tab = getSQLEditorTabsState().tabsById.get(
- getSQLEditorTabsState().currentTabId
- );
- const connectionDb = tab?.connection.database;
- if (tab && connectionDb && tab.treeState.database !== connectionDb) {
- getSQLEditorTabsState().updateTab(tab.id, {
- treeState: {
- ...tab.treeState,
- database: connectionDb,
- keys: defaultExpandedKeys(built),
- },
- });
- }
+ setTreeResult({ database: database.name, tree: built });
});
return () => cancelAnimationFrame(raf);
}, [isFetching, metadata, totalTableCount, database]);
+ // Seed expansion state for every tab, including a newly opened Data
+ // Explorer tab that reuses the already-built tree for the same database.
+ useEffect(() => {
+ if (!tree) return;
+ const tabsState = getSQLEditorTabsState();
+ const tab = tabsState.tabsById.get(currentTabId);
+ const connectionDb = tab?.connection.database;
+ if (
+ !tab ||
+ !connectionDb ||
+ connectionDb !== database.name ||
+ tab.treeState.database === connectionDb
+ ) {
+ return;
+ }
+ tabsState.updateTab(tab.id, {
+ treeState: {
+ ...tab.treeState,
+ database: connectionDb,
+ keys: defaultExpandedKeys(tree),
+ },
+ });
+ }, [currentTabId, database.name, tree]);
+
// Reactive proxy for `tab.treeState.keys`. Writes via `setExpandedKeys`
// always REPLACE the whole array. The Zustand selector subscribes on
// the keys array reference, which `updateTab` swaps via immer on every
diff --git a/frontend/src/modules/sql-editor/components/SchemaPane/actions.test.tsx b/frontend/src/modules/sql-editor/components/SchemaPane/actions.test.tsx
index dae2e99944..669507a0cd 100644
--- a/frontend/src/modules/sql-editor/components/SchemaPane/actions.test.tsx
+++ b/frontend/src/modules/sql-editor/components/SchemaPane/actions.test.tsx
@@ -27,6 +27,9 @@ const mocks = vi.hoisted(() => {
getInstanceResource: vi.fn(() => ({ engine: 1 })),
instanceV1HasAlterSchema: vi.fn(() => true),
supportGetStringSchema: vi.fn(() => true),
+ tabsById: new Map<string, unknown>(),
+ addTab: vi.fn(),
+ setCurrentTabId: vi.fn(),
sortByDictionary: vi.fn(
<T,>(arr: T[], order: string[], keyFn: (i: T) => string) => {
arr.sort((a, b) => {
@@ -75,10 +78,10 @@ vi.mock("@/modules/sql-editor/store/tab", () => ({
// invoked handler stays a no-op.
getSQLEditorTabsState: () => ({
currentTabId: "t1",
- tabsById: new Map([["t1", { id: "t1", viewState: { schema: "" } }]]),
+ tabsById: mocks.tabsById,
openTmpTabList: [],
- addTab: vi.fn(),
- setCurrentTabId: vi.fn(),
+ addTab: mocks.addTab,
+ setCurrentTabId: mocks.setCurrentTabId,
updateCurrentTab: vi.fn(),
updateTab: vi.fn(),
}),
@@ -132,7 +135,7 @@ vi.mock("@/types", () => ({
}));
vi.mock("@/types/proto-es/v1/common_pb", () => ({
- Engine: { REDIS: 7, MYSQL: 1 },
+ Engine: { REDIS: 7, MYSQL: 1, COSMOSDB: 20 },
}));
vi.mock("@/types/proto-es/v1/database_service_pb", () => ({
@@ -170,6 +173,14 @@ let useSchemaPaneContextMenu: typeof import("./actions").useSchemaPaneContextMen
type SchemaMenuItem = import("./actions").SchemaMenuItem;
beforeEach(async () => {
+ vi.clearAllMocks();
+ mocks.tabsById.clear();
+ mocks.tabsById.set("t1", {
+ id: "t1",
+ mode: "SAVED_QUERY",
+ viewState: { schema: "" },
+ });
+ mocks.getInstanceResource.mockReturnValue({ engine: 1 });
({ useSchemaPaneContextMenu } = await import("./actions"));
});
@@ -340,4 +351,56 @@ describe("useSchemaPaneContextMenu", () => {
mocks.instanceV1HasAlterSchema.mockReturnValue(true);
}
});
+
+ test("preview opens a data explorer tab for a supported engine", () => {
+ const node = makeNode("table", {
+ database: DATABASE,
+ schema: "",
+ table: "users",
+ });
+
+ captureItems(node, noopDeps)
+ .find((item) => item.key === "preview-table-data")
+ ?.onSelect?.();
+
+ expect(mocks.addTab).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "users",
+ mode: "DATA_EXPLORER",
+ connection: {
+ instance: "instances/i",
+ database: DATABASE,
+ schema: "",
+ table: "users",
+ },
+ dataExplorer: { filter: "", initialized: false },
+ }),
+ true
+ );
+ });
+
+ test("preview reuses an explorer for the same database object", () => {
+ mocks.tabsById.set("explorer", {
+ id: "explorer",
+ mode: "DATA_EXPLORER",
+ connection: {
+ instance: "instances/i",
+ database: DATABASE,
+ schema: "",
+ table: "users",
+ },
+ });
+ const node = makeNode("table", {
+ database: DATABASE,
+ schema: "",
+ table: "users",
+ });
+
+ captureItems(node, noopDeps)
+ .find((item) => item.key === "preview-table-data")
+ ?.onSelect?.();
+
+ expect(mocks.setCurrentTabId).toHaveBeenCalledWith("explorer");
+ expect(mocks.addTab).not.toHaveBeenCalled();
+ });
});
diff --git a/frontend/src/modules/sql-editor/components/SchemaPane/actions.tsx b/frontend/src/modules/sql-editor/components/SchemaPane/actions.tsx
index 4f73a01b62..e088cb7389 100644
--- a/frontend/src/modules/sql-editor/components/SchemaPane/actions.tsx
+++ b/frontend/src/modules/sql-editor/components/SchemaPane/actions.tsx
@@ -271,6 +271,49 @@ export function useSchemaPaneActions() {
[getDatabaseByName, execute]
);
+ const openDataExplorer = useCallback((node: TreeNode) => {
+ const { target, type } = (node as TreeNode<"table" | "view">).meta;
+ if (type !== "table" && type !== "view") return;
+
+ const table = readableTextForNodeTarget(type, target);
+ if (!table) return;
+
+ const { database, schema } = target;
+ const connection: SQLEditorConnection = {
+ instance: extractDatabaseResourceName(database).instance,
+ database,
+ schema: schema ?? "",
+ table,
+ };
+ const tabsState = getSQLEditorTabsState();
+ const existing = [...tabsState.tabsById.values()].find(
+ (tab) =>
+ tab.mode === "DATA_EXPLORER" &&
+ tab.connection.instance === connection.instance &&
+ tab.connection.database === connection.database &&
+ (tab.connection.schema ?? "") === connection.schema &&
+ tab.connection.table === connection.table
+ );
+ if (existing) {
+ tabsState.setCurrentTabId(existing.id);
+ return;
+ }
+
+ tabsState.addTab(
+ {
+ title: table,
+ status: "CLEAN",
+ mode: "DATA_EXPLORER",
+ connection,
+ dataExplorer: {
+ filter: "",
+ initialized: false,
+ },
+ },
+ true
+ );
+ }, []);
+
const viewDetail = useCallback(
async (node: TreeNode) => {
const { type, target } = node.meta;
@@ -335,7 +378,12 @@ export function useSchemaPaneActions() {
[openNewTab]
);
- return { selectAllFromTableOrView, viewDetail, openNewTab };
+ return {
+ selectAllFromTableOrView,
+ openDataExplorer,
+ viewDetail,
+ openNewTab,
+ };
}
export type SchemaMenuItem = {
@@ -390,8 +438,7 @@ export function useSchemaPaneContextMenu(
// metadata at call time via `useAppStore.getState()` so we don't
// subscribe (and re-derive the menu) on every metadata cache update.
const getTableMetadata = useAppStore((s) => s.getTableMetadata);
- const { selectAllFromTableOrView, viewDetail, openNewTab } =
- useSchemaPaneActions();
+ const { openDataExplorer, viewDetail, openNewTab } = useSchemaPaneActions();
const notify = useCallback(
(key: string) => {
@@ -535,10 +582,10 @@ export function useSchemaPaneContextMenu(
if (targetSupportsGenerateSQL(target)) {
items.push({
key: "preview-table-data",
- label: t("sql-editor.preview-table-data"),
+ label: t("sql-editor.explore-data"),
icon: <TableIcon className="size-4" />,
onSelect: () => {
- void selectAllFromTableOrView(node);
+ openDataExplorer(node);
},
});
}
@@ -654,8 +701,8 @@ export function useSchemaPaneContextMenu(
getDatabaseByName,
getTableMetadata,
notify,
+ openDataExplorer,
openNewTab,
- selectAllFromTableOrView,
t,
viewDetail,
]);
diff --git a/frontend/src/modules/sql-editor/components/TabItem/Label.test.tsx b/frontend/src/modules/sql-editor/components/TabItem/Label.test.tsx
index a7222678cc..b0019362b6 100644
--- a/frontend/src/modules/sql-editor/components/TabItem/Label.test.tsx
+++ b/frontend/src/modules/sql-editor/components/TabItem/Label.test.tsx
@@ -158,6 +158,18 @@ describe("Label", () => {
unmount();
});
+ test("data explorer title is read-only", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <Label tab={makeTab({ mode: "DATA_EXPLORER" })} />
+ );
+ render();
+
+ expect(container.querySelector(".cursor-text")).toBeNull();
+ expect(container.querySelector("input")).toBeNull();
+
+ unmount();
+ });
+
test("blur with the initial title still calls store.updateTab (preserving title)", () => {
const { container, render, unmount } = renderIntoContainer(
<Label tab={makeTab({ title: "Old" })} />
diff --git a/frontend/src/modules/sql-editor/components/TabItem/Label.tsx b/frontend/src/modules/sql-editor/components/TabItem/Label.tsx
index b09fc4f476..54086991ca 100644
--- a/frontend/src/modules/sql-editor/components/TabItem/Label.tsx
+++ b/frontend/src/modules/sql-editor/components/TabItem/Label.tsx
@@ -28,7 +28,8 @@ export function Label({ tab }: Props) {
const [draft, setDraft] = useState(tab.title);
const inputRef = useRef<HTMLInputElement>(null);
- const readonly = tab.viewState.view !== "CODE";
+ const readonly =
+ tab.mode === "DATA_EXPLORER" || tab.viewState.view !== "CODE";
const displayTitle = tab.title || t("common.untitled");
// Captures whether the tab was already current at mousedown time, before
// the parent TabItem's onMouseDown handler runs and switches activation.
diff --git a/frontend/src/modules/sql-editor/components/TabItem/Prefix.tsx b/frontend/src/modules/sql-editor/components/TabItem/Prefix.tsx
index ca2dba1de7..214f9774f1 100644
--- a/frontend/src/modules/sql-editor/components/TabItem/Prefix.tsx
+++ b/frontend/src/modules/sql-editor/components/TabItem/Prefix.tsx
@@ -1,4 +1,4 @@
-import { PencilLine, Users, Wrench } from "lucide-react";
+import { PencilLine, TableProperties, Users, Wrench } from "lucide-react";
import { useSheetContext } from "@/modules/sql-editor/model/Sheet";
import { useAppStore } from "@/stores/app";
import type { SQLEditorTab } from "@/types/sqlEditor/tab";
@@ -19,7 +19,10 @@ type Props = {
export function Prefix({ tab }: Props) {
const { isSavedQueryCreator } = useSheetContext();
- const isDraft = !tab.savedQuery && tab.viewState.view === "CODE";
+ const isDraft =
+ tab.mode === "SAVED_QUERY" &&
+ !tab.savedQuery &&
+ tab.viewState.view === "CODE";
const sheet = useAppStore((s) =>
tab.savedQuery ? s.getSavedQueryByName(tab.savedQuery) : null
@@ -33,6 +36,9 @@ export function Prefix({ tab }: Props) {
<>
{sheet && !isSavedQueryCreator(sheet) && <Users className="size-4" />}
{tab.mode === "ADMIN" && <Wrench className="size-4" />}
+ {tab.mode === "DATA_EXPLORER" && (
+ <TableProperties className="size-4" />
+ )}
</>
)}
<SheetConnectionIcon tab={tab} />
diff --git a/frontend/src/modules/sql-editor/components/TabItem/TabItem.tsx b/frontend/src/modules/sql-editor/components/TabItem/TabItem.tsx
index 247732cb24..bb83a5e7de 100644
--- a/frontend/src/modules/sql-editor/components/TabItem/TabItem.tsx
+++ b/frontend/src/modules/sql-editor/components/TabItem/TabItem.tsx
@@ -127,11 +127,7 @@ export function TabItem({
style={bodyStyle}
>
<Prefix tab={tab} />
- {tab.mode === "SAVED_QUERY" ? (
- <Label tab={tab} />
- ) : (
- <AdminLabel tab={tab} />
- )}
+ {tab.mode === "ADMIN" ? <AdminLabel tab={tab} /> : <Label tab={tab} />}
<Suffix tab={tab} onClose={() => onClose(tab, index)} />
</div>
</div>
diff --git a/frontend/src/modules/sql-editor/store/tab.test.ts b/frontend/src/modules/sql-editor/store/tab.test.ts
index 50e72fe091..d1e6af728a 100644
--- a/frontend/src/modules/sql-editor/store/tab.test.ts
+++ b/frontend/src/modules/sql-editor/store/tab.test.ts
@@ -3,6 +3,7 @@ import { storageKeySqlEditorTabs } from "@/utils";
import {
__resetTabStoreProjectCursor,
getSQLEditorTabsState,
+ isSQLEditorTabClosable,
subscribeSQLEditorTabsState,
useSQLEditorTabsStore,
} from "./tab";
@@ -152,6 +153,12 @@ describe("useSQLEditorTabsStore", () => {
expect(state.currentTabId).toBe("");
});
+ test("the only data explorer tab is closable", () => {
+ const tab = getSQLEditorTabsState().addTab({ mode: "DATA_EXPLORER" });
+
+ expect(isSQLEditorTabClosable(tab)).toBe(true);
+ });
+
test("setOpenTabListOrder rewrites the persisted order without losing tabs", () => {
const a = getSQLEditorTabsState().addTab({ title: "a" });
const b = getSQLEditorTabsState().addTab({ title: "b" });
diff --git a/frontend/src/modules/sql-editor/store/tab.ts b/frontend/src/modules/sql-editor/store/tab.ts
index e2e7764185..147b779865 100644
--- a/frontend/src/modules/sql-editor/store/tab.ts
+++ b/frontend/src/modules/sql-editor/store/tab.ts
@@ -160,7 +160,7 @@ const persistOpenTabs = (openTabs: PersistentTab[]) => {
if (!scope) return;
safeWrite(
storageKeySqlEditorTabs(scope.wsScope, scope.project, scope.email),
- openTabs
+ openTabs.filter((tab) => tab.mode !== "DATA_EXPLORER")
);
};
@@ -637,6 +637,7 @@ export const useTabById = (tabId: string): SQLEditorTab | undefined =>
export const isSQLEditorTabClosable = (tab: SQLEditorTab): boolean => {
const open = getSQLEditorTabsState().openTmpTabList;
if (open.length > 1) return true;
+ if (tab.mode === "DATA_EXPLORER") return true;
if (open.length === 1) return !!tab.savedQuery;
return false;
};
@@ -657,14 +658,14 @@ export const useIsDisconnected = (): boolean =>
export const useSupportBatchMode = (): boolean =>
useSQLEditorTabsStore((s) => {
const tab = s.tabsById.get(s.currentTabId);
- return tab?.mode !== "ADMIN";
+ return tab?.mode === "SAVED_QUERY";
});
export const useIsInBatchMode = (): boolean =>
useSQLEditorTabsStore((s) => {
const tab = s.tabsById.get(s.currentTabId);
if (!tab) return false;
- if (tab.mode === "ADMIN") return false;
+ if (tab.mode !== "SAVED_QUERY") return false;
const appStore = useAppStore.getState();
if (!appStore.hasFeature(PlanFeature.FEATURE_BATCH_QUERY)) return false;
const ctx = tab.batchQueryContext;
diff --git a/frontend/src/types/sqlEditor/tab.ts b/frontend/src/types/sqlEditor/tab.ts
index 095bf0518c..40878a6441 100644
--- a/frontend/src/types/sqlEditor/tab.ts
+++ b/frontend/src/types/sqlEditor/tab.ts
@@ -10,8 +10,14 @@ export type SQLEditorTabStatus =
| "SAVING" // auto-saving in progress
| "CLEAN"; // saved to a remote sheet
-export type SQLEditorTabMode = "SAVED_QUERY" | "ADMIN";
+export type SQLEditorTabMode = "SAVED_QUERY" | "ADMIN" | "DATA_EXPLORER";
export const DEFAULT_SQL_EDITOR_TAB_MODE: SQLEditorTabMode = "SAVED_QUERY";
+
+export type DataExplorerState = {
+ filter: string;
+ initialized: boolean;
+ selectedRowKey?: number;
+};
export type QueryDataSourceType =
| DataSourceType.ADMIN
| DataSourceType.READ_ONLY;
@@ -72,6 +78,7 @@ export type SQLEditorTab = {
statement: string; // local editing statement, might be out-of-sync to ref sheet's statement
selectedStatement: string;
mode: SQLEditorTabMode;
+ dataExplorer?: DataExplorerState;
// SQL query related fields
// won't be saved to localStorage
diff --git a/frontend/src/utils/v1/sql.ts b/frontend/src/utils/v1/sql.ts
index 90772cf4d0..e5ef3cdfee 100644
--- a/frontend/src/utils/v1/sql.ts
+++ b/frontend/src/utils/v1/sql.ts
@@ -135,7 +135,7 @@ const formatTimestampWithTz = (timestampTzValue: RowValue_TimestampTZ) => {
return formattedTimestamp;
};
-const escapeMongoDBCollectionName = (name: string) => {
+export const escapeMongoDBCollectionName = (name: string) => {
// The backend wraps --eval in single quotes for shell execution and escapes
// single quotes with '"'"'. To avoid conflicts, we:
// 1. Use double quotes for the collection name string
@@ -168,7 +168,7 @@ const wrapSQLIdentifier = (id: string, engine: Engine) => {
return "`" + id + "`";
};
-const generateSchemaAndTableNameInSQL = (
+export const generateSchemaAndTableNameInSQL = (
engine: Engine,
schema: string,
tableOrView: string