Skip to content

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

chore: support click to show row detail (#21204)

ecmadao334c5c31d1e6
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 663a9fc5a2..aedc5e6261 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -3065,6 +3065,7 @@
"request-access-grant": "Request access grant",
"request-export": "Request export",
"result-detail": {
+ "cell": "Cell detail",
"next-match": "Next match",
"previous-match": "Previous match",
"search": "Search detail"
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index ba41109b3f..0516eaf844 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -3065,6 +3065,7 @@
"request-access-grant": "Solicitar concesión de acceso",
"request-export": "Solicitar exportación",
"result-detail": {
+ "cell": "Detalle de celda",
"next-match": "Siguiente coincidencia",
"previous-match": "Coincidencia anterior",
"search": "Buscar en detalles"
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 27cdbf904f..2ea98a25ce 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -3065,6 +3065,7 @@
"request-access-grant": "アクセス付与をリクエスト",
"request-export": "エクスポートをリクエスト",
"result-detail": {
+ "cell": "セルの詳細",
"next-match": "次の一致",
"previous-match": "前の一致",
"search": "詳細を検索"
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index e9506e2383..abb0682945 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -3065,6 +3065,7 @@
"request-access-grant": "Yêu cầu cấp quyền truy cập",
"request-export": "Yêu cầu xuất dữ liệu",
"result-detail": {
+ "cell": "Chi tiết ô",
"next-match": "Kết quả tiếp theo",
"previous-match": "Kết quả trước",
"search": "Tìm trong chi tiết"
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 2d10f932a3..566c9d2479 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -3065,6 +3065,7 @@
"request-access-grant": "申请访问授权",
"request-export": "申请导出",
"result-detail": {
+ "cell": "单元格详情",
"next-match": "下一个匹配项",
"previous-match": "上一个匹配项",
"search": "搜索详情"
diff --git a/frontend/src/modules/sql-editor/components/ResultView/DetailPanel.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/DetailPanel.test.tsx
index f65f511b6d..11c2a589eb 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/DetailPanel.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/DetailPanel.test.tsx
@@ -1,15 +1,20 @@
import { create } from "@bufbuild/protobuf";
+import { NullValue } from "@bufbuild/protobuf/wkt";
import type { ReactElement } from "react";
import { act, useEffect } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, 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 {
+ type QueryResult,
+ QueryResultSchema,
QueryRowSchema,
type RowValue,
RowValueSchema,
} from "@/types/proto-es/v1/sql_service_pb";
import {
+ type ResultViewDetail,
SQLResultViewProvider,
useSelectionContext,
useSQLResultViewContext,
@@ -45,6 +50,14 @@ vi.mock("@/components/ui/tooltip", () => ({
Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
+vi.mock("@/modules/sql-editor/components/MaskingReasonPopover", () => ({
+ MaskingReasonPopover: () => null,
+}));
+
+vi.mock("@/utils/v1/database", () => ({
+ getInstanceResource: (database: Database) => database.instanceResource,
+}));
+
const textValue = (value: string): RowValue =>
create(RowValueSchema, {
kind: { case: "stringValue", value },
@@ -68,11 +81,31 @@ const rows: ResultTableRow[] = [
},
];
-function OpenDetailOnMount() {
+const databaseForEngine = (engine: Engine) =>
+ ({
+ name: "instances/prod/databases/main",
+ project: "projects/prod",
+ instanceResource: {
+ name: "instances/prod",
+ engine,
+ },
+ }) as Database;
+
+const resultForRows = (
+ panelRows: ResultTableRow[],
+ panelColumns: ResultTableColumn[]
+) =>
+ create(QueryResultSchema, {
+ columnNames: panelColumns.map((column) => column.name),
+ columnTypeNames: panelColumns.map((column) => column.columnType),
+ rows: panelRows.map((row) => row.item),
+ });
+
+function OpenDetailOnMount({ view }: Pick<ResultViewDetail, "view">) {
const { setDetail } = useSQLResultViewContext();
useEffect(() => {
- setDetail({ row: 0, col: 0 });
- }, [setDetail]);
+ setDetail({ row: 0, col: 0, view });
+ }, [setDetail, view]);
return null;
}
@@ -88,20 +121,32 @@ function TestDetailPanel({
disallowCopyingData = false,
panelRows = rows,
panelColumns = columns,
+ engine = Engine.POSTGRES,
+ sourceResult,
+ detailView = "cell",
}: {
disallowCopyingData?: boolean;
panelRows?: ResultTableRow[];
panelColumns?: ResultTableColumn[];
+ engine?: Engine;
+ sourceResult?: QueryResult;
+ detailView?: ResultViewDetail["view"];
}) {
+ const result = sourceResult ?? resultForRows(panelRows, panelColumns);
return (
<SQLResultViewProvider
- engine={Engine.POSTGRES}
+ engine={engine}
rows={panelRows}
columns={panelColumns}
disallowCopyingData={disallowCopyingData}
>
- <OpenDetailOnMount />
- <DetailPanel rows={panelRows} columns={panelColumns} />
+ <OpenDetailOnMount view={detailView} />
+ <DetailPanel
+ rows={panelRows}
+ columns={panelColumns}
+ database={databaseForEngine(engine)}
+ result={result}
+ />
</SQLResultViewProvider>
);
}
@@ -169,7 +214,7 @@ const waitForAssertion = async (assertion: () => void) => {
};
const getDetailSearchControl = (input: HTMLInputElement) => {
- const searchControl = input.closest("[data-testid='detail-search-control']");
+ const searchControl = input.parentElement;
expect(searchControl).toBeInstanceOf(HTMLDivElement);
return searchControl as HTMLDivElement;
};
@@ -204,6 +249,10 @@ describe("DetailPanel", () => {
const { render, unmount } = renderIntoContainer(<TestDetailPanel />);
render();
+ expect(document.body.textContent).toContain(
+ "sql-editor.result-detail.cell"
+ );
+ expect(document.body.textContent).toContain("common.column:payload");
expect(getDetailContentRegion().className).toContain("select-text");
unmount();
@@ -299,9 +348,7 @@ describe("DetailPanel", () => {
expect(marks.map((mark) => mark.textContent)).toEqual(["CREATE", "CREATE"]);
expect(document.body.textContent).toContain("1 / 2");
expect(marks[0]?.className).toContain("bg-accent");
- const searchControl = input!.closest(
- "[data-testid='detail-search-control']"
- );
+ const searchControl = getDetailSearchControl(input!);
expect(searchControl).toBeInstanceOf(HTMLDivElement);
expect(searchControl?.textContent).toContain("1 / 2");
expect(searchControl?.querySelectorAll("button")).toHaveLength(3);
@@ -431,6 +478,159 @@ describe("DetailPanel", () => {
unmount();
});
+ test("shows the original document as formatted JSON for a document table row", async () => {
+ const flattenedRows: ResultTableRow[] = [
+ {
+ key: 1,
+ item: create(QueryRowSchema, {
+ values: [textValue("two")],
+ }),
+ },
+ ];
+ const sourceResult = create(QueryResultSchema, {
+ columnNames: ["result"],
+ columnTypeNames: ["JSON"],
+ rows: [
+ create(QueryRowSchema, {
+ values: [
+ textValue('{"id":"one","profile":{"tags":["a","b"]}}'),
+ ],
+ }),
+ create(QueryRowSchema, {
+ values: [
+ textValue('{"id":"two","settings":{"theme":"dark"}}'),
+ ],
+ }),
+ ],
+ });
+ const { render, unmount } = renderIntoContainer(
+ <TestDetailPanel
+ panelRows={flattenedRows}
+ engine={Engine.COSMOSDB}
+ sourceResult={sourceResult}
+ detailView="row"
+ />
+ );
+ render();
+
+ await waitForAssertion(() => {
+ const contentRegion = getDetailContentRegion("settings");
+ expect(contentRegion.textContent).toContain("theme");
+ expect(contentRegion.textContent).toContain("dark");
+ });
+ expect(document.body.querySelector(".lucide-braces")).toBeNull();
+
+ unmount();
+ });
+
+ test("shows the clicked cell instead of the source document for cell detail", () => {
+ const flattenedRows: ResultTableRow[] = [
+ {
+ key: 0,
+ item: create(QueryRowSchema, {
+ values: [textValue('{"cell":"value"}')],
+ }),
+ },
+ ];
+ const sourceResult = create(QueryResultSchema, {
+ columnNames: ["result"],
+ columnTypeNames: ["JSON"],
+ rows: [
+ create(QueryRowSchema, {
+ values: [textValue('{"document":"source"}')],
+ }),
+ ],
+ });
+ const { render, unmount } = renderIntoContainer(
+ <TestDetailPanel
+ panelRows={flattenedRows}
+ engine={Engine.COSMOSDB}
+ sourceResult={sourceResult}
+ />
+ );
+ render();
+
+ const contentRegion = getDetailContentRegion("cell");
+ expect(contentRegion.textContent).toContain('{"cell":"value"}');
+ expect(contentRegion.textContent).not.toContain("source");
+
+ unmount();
+ });
+
+ test("shows every column and value for a relational table row", () => {
+ const rowColumns: ResultTableColumn[] = [
+ { id: "id", name: "id", columnType: "TEXT" },
+ { id: "name-1", name: "name", columnType: "TEXT" },
+ { id: "name-2", name: "name", columnType: "TEXT" },
+ { id: "environment", name: "environment", columnType: "TEXT" },
+ { id: "optional", name: "optional", columnType: "TEXT" },
+ ];
+ const rowRows: ResultTableRow[] = [
+ {
+ key: 0,
+ item: create(QueryRowSchema, {
+ values: [
+ textValue("1"),
+ textValue("Ada"),
+ textValue("Lovelace"),
+ create(RowValueSchema, {
+ kind: { case: "nullValue", value: NullValue.NULL_VALUE },
+ }),
+ create(RowValueSchema),
+ ],
+ }),
+ },
+ ];
+ const { render, unmount } = renderIntoContainer(
+ <TestDetailPanel
+ panelRows={rowRows}
+ panelColumns={rowColumns}
+ detailView="row"
+ />
+ );
+ render();
+
+ const contentRegion = getDetailContentRegion("id: 1");
+ expect(
+ contentRegion.querySelector('[data-testid="row-data-block"]')
+ ).toBeInstanceOf(HTMLDivElement);
+ expect(contentRegion.textContent).toContain("name: Ada");
+ expect(contentRegion.textContent).toContain("name: Lovelace");
+ expect(contentRegion.textContent).toContain("environment: NULL");
+ expect(contentRegion.textContent).toContain("optional: UNSET");
+ const placeholders = Array.from(contentRegion.querySelectorAll("span"))
+ .filter((element) => ["NULL", "UNSET"].includes(element.textContent ?? ""));
+ expect(placeholders).toHaveLength(2);
+ for (const placeholder of placeholders) {
+ expect(placeholder).toHaveClass("text-control-placeholder", "italic");
+ }
+
+ const input = document.body.querySelector(
+ "input[aria-label='sql-editor.result-detail.search']"
+ ) as HTMLInputElement;
+ act(() => {
+ setInputValue(input, "name");
+ });
+
+ let marks = Array.from(contentRegion.querySelectorAll("mark"));
+ expect(marks.map((mark) => mark.textContent)).toEqual(["name", "name"]);
+ expect(getDetailSearchControl(input).textContent).toContain("1 / 2");
+
+ act(() => {
+ input.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: "Enter",
+ bubbles: true,
+ cancelable: true,
+ })
+ );
+ });
+ marks = Array.from(contentRegion.querySelectorAll("mark"));
+ expect(marks[1]?.dataset.detailSearchActiveMatch).toBe("true");
+
+ unmount();
+ });
+
test("focuses detail search from the native find shortcut", () => {
const { render, unmount } = renderIntoContainer(<TestDetailPanel />);
render();
diff --git a/frontend/src/modules/sql-editor/components/ResultView/DetailPanel.tsx b/frontend/src/modules/sql-editor/components/ResultView/DetailPanel.tsx
index 9a5b511ada..639cee6174 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/DetailPanel.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/DetailPanel.tsx
@@ -8,41 +8,53 @@ import {
ChevronDownIcon,
ChevronUpIcon,
CopyIcon,
- SearchIcon,
WrapTextIcon,
- XIcon,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
import {
Sheet,
SheetContent,
+ SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import { Tooltip } from "@/components/ui/tooltip";
import { writeTextToClipboard } from "@/lib/clipboard";
import { cn } from "@/lib/utils";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import type {
+ MaskingReason,
+ QueryResult,
+} from "@/types/proto-es/v1/sql_service_pb";
import {
STORAGE_KEY_SQL_EDITOR_DETAIL_FORMAT,
STORAGE_KEY_SQL_EDITOR_DETAIL_LINE_WRAP,
} from "@/utils/storage-keys";
+import { getInstanceResource } from "@/utils/v1/database";
import { BinaryFormatButton } from "./BinaryFormatButton";
-import { getPlainValue } from "./cell-value";
+import { getPlainValue, isLikelyJSON } from "./cell-value";
import { useBinaryFormatContext, useSQLResultViewContext } from "./context";
import {
DETAIL_SEARCH_ACTIVE_MATCH_SELECTOR,
+ renderRowFieldsWithSearchMatches,
renderTextWithSearchMatches,
- searchMatchCountLabel,
} from "./detail-panel-search";
+import { getCellDisplayText, PlainCellValue } from "./PlainCellValue";
import { PrettyJSON } from "./PrettyJSON";
+import { RowDataBlock } from "./RowDataBlock";
+import { TextSearchControl } from "./TextSearchControl";
import type { ResultTableColumn, ResultTableRow } from "./types";
interface DetailPanelProps {
rows: ResultTableRow[];
columns: ResultTableColumn[];
+ database: Database;
+ result: QueryResult;
+ statement?: string;
+ getMaskingReason?: (index: number) => MaskingReason | undefined;
}
function useLocalStorageBoolean(
@@ -86,16 +98,22 @@ const isEditableTarget = (target: EventTarget | null) => {
);
};
-export function DetailPanel({ rows, columns }: DetailPanelProps) {
+export function DetailPanel({
+ rows,
+ columns,
+ database,
+ result,
+ statement,
+ getMaskingReason,
+}: DetailPanelProps) {
const { t } = useTranslation();
const { detail, disallowCopyingData, setDetail } = useSQLResultViewContext();
const { getBinaryFormat, setBinaryFormat } = useBinaryFormatContext();
const [copied, setCopied] = useState(false);
const [searchQuery, setSearchQuery] = useState("");
const [activeMatchIndex, setActiveMatchIndex] = useState(0);
- const [matchCount, setMatchCount] = useState(0);
+ const [formattedMatchCount, setFormattedMatchCount] = useState(0);
const [highlightedContentVersion, setHighlightedContentVersion] = useState(0);
- const searchInputRef = useRef<HTMLInputElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const [format, setFormat] = useLocalStorageBoolean(
@@ -109,32 +127,98 @@ export function DetailPanel({ rows, columns }: DetailPanelProps) {
const totalCount = rows.length;
- const rawValue = useMemo(() => {
- if (!detail) return undefined;
- return rows[detail.row]?.item.values[detail.col];
- }, [detail, rows]);
-
- const columnType = detail ? (columns[detail.col]?.columnType ?? "") : "";
-
- const binaryFormat = detail
- ? getBinaryFormat({ rowIndex: detail.row, colIndex: detail.col })
- : undefined;
+ const engine = getInstanceResource(database).engine;
+ const isDocumentEngine =
+ engine === Engine.COSMOSDB || engine === Engine.MONGODB;
- const isBinaryData = rawValue?.kind?.case === "bytesValue";
+ const detailContent = useMemo(() => {
+ if (!detail) return undefined;
+ const displayedRow = rows[detail.row];
+ if (!displayedRow) return undefined;
+
+ if (detail.view === "row") {
+ if (isDocumentEngine) {
+ const sourceValue = result.rows[displayedRow.key]?.values[0];
+ return {
+ kind: "document" as const,
+ content: getPlainValue(
+ sourceValue,
+ result.columnTypeNames[0] ?? "",
+ undefined
+ ),
+ };
+ }
- const content = useMemo(
- () => getPlainValue(rawValue, columnType, binaryFormat),
- [rawValue, columnType, binaryFormat]
- );
+ const fields = columns.map((column, colIndex) => ({
+ column,
+ value: getPlainValue(
+ displayedRow.item.values[colIndex],
+ column.columnType,
+ getBinaryFormat({ rowIndex: detail.row, colIndex })
+ ),
+ }));
+ return {
+ kind: "row" as const,
+ fields,
+ content: fields
+ .map(
+ ({ column, value }) =>
+ `${column.name}: ${getCellDisplayText(value)}`
+ )
+ .join("\n"),
+ };
+ }
- const guessedIsJSON = useMemo(() => {
- if (!content) return false;
- const trimmed = content.trim();
- return (
- (trimmed.startsWith("{") && trimmed.endsWith("}")) ||
- (trimmed.startsWith("[") && trimmed.endsWith("]"))
- );
- }, [content]);
+ const value = displayedRow.item.values[detail.col];
+ const columnType = columns[detail.col]?.columnType ?? "";
+ const binaryFormat = getBinaryFormat({
+ rowIndex: detail.row,
+ colIndex: detail.col,
+ });
+ return {
+ kind: "cell" as const,
+ value,
+ binaryFormat,
+ content: getPlainValue(value, columnType, binaryFormat),
+ };
+ }, [columns, detail, getBinaryFormat, isDocumentEngine, result, rows]);
+
+ const content = detailContent?.content;
+
+ const guessedIsJSON = isLikelyJSON(content);
+ const showFormattedJSON =
+ guessedIsJSON &&
+ (detailContent?.kind === "document" ||
+ (detailContent?.kind === "cell" && format));
+
+ const searchResult = useMemo(() => {
+ if (detailContent?.kind === "row") {
+ return {
+ kind: "row" as const,
+ ...renderRowFieldsWithSearchMatches(
+ detailContent.fields.map(({ column, value }) => ({
+ columnName: column.name,
+ value: getCellDisplayText(value),
+ })),
+ searchQuery,
+ activeMatchIndex
+ ),
+ };
+ }
+ return {
+ kind: "plain" as const,
+ ...renderTextWithSearchMatches(
+ content ?? "",
+ searchQuery,
+ activeMatchIndex
+ ),
+ };
+ }, [activeMatchIndex, content, detailContent, searchQuery]);
+ const matchCount = showFormattedJSON
+ ? formattedMatchCount
+ : searchResult.count;
+ const rowSearchFields =
+ searchResult.kind === "row" ? searchResult.fields : [];
const move = useCallback(
(offset: number) => {
@@ -180,23 +264,9 @@ export function DetailPanel({ rows, columns }: DetailPanelProps) {
return () => document.removeEventListener("keydown", handler);
}, [detail, move]);
- useEffect(() => {
- if (!detail) return;
- const handler = (e: KeyboardEvent) => {
- if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "f") {
- e.preventDefault();
- e.stopPropagation();
- searchInputRef.current?.focus();
- searchInputRef.current?.select();
- }
- };
- document.addEventListener("keydown", handler);
- return () => document.removeEventListener("keydown", handler);
- }, [detail]);
-
useEffect(() => {
setActiveMatchIndex(0);
- }, [content, format, searchQuery]);
+ }, [content, detailContent?.kind, format, searchQuery]);
useEffect(() => {
if (matchCount === 0) {
@@ -226,7 +296,7 @@ export function DetailPanel({ rows, columns }: DetailPanelProps) {
const copyContent = useMemo(() => {
const raw = content ?? "";
- if (guessedIsJSON && format) {
+ if (showFormattedJSON) {
try {
const obj = losslessParse(raw);
return losslessStringify(obj, null, " ") ?? raw;
@@ -236,7 +306,7 @@ export function DetailPanel({ rows, columns }: DetailPanelProps) {
}
}
return raw;
- }, [content, guessedIsJSON, format]);
+ }, [content, showFormattedJSON]);
const handleCopy = useCallback(async () => {
if (await writeTextToClipboard(copyContent)) {
@@ -258,42 +328,31 @@ export function DetailPanel({ rows, columns }: DetailPanelProps) {
}
};
- const plainSearchResult = useMemo(
- () =>
- renderTextWithSearchMatches(content ?? "", searchQuery, activeMatchIndex),
- [activeMatchIndex, content, searchQuery]
- );
-
const handleHighlightedContentChange = useCallback(() => {
setHighlightedContentVersion((version) => version + 1);
}, []);
-
- useEffect(() => {
- if (!(guessedIsJSON && format)) {
- setMatchCount(plainSearchResult.count);
- }
- }, [format, guessedIsJSON, plainSearchResult.count]);
-
- const handleSearchKeyDown = (
- event: React.KeyboardEvent<HTMLInputElement>
- ) => {
- if (event.key !== "Enter") {
- return;
- }
- event.preventDefault();
- moveSearchMatch(event.shiftKey ? -1 : 1);
- };
-
- const clearSearch = () => {
- setSearchQuery("");
- searchInputRef.current?.focus();
- };
+ const selectedColumnName =
+ detail?.view === "cell" ? columns[detail.col]?.name : undefined;
return (
<Sheet open={isOpen} onOpenChange={handleOpenChange}>
<SheetContent width="standard">
<SheetHeader>
- <SheetTitle>{t("common.detail")}</SheetTitle>
+ <SheetTitle>
+ {detail?.view === "cell"
+ ? t("sql-editor.result-detail.cell")
+ : t("common.detail")}
+ </SheetTitle>
+ {selectedColumnName && (
+ <SheetDescription className="flex min-w-0 items-center gap-x-1">
+ <span className="shrink-0">{t("common.column")}:</span>
+ <Tooltip content={selectedColumnName} delayDuration={500}>
+ <span className="block max-w-[32rem] truncate font-mono text-control">
+ {selectedColumnName}
+ </span>
+ </Tooltip>
+ </SheetDescription>
+ )}
</SheetHeader>
{detail && (
<div
@@ -345,74 +404,18 @@ export function DetailPanel({ rows, columns }: DetailPanelProps) {
</div>
<div className="flex min-w-0 items-center gap-x-2">
- <div
- data-testid="detail-search-control"
- className={cn(
- "h-8 w-80 min-w-0 flex items-center overflow-hidden rounded-xs",
- "border border-control-border bg-transparent text-main transition-colors"
- )}
- >
- <SearchIcon className="ml-2.5 size-4 shrink-0 text-control-placeholder" />
- <Input
- ref={searchInputRef}
- size="sm"
- aria-label={t("sql-editor.result-detail.search")}
- className="h-7 min-w-0 flex-1 border-0 px-2 text-sm focus:ring-0"
- placeholder={t("sql-editor.result-detail.search")}
- value={searchQuery}
- autoComplete="off"
- onChange={(event) => setSearchQuery(event.target.value)}
- onKeyDown={handleSearchKeyDown}
- />
- {searchQuery.trim() && (
- <span className="min-w-10 text-center text-xs text-control-light">
- {searchMatchCountLabel(activeMatchIndex, matchCount)}
- </span>
- )}
- {searchQuery.trim() && (
- <div className="ml-1 flex shrink-0 items-center">
- <Tooltip
- content={t("sql-editor.result-detail.previous-match")}
- >
- <Button
- size="sm"
- appearance="secondary"
- className="size-7 p-0"
- disabled={matchCount === 0}
- onClick={() => moveSearchMatch(-1)}
- >
- <ChevronUpIcon className="size-4" />
- </Button>
- </Tooltip>
- <Tooltip
- content={t("sql-editor.result-detail.next-match")}
- >
- <Button
- size="sm"
- appearance="secondary"
- className="size-7 p-0"
- disabled={matchCount === 0}
- onClick={() => moveSearchMatch(1)}
- >
- <ChevronDownIcon className="size-4" />
- </Button>
- </Tooltip>
- <Tooltip content={t("common.close")}>
- <Button
- size="sm"
- appearance="secondary"
- className="size-7 border-l border-control-border p-0"
- onClick={clearSearch}
- >
- <XIcon className="size-4" />
- </Button>
- </Tooltip>
- </div>
- )}
- </div>
+ <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 && (
+ {guessedIsJSON && detailContent?.kind === "cell" && (
<Tooltip content={t("sql-editor.format")}>
<Button
size="sm"
@@ -425,18 +428,19 @@ export function DetailPanel({ rows, columns }: DetailPanelProps) {
</Tooltip>
)}
- {isBinaryData && (
- <BinaryFormatButton
- format={binaryFormat}
- onFormatChange={(next) =>
- setBinaryFormat({
- rowIndex: detail.row,
- colIndex: detail.col,
- format: next,
- })
- }
- />
- )}
+ {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")}>
@@ -463,13 +467,32 @@ export function DetailPanel({ rows, columns }: DetailPanelProps) {
className={cn(
"flex-1 overflow-auto text-sm font-mono border p-2 relative",
disallowCopyingData ? "select-none" : "select-text",
- guessedIsJSON && format && !wrap
+ showFormattedJSON && !wrap
? "whitespace-pre"
: "whitespace-pre-wrap"
)}
onClick={stopSelectionClickPropagation}
>
- {guessedIsJSON && format ? (
+ {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")}>
@@ -487,12 +510,12 @@ export function DetailPanel({ rows, columns }: DetailPanelProps) {
content={content ?? ""}
searchQuery={searchQuery}
activeMatchIndex={activeMatchIndex}
- onMatchCountChange={setMatchCount}
+ onMatchCountChange={setFormattedMatchCount}
onHighlightedContentChange={handleHighlightedContentChange}
/>
</>
) : content && content.length > 0 ? (
- <>{plainSearchResult.nodes}</>
+ <>{searchResult.kind === "plain" ? searchResult.nodes : null}</>
) : (
<br style={{ minWidth: "1rem", display: "inline-flex" }} />
)}
diff --git a/frontend/src/modules/sql-editor/components/ResultView/DocumentJSONView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/DocumentJSONView.test.tsx
index 26a7667eff..492e12ef6e 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/DocumentJSONView.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/DocumentJSONView.test.tsx
@@ -1,6 +1,12 @@
+import { create } from "@bufbuild/protobuf";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { useEffect } from "react";
import { beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ QueryResultSchema,
+ QueryRowSchema,
+ RowValueSchema,
+} from "@/types/proto-es/v1/sql_service_pb";
import { DocumentJSONView } from "./DocumentJSONView";
const {
@@ -63,6 +69,21 @@ vi.mock("@/components/monaco/MonacoEditor", () => ({
},
}));
+const documentResult = (documents: string[]) =>
+ create(QueryResultSchema, {
+ columnNames: ["result"],
+ columnTypeNames: ["JSON"],
+ rows: documents.map((document) =>
+ create(QueryRowSchema, {
+ values: [
+ create(RowValueSchema, {
+ kind: { case: "stringValue", value: document },
+ }),
+ ],
+ })
+ ),
+ });
+
describe("DocumentJSONView", () => {
beforeEach(() => {
handlers.mouseMove = undefined;
@@ -75,13 +96,12 @@ describe("DocumentJSONView", () => {
render(
<DocumentJSONView
- content={content}
+ result={documentResult(['{"id":"one"}'])}
disallowCopyingData={false}
compact={false}
searchQuery=""
activeMatchIndex={0}
onMatchCountChange={vi.fn()}
- documents={[]}
/>
);
@@ -101,13 +121,12 @@ describe("DocumentJSONView", () => {
test("prevents native copy events when result copying is disabled", () => {
const { rerender } = render(
<DocumentJSONView
- content="[]"
+ result={documentResult([])}
disallowCopyingData
compact={false}
searchQuery=""
activeMatchIndex={0}
onMatchCountChange={vi.fn()}
- documents={[]}
/>
);
@@ -120,13 +139,12 @@ describe("DocumentJSONView", () => {
rerender(
<DocumentJSONView
- content="[]"
+ result={documentResult([])}
disallowCopyingData={false}
compact={false}
searchQuery=""
activeMatchIndex={0}
onMatchCountChange={vi.fn()}
- documents={[]}
/>
);
const allowedEvent = new Event("copy", {
@@ -138,15 +156,12 @@ describe("DocumentJSONView", () => {
});
test("copies the top-level document under the pointer", async () => {
- const document = {
- content: '{\n "id": "one"\n}',
- startLineNumber: 2,
- endLineNumber: 4,
- };
+ const firstDocument = '{\n "id": "one"\n}';
+ const secondDocument = '{\n "id": "two"\n}';
+ const result = documentResult(['{"id":"one"}', '{"id":"two"}']);
const view = render(
<DocumentJSONView
- content={`[\n ${document.content.replaceAll("\n", "\n ")}\n]`}
- documents={[document]}
+ result={result}
disallowCopyingData={false}
compact={false}
searchQuery=""
@@ -157,18 +172,30 @@ describe("DocumentJSONView", () => {
await waitFor(() => expect(onMouseMove).toHaveBeenCalled());
act(() => {
- handlers.mouseMove?.({ target: { position: { lineNumber: 3 } } });
+ handlers.mouseMove?.({ target: { position: { lineNumber: 6 } } });
});
const copyButton = screen.getByRole("button", { name: "common.copy" });
expect(copyButton.parentElement?.parentElement).toHaveStyle({ left: "6px" });
fireEvent.click(copyButton);
- expect(writeTextToClipboard).toHaveBeenCalledWith(document.content);
+ expect(writeTextToClipboard).toHaveBeenCalledWith(secondDocument);
+
+ act(() => {
+ handlers.mouseMove?.({ target: { position: { lineNumber: 1 } } });
+ });
+ expect(
+ screen.queryByRole("button", { name: "common.copy" })
+ ).not.toBeInTheDocument();
+
+ act(() => {
+ handlers.mouseMove?.({ target: { position: { lineNumber: 3 } } });
+ });
+ fireEvent.click(screen.getByRole("button", { name: "common.copy" }));
+ expect(writeTextToClipboard).toHaveBeenLastCalledWith(firstDocument);
view.rerender(
<DocumentJSONView
- content={`[\n ${document.content.replaceAll("\n", "\n ")}\n]`}
- documents={[document]}
+ result={result}
disallowCopyingData
compact={false}
searchQuery=""
diff --git a/frontend/src/modules/sql-editor/components/ResultView/DocumentJSONView.tsx b/frontend/src/modules/sql-editor/components/ResultView/DocumentJSONView.tsx
index 384b79f35e..61e70a5c16 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/DocumentJSONView.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/DocumentJSONView.tsx
@@ -1,5 +1,5 @@
import { CheckIcon, CopyIcon } from "lucide-react";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { MonacoEditor } from "@/components/monaco/MonacoEditor";
import type {
@@ -11,12 +11,15 @@ import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
import { writeTextToClipboard } from "@/lib/clipboard";
import { cn } from "@/lib/utils";
-import type { NoSQLJSONDocument } from "@/utils/sqlResult";
+import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";
+import {
+ formatNoSQLQueryResultForJSONView,
+ type NoSQLJSONDocument,
+} from "@/utils/sqlResult";
import { normalizeSearchQuery } from "./detail-panel-search";
interface DocumentJSONViewProps {
- content: string;
- documents: NoSQLJSONDocument[];
+ result: QueryResult;
disallowCopyingData: boolean;
compact: boolean;
searchQuery: string;
@@ -24,9 +27,30 @@ interface DocumentJSONViewProps {
onMatchCountChange: (count: number) => void;
}
+const findDocumentIndex = (
+ documents: NoSQLJSONDocument[],
+ lineNumber: number
+) => {
+ let low = 0;
+ let high = documents.length - 1;
+
+ while (low <= high) {
+ const middle = Math.floor((low + high) / 2);
+ const document = documents[middle];
+ if (lineNumber < document.startLineNumber) {
+ high = middle - 1;
+ } else if (lineNumber > document.endLineNumber) {
+ low = middle + 1;
+ } else {
+ return middle;
+ }
+ }
+
+ return -1;
+};
+
export function DocumentJSONView({
- content,
- documents,
+ result,
disallowCopyingData,
compact,
searchQuery,
@@ -34,6 +58,14 @@ export function DocumentJSONView({
onMatchCountChange,
}: DocumentJSONViewProps) {
const { t } = useTranslation();
+ const { content, documents } = useMemo(
+ () =>
+ formatNoSQLQueryResultForJSONView(result) ?? {
+ content: "[]",
+ documents: [],
+ },
+ [result]
+ );
const [editor, setEditor] = useState<IStandaloneCodeEditor | null>(null);
const [copyAction, setCopyAction] = useState<{
documentIndex: number;
@@ -119,11 +151,7 @@ export function DocumentJSONView({
setCopyAction(undefined);
return;
}
- const documentIndex = documents.findIndex(
- (document) =>
- lineNumber >= document.startLineNumber &&
- lineNumber <= document.endLineNumber
- );
+ const documentIndex = findDocumentIndex(documents, lineNumber);
if (documentIndex < 0) {
setCopyAction(undefined);
return;
@@ -131,7 +159,7 @@ export function DocumentJSONView({
const document = documents[documentIndex];
const layout = editor.getLayoutInfo();
- setCopyAction({
+ const next = {
documentIndex,
left:
layout.glyphMarginLeft +
@@ -140,7 +168,14 @@ export function DocumentJSONView({
top:
editor.getTopForLineNumber(document.startLineNumber) -
editor.getScrollTop(),
- });
+ };
+ setCopyAction((current) =>
+ current?.documentIndex === next.documentIndex &&
+ current.left === next.left &&
+ current.top === next.top
+ ? current
+ : next
+ );
},
[disallowCopyingData, documents, editor]
);
diff --git a/frontend/src/modules/sql-editor/components/ResultView/PlainCellValue.tsx b/frontend/src/modules/sql-editor/components/ResultView/PlainCellValue.tsx
new file mode 100644
index 0000000000..d21a199a6a
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/ResultView/PlainCellValue.tsx
@@ -0,0 +1,26 @@
+import type { ReactNode } from "react";
+
+interface PlainCellValueProps {
+ value: string | null | undefined;
+ children?: ReactNode;
+}
+
+export const getCellDisplayText = (value: string | null | undefined) => {
+ if (value === undefined) return "UNSET";
+ if (value === null) return "NULL";
+ return value;
+};
+
+export function PlainCellValue({ value, children }: PlainCellValueProps) {
+ if (value === undefined || value === null) {
+ return (
+ <span className="text-control-placeholder italic">
+ {children ?? getCellDisplayText(value)}
+ </span>
+ );
+ }
+ if (value.length === 0) {
+ return <br style={{ minWidth: "1rem", display: "inline-flex" }} />;
+ }
+ return <>{children ?? value}</>;
+}
diff --git a/frontend/src/modules/sql-editor/components/ResultView/RowDataBlock.tsx b/frontend/src/modules/sql-editor/components/ResultView/RowDataBlock.tsx
new file mode 100644
index 0000000000..16e09badc1
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/ResultView/RowDataBlock.tsx
@@ -0,0 +1,62 @@
+import type { ReactNode } from "react";
+import { cn } from "@/lib/utils";
+import { MaskingReasonPopover } from "@/modules/sql-editor/components/MaskingReasonPopover";
+import type { MaskingReason } from "@/types/proto-es/v1/sql_service_pb";
+import type { ResultTableColumn } from "./types";
+
+interface RowDataBlockProps {
+ columns: ResultTableColumn[];
+ database: string;
+ statement?: string;
+ getMaskingReason?: (index: number) => MaskingReason | undefined;
+ renderColumnName?: (column: ResultTableColumn, index: number) => ReactNode;
+ renderValue: (column: ResultTableColumn, index: number) => ReactNode;
+ actions?: ReactNode;
+ className?: string;
+}
+
+export function RowDataBlock({
+ columns,
+ database,
+ statement,
+ getMaskingReason,
+ renderColumnName = (column) => column.name,
+ renderValue,
+ actions,
+ className,
+}: RowDataBlockProps) {
+ return (
+ <div
+ data-testid="row-data-block"
+ className={cn("relative rounded bg-control-bg/40 px-3 py-2", className)}
+ >
+ {actions}
+ {columns.map((column, columnIndex) => {
+ const reason = getMaskingReason?.(columnIndex);
+ return (
+ <div
+ key={`${column.id}-${columnIndex}`}
+ className="flex items-start text-sm text-control-light"
+ >
+ <div className="flex min-w-28 items-center pt-1 text-left font-medium">
+ <div className="flex items-center gap-x-1">
+ {renderColumnName(column, columnIndex)}
+ {reason && (
+ <MaskingReasonPopover
+ reason={reason}
+ statement={statement}
+ database={database}
+ />
+ )}
+ </div>
+ {": "}
+ </div>
+ <div className="min-w-0 flex-1">
+ {renderValue(column, columnIndex)}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
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 180e1cab4c..ba9c03570e 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx
@@ -221,7 +221,12 @@ vi.mock("@/utils/v1/sql", () => ({
}));
vi.mock("./DetailPanel", () => ({
- DetailPanel: () => <div data-testid="detail-panel" />,
+ DetailPanel: ({ result }: { result: { rows: unknown[] } }) => (
+ <div
+ data-testid="detail-panel"
+ data-result-row-count={result.rows.length}
+ />
+ ),
}));
vi.mock("./context", () => ({
@@ -372,6 +377,10 @@ describe("SingleResultView document view", () => {
"id,profile,ssn"
);
expect(screen.getByTestId("result-table")).toHaveTextContent("******");
+ expect(screen.getByTestId("detail-panel")).toHaveAttribute(
+ "data-result-row-count",
+ "1"
+ );
}
);
@@ -396,6 +405,27 @@ describe("SingleResultView document view", () => {
).toBeInTheDocument();
});
+ test("shows an empty document result in JSON view", () => {
+ render(
+ <SingleResultView
+ disallowCopyingData
+ params={params}
+ database={databaseForEngine(Engine.COSMOSDB)}
+ result={
+ create(QueryResultSchema, {
+ columnNames: ["result"],
+ columnTypeNames: ["JSON"],
+ })
+ }
+ showExport={false}
+ />
+ );
+
+ expect(
+ screen.getByRole("region", { name: "sql-editor.json-view" })
+ ).toHaveTextContent("[]");
+ });
+
test("does not offer JSON mode for relational or malformed results", () => {
const relationalResult = create(QueryResultSchema, {
columnNames: ["name"],
diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx
index 0d10ae4e5e..6dd2993e4d 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx
@@ -64,8 +64,8 @@ import { createExplainToken } from "@/utils/pev2";
import {
flattenElasticsearchSearchResult,
flattenNoSQLQueryResult,
- formatNoSQLQueryResultForJSONView,
- type NoSQLJSONDocument,
+ formatNoSQLQueryResultAsJSON,
+ isNoSQLQueryResult,
} from "@/utils/sqlResult";
import { STORAGE_KEY_SQL_EDITOR_NOSQL_TABLE_VIEW } from "@/utils/storage-keys";
import { isNullOrUndefined } from "@/utils/util";
@@ -129,7 +129,8 @@ export function SingleResultView(props: SingleResultViewProps) {
STORAGE_KEY_SQL_EDITOR_NOSQL_TABLE_VIEW,
true
);
- const [documentTableView, setDocumentTableView] = useState(false);
+ const [documentViewMode, setDocumentViewMode] =
+ useState<DocumentViewMode>("JSON");
// Sort state lives at this level (not inside the inner component) so the
// sorted `rows` we feed into the provider are the same array the user
// sees in the table. The provider's selection-copy logic dereferences
@@ -139,25 +140,22 @@ export function SingleResultView(props: SingleResultViewProps) {
const isDocumentEngine =
engine === Engine.COSMOSDB || engine === Engine.MONGODB;
+ const supportsDocumentJSONView = useMemo(
+ () => isDocumentEngine && isNoSQLQueryResult(result),
+ [isDocumentEngine, result]
+ );
+ const activeDocumentViewMode = supportsDocumentJSONView
+ ? documentViewMode
+ : "TABLE";
const flattened = useMemo(() => {
if (engine === Engine.ELASTICSEARCH) {
return flattenElasticsearchSearchResult(result);
}
- if (isDocumentEngine) {
+ if (isDocumentEngine && activeDocumentViewMode === "TABLE") {
return flattenNoSQLQueryResult(result);
}
return undefined;
- }, [engine, isDocumentEngine, result]);
- const documentJSONViewResult = useMemo(
- () =>
- isDocumentEngine ? formatNoSQLQueryResultForJSONView(result) : undefined,
- [isDocumentEngine, result]
- );
- const documentJSON = documentJSONViewResult?.content;
- const supportsDocumentJSONView =
- isDocumentEngine && flattened !== undefined && documentJSON !== undefined;
- const documentViewMode: DocumentViewMode =
- supportsDocumentJSONView && !documentTableView ? "JSON" : "TABLE";
+ }, [activeDocumentViewMode, engine, isDocumentEngine, result]);
const supportsTableViewToggle =
engine === Engine.ELASTICSEARCH && flattened !== undefined;
const activeResult = isDocumentEngine
@@ -201,11 +199,11 @@ export function SingleResultView(props: SingleResultViewProps) {
});
}, [baseRows, sortState, columns]);
- // Reset sort whenever the user toggles the NoSQL table-view switch:
+ // Reset sort whenever the user toggles a NoSQL view:
// column indices don't carry over between flattened/raw shapes.
useEffect(() => {
setSortState(undefined);
- }, [noSQLTableView]);
+ }, [activeDocumentViewMode, noSQLTableView]);
const toggleSort = useCallback((columnIndex: number) => {
setSortState((current) => {
@@ -230,7 +228,6 @@ export function SingleResultView(props: SingleResultViewProps) {
<SingleResultViewInner
{...props}
engine={engine}
- activeResult={activeResult}
columns={columns}
rows={rows}
sortState={sortState}
@@ -240,10 +237,8 @@ export function SingleResultView(props: SingleResultViewProps) {
noSQLTableView={noSQLTableView}
setNoSQLTableView={setNoSQLTableView}
supportsDocumentJSONView={supportsDocumentJSONView}
- documentJSON={documentJSON}
- documentJSONDocuments={documentJSONViewResult?.documents ?? []}
- documentViewMode={documentViewMode}
- setDocumentViewMode={(mode) => setDocumentTableView(mode === "TABLE")}
+ documentViewMode={activeDocumentViewMode}
+ setDocumentViewMode={setDocumentViewMode}
/>
</SQLResultViewProvider>
);
@@ -251,7 +246,6 @@ export function SingleResultView(props: SingleResultViewProps) {
interface SingleResultViewInnerProps extends SingleResultViewProps {
engine: Engine;
- activeResult: QueryResult;
columns: ResultTableColumn[];
rows: ResultTableRow[];
sortState: SortState | undefined;
@@ -261,8 +255,6 @@ interface SingleResultViewInnerProps extends SingleResultViewProps {
noSQLTableView: boolean;
setNoSQLTableView: (next: boolean) => void;
supportsDocumentJSONView: boolean;
- documentJSON: string | undefined;
- documentJSONDocuments: NoSQLJSONDocument[];
documentViewMode: DocumentViewMode;
setDocumentViewMode: (mode: DocumentViewMode) => void;
}
@@ -278,7 +270,6 @@ function SingleResultViewInner({
onExport,
requestExportSlot,
engine,
- activeResult: _activeResult,
columns,
rows,
sortState,
@@ -288,8 +279,6 @@ function SingleResultViewInner({
noSQLTableView,
setNoSQLTableView,
supportsDocumentJSONView,
- documentJSON,
- documentJSONDocuments,
documentViewMode,
setDocumentViewMode,
compact = false,
@@ -337,7 +326,7 @@ function SingleResultViewInner({
setDocumentSearchQuery("");
setDocumentSearchActiveIndex(0);
setDocumentSearchMatchCount(0);
- }, [documentJSON]);
+ }, [result]);
useEffect(() => {
setDocumentSearchActiveIndex(0);
@@ -499,20 +488,6 @@ function SingleResultViewInner({
currentTabMode !== "ADMIN" &&
(rows.length === resultRowsLimit || rows.length === policyMaxRows);
- const isSensitiveColumn = useCallback(
- (columnIndex: number): boolean => {
- if (flattenedTableView) return false;
- const reason = result.masked?.[columnIndex];
- return (
- reason !== null &&
- reason !== undefined &&
- reason.semanticTypeId !== undefined &&
- reason.semanticTypeId !== ""
- );
- },
- [flattenedTableView, result.masked]
- );
-
const getMaskingReason = useCallback(
(columnIndex: number) => {
if (flattenedTableView) return undefined;
@@ -558,10 +533,7 @@ function SingleResultViewInner({
}, [result]);
const resultRowsText = `${rows.length} ${t("sql-editor.rows.self")}`;
- const isJSONView =
- supportsDocumentJSONView &&
- documentViewMode === "JSON" &&
- documentJSON !== undefined;
+ const isJSONView = supportsDocumentJSONView && documentViewMode === "JSON";
const moveDocumentSearchMatch = (offset: number) => {
if (documentSearchMatchCount === 0) {
return;
@@ -583,10 +555,13 @@ function SingleResultViewInner({
};
const handleCopyJSON = () => {
- if (disallowCopyingData || !documentJSON) {
+ if (disallowCopyingData) {
return;
}
- void writeTextToClipboard(documentJSON);
+ const content = formatNoSQLQueryResultAsJSON(result);
+ if (content) {
+ void writeTextToClipboard(content);
+ }
};
// ---- Render branches by viewMode ----
@@ -800,8 +775,7 @@ function SingleResultViewInner({
{/* Body */}
{isJSONView ? (
<DocumentJSONView
- content={documentJSON}
- documents={documentJSONDocuments}
+ result={result}
disallowCopyingData={disallowCopyingData}
compact={compact}
searchQuery={documentSearchQuery}
@@ -822,7 +796,6 @@ function SingleResultViewInner({
ref={dataTableRef as React.RefObject<VirtualDataBlockHandle>}
rows={rows}
columns={columns}
- isSensitiveColumn={isSensitiveColumn}
getMaskingReason={getMaskingReason}
database={database}
statement={params.statement}
@@ -834,7 +807,6 @@ function SingleResultViewInner({
ref={dataTableRef as React.RefObject<VirtualDataTableHandle>}
rows={rows}
columns={columns}
- isSensitiveColumn={isSensitiveColumn}
getMaskingReason={getMaskingReason}
database={database}
statement={params.statement}
@@ -922,7 +894,16 @@ function SingleResultViewInner({
</>
)}
- {!isJSONView && <DetailPanel rows={rows} columns={columns} />}
+ {!isJSONView && (
+ <DetailPanel
+ rows={rows}
+ columns={columns}
+ database={database}
+ result={result}
+ statement={result.statement}
+ getMaskingReason={getMaskingReason}
+ />
+ )}
</>
);
}
diff --git a/frontend/src/modules/sql-editor/components/ResultView/TableCell.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/TableCell.test.tsx
index efe3e0ca9b..30b27080f9 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/TableCell.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/TableCell.test.tsx
@@ -1,13 +1,15 @@
import { create } from "@bufbuild/protobuf";
-import { render, screen } from "@testing-library/react";
+import { fireEvent, render, screen } from "@testing-library/react";
import { afterEach, 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 {
QueryRowSchema,
RowValueSchema,
} from "@/types/proto-es/v1/sql_service_pb";
-import { SQLResultViewProvider } from "./context";
+import {
+ SQLResultViewProvider,
+ useSQLResultViewContext,
+} from "./context";
import { TableCell } from "./TableCell";
import type { ResultTableColumn, ResultTableRow } from "./types";
@@ -19,13 +21,6 @@ vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
-vi.mock("@/utils/v1/database", () => ({
- getInstanceResource: () => ({
- name: "instances/prod",
- engine: Engine.POSTGRES,
- }),
-}));
-
class ResizeObserverStub implements ResizeObserver {
private readonly callback: ResizeObserverCallback;
@@ -44,15 +39,6 @@ class ResizeObserverStub implements ResizeObserver {
globalThis.ResizeObserver = ResizeObserverStub;
-const database = {
- name: "instances/prod/databases/main",
- project: "projects/prod",
- instanceResource: {
- name: "instances/prod",
- engine: Engine.POSTGRES,
- },
-} as Database;
-
const columns: ResultTableColumn[] = [
{ id: "created_at", name: "created_at", columnType: "TEXT" },
];
@@ -64,6 +50,9 @@ const value = create(RowValueSchema, {
const indentedValue = create(RowValueSchema, {
kind: { case: "stringValue", value: " -> Seq Scan on project" },
});
+const jsonValue = create(RowValueSchema, {
+ kind: { case: "stringValue", value: '{"name":"Ada"}' },
+});
const rows: ResultTableRow[] = [
{
@@ -74,9 +63,18 @@ const rows: ResultTableRow[] = [
},
];
+function DetailProbe() {
+ const { detail } = useSQLResultViewContext();
+ return (
+ <div data-testid="detail-state">
+ {detail ? `${detail.row}:${detail.col}:${detail.view}` : "closed"}
+ </div>
+ );
+}
+
describe("TableCell", () => {
beforeEach(() => {
- vi.spyOn(HTMLElement.prototype, "scrollWidth", "get").mockReturnValue(160);
+ vi.spyOn(HTMLElement.prototype, "scrollWidth", "get").mockReturnValue(80);
vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(80);
vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockReturnValue(20);
vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(20);
@@ -87,6 +85,8 @@ describe("TableCell", () => {
});
test("reserves space for the expand action when cell content is truncated", async () => {
+ vi.spyOn(HTMLElement.prototype, "scrollWidth", "get").mockReturnValue(160);
+
const { container } = render(
<SQLResultViewProvider
engine={Engine.POSTGRES}
@@ -99,7 +99,6 @@ describe("TableCell", () => {
colIndex={0}
allowSelect
columnType="TEXT"
- database={database}
keyword=""
/>
</SQLResultViewProvider>
@@ -111,6 +110,31 @@ describe("TableCell", () => {
);
});
+ test("shows the expand action for non-truncated JSON content", async () => {
+ render(
+ <SQLResultViewProvider
+ engine={Engine.POSTGRES}
+ rows={rows}
+ columns={columns}
+ >
+ <TableCell
+ value={jsonValue}
+ rowIndex={0}
+ colIndex={0}
+ allowSelect
+ columnType="JSON"
+ keyword=""
+ />
+ <DetailProbe />
+ </SQLResultViewProvider>
+ );
+
+ const action = await screen.findByRole("button");
+ fireEvent.click(action);
+
+ expect(screen.getByTestId("detail-state")).toHaveTextContent("0:0:cell");
+ });
+
test("preserves leading whitespace without soft-wrapping string cells", () => {
const { container } = render(
<SQLResultViewProvider
@@ -124,7 +148,6 @@ describe("TableCell", () => {
colIndex={0}
allowSelect
columnType="TEXT"
- database={database}
keyword=""
/>
</SQLResultViewProvider>
diff --git a/frontend/src/modules/sql-editor/components/ResultView/TableCell.tsx b/frontend/src/modules/sql-editor/components/ResultView/TableCell.tsx
index c7a78bce26..681d406cb8 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/TableCell.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/TableCell.tsx
@@ -3,19 +3,17 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { HighlightLabelText } from "@/components/HighlightLabelText";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
-import { Engine } from "@/types/proto-es/v1/common_pb";
-import type { Database } from "@/types/proto-es/v1/database_service_pb";
import type { RowValue } from "@/types/proto-es/v1/sql_service_pb";
import type { SearchScope } from "@/utils/v1/advanced-search/common";
-import { getInstanceResource } from "@/utils/v1/database";
import { BinaryFormatButton } from "./BinaryFormatButton";
import type { BinaryFormat } from "./binary-format";
-import { getPlainValue } from "./cell-value";
+import { getPlainValue, isLikelyJSON } from "./cell-value";
import {
useBinaryFormatContext,
useSelectionContext,
useSQLResultViewContext,
} from "./context";
+import { PlainCellValue } from "./PlainCellValue";
interface TableCellProps {
value: RowValue;
@@ -23,7 +21,6 @@ interface TableCellProps {
colIndex: number;
allowSelect?: boolean;
columnType: string;
- database: Database;
scope?: SearchScope;
keyword: string;
}
@@ -34,7 +31,6 @@ export function TableCell({
colIndex,
allowSelect: allowSelectProp,
columnType,
- database,
scope,
keyword,
}: TableCellProps) {
@@ -55,6 +51,10 @@ export function TableCell({
const hasByteData = value.kind?.case === "bytesValue";
const binaryFormat = getBinaryFormat({ rowIndex, colIndex });
+ const plainValue = useMemo(
+ () => getPlainValue(value, columnType, binaryFormat),
+ [value, columnType, binaryFormat]
+ );
// ResizeObserver replaces Vue's `useResizeObserver(cellRef, ...)`.
useEffect(() => {
@@ -73,18 +73,10 @@ export function TableCell({
return () => observer.disconnect();
}, []);
- const clickable = useMemo(() => {
- if (truncated) return true;
- const eng = getInstanceResource(database).engine;
- if (eng === Engine.MONGODB || eng === Engine.ELASTICSEARCH) {
- const maybeJSON = String(value).trim();
- return (
- (maybeJSON.startsWith("{") && maybeJSON.endsWith("}")) ||
- (maybeJSON.startsWith("[") && maybeJSON.endsWith("]"))
- );
- }
- return false;
- }, [truncated, database, value]);
+ const clickable = useMemo(
+ () => truncated || isLikelyJSON(plainValue),
+ [plainValue, truncated]
+ );
const selected = useMemo(() => {
if (!allowSelect) return false;
@@ -95,13 +87,8 @@ export function TableCell({
return columns.includes(colIndex) || rows.includes(rowIndex);
}, [allowSelect, selectionState, colIndex, rowIndex]);
- const plainValue = useMemo(
- () => getPlainValue(value, columnType, binaryFormat),
- [value, columnType, binaryFormat]
- );
-
const showDetail = () => {
- setDetail({ row: rowIndex, col: colIndex });
+ setDetail({ row: rowIndex, col: colIndex, view: "cell" });
};
const handleClick = (e: React.MouseEvent) => {
@@ -117,22 +104,18 @@ export function TableCell({
const activeKeyword = (scope?.value || keyword).trim();
- let inner: React.ReactNode;
- if (plainValue === undefined) {
- inner = <span className="text-control-placeholder italic">UNSET</span>;
- } else if (plainValue === null) {
- inner = <span className="text-control-placeholder italic">NULL</span>;
- } else if (plainValue.length === 0) {
- inner = <br style={{ minWidth: "1rem", display: "inline-flex" }} />;
- } else {
- inner = <HighlightLabelText text={plainValue} keyword={activeKeyword} />;
- }
+ const inner = (
+ <PlainCellValue value={plainValue}>
+ {plainValue !== undefined && plainValue !== null ? (
+ <HighlightLabelText text={plainValue} keyword={activeKeyword} />
+ ) : undefined}
+ </PlainCellValue>
+ );
return (
<div
ref={cellRef}
onClick={handleClick}
- onDoubleClick={showDetail}
className={cn(
"relative w-full h-full px-2 py-1 flex items-center",
allowSelect ? "cursor-pointer hover:bg-accent/10" : "select-none",
diff --git a/frontend/src/modules/sql-editor/components/ResultView/TextSearchControl.tsx b/frontend/src/modules/sql-editor/components/ResultView/TextSearchControl.tsx
index 5fc52d7bdc..25c21c1bc5 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/TextSearchControl.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/TextSearchControl.tsx
@@ -18,6 +18,8 @@ interface TextSearchControlProps {
matchCount: number;
onQueryChange: (query: string) => void;
onMove: (offset: number) => void;
+ label?: string;
+ className?: string;
}
export function TextSearchControl({
@@ -26,10 +28,13 @@ export function TextSearchControl({
matchCount,
onQueryChange,
onMove,
+ label,
+ className,
}: TextSearchControlProps) {
const { t } = useTranslation();
const inputRef = useRef<HTMLInputElement>(null);
const searchActive = query.trim().length > 0;
+ const searchLabel = label ?? t("common.search");
useEffect(() => {
const handler = (event: KeyboardEvent) => {
@@ -48,16 +53,17 @@ export function TextSearchControl({
<div
className={cn(
"h-8 min-w-0 flex-1 flex items-center overflow-hidden rounded-xs",
- "border border-control-border bg-transparent text-main transition-colors"
+ "border border-control-border bg-transparent text-main transition-colors",
+ className
)}
>
<SearchIcon className="ml-2.5 size-4 shrink-0 text-control-placeholder" />
<Input
ref={inputRef}
size="sm"
- aria-label={t("common.search")}
+ aria-label={searchLabel}
className="h-7 min-w-0 flex-1 border-0 px-2 text-sm focus:ring-0"
- placeholder={t("common.search")}
+ placeholder={searchLabel}
value={query}
autoComplete="off"
onChange={(event) => onQueryChange(event.target.value)}
diff --git a/frontend/src/modules/sql-editor/components/ResultView/VirtualDataBlock.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/VirtualDataBlock.test.tsx
index 82540e5eb1..8334755553 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/VirtualDataBlock.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/VirtualDataBlock.test.tsx
@@ -9,7 +9,10 @@ import {
type RowValue,
RowValueSchema,
} from "@/types/proto-es/v1/sql_service_pb";
-import { SQLResultViewProvider } from "./context";
+import {
+ SQLResultViewProvider,
+ useSQLResultViewContext,
+} from "./context";
import type { ResultTableColumn, ResultTableRow } from "./types";
import { VirtualDataBlock } from "./VirtualDataBlock";
@@ -140,6 +143,15 @@ const database = {
},
} as Database;
+function DetailProbe() {
+ const { detail } = useSQLResultViewContext();
+ return (
+ <div data-testid="detail-state">
+ {detail ? `${detail.row}:${detail.col}:${detail.view}` : "closed"}
+ </div>
+ );
+}
+
const renderBlock = () =>
render(
<SQLResultViewProvider
@@ -151,10 +163,10 @@ const renderBlock = () =>
rows={rows}
columns={columns}
activeRowIndex={-1}
- isSensitiveColumn={() => false}
database={database}
search={{ query: "", scopes: [] }}
/>
+ <DetailProbe />
</SQLResultViewProvider>
);
@@ -171,6 +183,10 @@ describe("VirtualDataBlock", () => {
test("reserves end scroll space and keeps the final row copy action clickable", () => {
const { container } = renderBlock();
+ expect(
+ container.querySelectorAll('[data-testid="row-data-block"]')
+ ).toHaveLength(rows.length);
+
const virtualizerConfig = virtualizerOptions.at(-1);
expect(virtualizerConfig?.paddingEnd).toBeGreaterThanOrEqual(96);
@@ -201,4 +217,12 @@ describe("VirtualDataBlock", () => {
)
);
});
+
+ test("opens cell detail when a value is double-clicked", () => {
+ renderBlock();
+
+ fireEvent.doubleClick(screen.getByText("Acme"));
+
+ expect(screen.getByTestId("detail-state")).toHaveTextContent("0:0:cell");
+ });
});
diff --git a/frontend/src/modules/sql-editor/components/ResultView/VirtualDataBlock.tsx b/frontend/src/modules/sql-editor/components/ResultView/VirtualDataBlock.tsx
index 9a718e0df2..210d93b260 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/VirtualDataBlock.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/VirtualDataBlock.tsx
@@ -12,13 +12,13 @@ import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
import { writeTextToClipboard } from "@/lib/clipboard";
import { cn } from "@/lib/utils";
-import { MaskingReasonPopover } from "@/modules/sql-editor/components/MaskingReasonPopover";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import type { MaskingReason } from "@/types/proto-es/v1/sql_service_pb";
import type { SearchParams } from "@/utils/v1/advanced-search/common";
import { getPlainValue } from "./cell-value";
-import { useBinaryFormatContext } from "./context";
+import { useBinaryFormatContext, useSQLResultViewContext } from "./context";
import { ResultCopyContextMenu } from "./ResultCopyContextMenu";
+import { RowDataBlock } from "./RowDataBlock";
import { TableCell } from "./TableCell";
import type { ResultTableColumn, ResultTableRow } from "./types";
@@ -30,7 +30,6 @@ export interface VirtualDataBlockProps {
rows: ResultTableRow[];
columns: ResultTableColumn[];
activeRowIndex: number;
- isSensitiveColumn: (index: number) => boolean;
getMaskingReason?: (index: number) => MaskingReason | undefined;
database: Database;
statement?: string;
@@ -60,6 +59,7 @@ export const VirtualDataBlock = forwardRef<
const { t } = useTranslation();
const containerRef = useRef<HTMLDivElement>(null);
const { getBinaryFormat } = useBinaryFormatContext();
+ const { setDetail } = useSQLResultViewContext();
// Estimate based on column count: header + (per-column line ≈ 28px) +
// padding. Real measurements come from `measureElement` once mounted.
@@ -150,57 +150,45 @@ export const VirtualDataBlock = forwardRef<
******************************** {rowIndex + 1}. row
********************************
</p>
- <div
+ <RowDataBlock
+ columns={columns}
+ database={database.name}
+ statement={statement}
+ getMaskingReason={getMaskingReason}
className={cn(
- // Subtle surface tint (matches VirtualDataTable's zebra
- // rows) rather than full surface, so a dark custom surface
- // doesn't make each card too heavy.
- "py-2 px-3 bg-control-bg/40 rounded relative",
isActive && "border-2 border-accent/20 bg-accent/10!"
)}
- >
- <CopyJSONButton
- getContent={() => buildRowJSON(rowIndex)}
- label={t("common.copy")}
- />
- {columns.map((column, columnIndex) => {
- const reason = getMaskingReason?.(columnIndex);
- return (
- <div
- key={column.id}
- className="flex items-start text-control-light text-sm"
- >
- <div className="min-w-28 text-left flex items-center font-medium pt-1">
- <div className="flex items-center gap-x-1">
- {column.name}
- {reason && (
- <MaskingReasonPopover
- reason={reason}
- statement={statement}
- database={database.name}
- />
- )}
- </div>
- :
- </div>
- <div className="flex-1">
- <TableCell
- value={row.item.values[columnIndex]}
- keyword={search.query}
- scope={search.scopes.find(
- (s) => s.id === columns[columnIndex]?.id
- )}
- rowIndex={rowIndex}
- colIndex={columnIndex}
- columnType={column.columnType}
- allowSelect
- database={database}
- />
- </div>
- </div>
- );
- })}
- </div>
+ actions={
+ <CopyJSONButton
+ getContent={() => buildRowJSON(rowIndex)}
+ label={t("common.copy")}
+ />
+ }
+ renderValue={(column, columnIndex) => (
+ <div
+ onDoubleClick={(event) => {
+ event.stopPropagation();
+ setDetail({
+ row: rowIndex,
+ col: columnIndex,
+ view: "cell",
+ });
+ }}
+ >
+ <TableCell
+ value={row.item.values[columnIndex]}
+ keyword={search.query}
+ scope={search.scopes.find(
+ (scope) => scope.id === column.id
+ )}
+ rowIndex={rowIndex}
+ colIndex={columnIndex}
+ columnType={column.columnType}
+ allowSelect
+ />
+ </div>
+ )}
+ />
</div>
);
})}
diff --git a/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.test.tsx
new file mode 100644
index 0000000000..4e997ca9b9
--- /dev/null
+++ b/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.test.tsx
@@ -0,0 +1,187 @@
+import { create } from "@bufbuild/protobuf";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { 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 {
+ QueryRowSchema,
+ RowValueSchema,
+} from "@/types/proto-es/v1/sql_service_pb";
+import {
+ SQLResultViewProvider,
+ useSQLResultViewContext,
+} from "./context";
+import type { ResultTableColumn, ResultTableRow } from "./types";
+import { VirtualDataTable } from "./VirtualDataTable";
+
+vi.mock("@tanstack/react-virtual", () => ({
+ useVirtualizer: (options: {
+ count: number;
+ estimateSize: (index: number) => number;
+ }) => ({
+ getVirtualItems: () =>
+ Array.from({ length: options.count }, (_, index) => ({
+ index,
+ key: index,
+ start: index * options.estimateSize(index),
+ })),
+ getTotalSize: () => options.count * options.estimateSize(0),
+ scrollToIndex: vi.fn(),
+ }),
+}));
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: {
+ init: vi.fn(),
+ type: "3rdParty",
+ },
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/components/ui/tooltip", () => ({
+ Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+}));
+
+vi.mock("@/modules/sql-editor/components/MaskingReasonPopover", () => ({
+ MaskingReasonPopover: () => null,
+}));
+
+vi.mock("@/stores/app", () => {
+ const state = () => ({ notify: vi.fn() });
+ return {
+ useAppStore: Object.assign(
+ (selector: (value: ReturnType<typeof state>) => unknown) =>
+ selector(state()),
+ { getState: state }
+ ),
+ };
+});
+
+vi.mock("@/utils/v1/database", () => ({
+ getInstanceResource: () => ({
+ name: "instances/prod",
+ engine: Engine.COSMOSDB,
+ }),
+}));
+
+class ResizeObserverStub implements ResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+globalThis.ResizeObserver = ResizeObserverStub;
+
+const columns: ResultTableColumn[] = [
+ { id: "id", name: "id", columnType: "TEXT" },
+];
+const rows: ResultTableRow[] = [
+ {
+ key: 0,
+ item: create(QueryRowSchema, {
+ values: [
+ create(RowValueSchema, {
+ kind: { case: "stringValue", value: "one" },
+ }),
+ ],
+ }),
+ },
+];
+const database = {
+ name: "instances/prod/databases/main",
+ project: "projects/prod",
+ instanceResource: {
+ name: "instances/prod",
+ engine: Engine.COSMOSDB,
+ },
+} as Database;
+
+function DetailProbe() {
+ const { detail } = useSQLResultViewContext();
+ return (
+ <div data-testid="detail-state">
+ {detail ? `${detail.row}:${detail.col}:${detail.view}` : "closed"}
+ </div>
+ );
+}
+
+describe("VirtualDataTable row detail action", () => {
+ test("replaces the hovered row number with a View detail action", () => {
+ const { container } = 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 rowNumber = container.querySelector(
+ '[data-row-index="0"] .textinfolabel'
+ );
+ expect(rowNumber).toHaveClass(
+ "group-hover:opacity-0",
+ "group-hover:pointer-events-none"
+ );
+ const action = screen.getByRole("button", {
+ name: "sql-editor.view-detail",
+ });
+ expect(action).toHaveClass(
+ "border",
+ "size-6",
+ "rounded-full",
+ "shadow"
+ );
+ expect(action).not.toHaveClass("absolute");
+ expect(action.parentElement).toHaveClass(
+ "absolute",
+ "left-3",
+ "top-1/2",
+ "opacity-0",
+ "group-hover:opacity-100",
+ "group-hover:pointer-events-auto"
+ );
+ expect(action.querySelector(".lucide-expand")).toBeInTheDocument();
+
+ fireEvent.click(action);
+ expect(screen.getByTestId("detail-state")).toHaveTextContent("0:0:row");
+ });
+
+ test("opens the entire relational row when a data cell is double-clicked", () => {
+ const { container } = render(
+ <SQLResultViewProvider
+ engine={Engine.POSTGRES}
+ rows={rows}
+ columns={columns}
+ >
+ <VirtualDataTable
+ rows={rows}
+ columns={columns}
+ activeRowIndex={-1}
+ database={database}
+ search={{ query: "", scopes: [] }}
+ onToggleSort={() => undefined}
+ />
+ <DetailProbe />
+ </SQLResultViewProvider>
+ );
+
+ const cell = container.querySelector(
+ '[data-row-index="0"] [data-col-index="1"]'
+ );
+ expect(cell).toBeInstanceOf(HTMLDivElement);
+ const cellValue = screen.getByText("one");
+
+ fireEvent.doubleClick(cellValue);
+ expect(screen.getByTestId("detail-state")).toHaveTextContent("0:0:row");
+ });
+});
diff --git a/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.tsx b/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.tsx
index 178cbccdc1..b4a1ac47c3 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/VirtualDataTable.tsx
@@ -1,5 +1,6 @@
import { useVirtualizer } from "@tanstack/react-virtual";
import { head, last } from "lodash-es";
+import { ExpandIcon } from "lucide-react";
import {
forwardRef,
useCallback,
@@ -9,6 +10,9 @@ import {
useRef,
useState,
} from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/components/ui/button";
+import { Tooltip } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { MaskingReasonPopover } from "@/modules/sql-editor/components/MaskingReasonPopover";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
@@ -21,7 +25,11 @@ import {
} from "./binary-format";
import { ColumnSortedIcon } from "./ColumnSortedIcon";
import { getPlainValue } from "./cell-value";
-import { useBinaryFormatContext, useSelectionContext } from "./context";
+import {
+ useBinaryFormatContext,
+ useSelectionContext,
+ useSQLResultViewContext,
+} from "./context";
import { ResultCopyContextMenu } from "./ResultCopyContextMenu";
import { TableCell } from "./TableCell";
import type {
@@ -44,7 +52,6 @@ export interface VirtualDataTableProps {
rows: ResultTableRow[];
columns: ResultTableColumn[];
activeRowIndex: number;
- isSensitiveColumn: (index: number) => boolean;
getMaskingReason?: (index: number) => MaskingReason | undefined;
database: Database;
statement?: string;
@@ -77,6 +84,7 @@ export const VirtualDataTable = forwardRef<
},
ref
) {
+ const { t } = useTranslation();
const containerRef = useRef<HTMLDivElement>(null);
const [containerWidth, setContainerWidth] = useState(0);
@@ -100,6 +108,7 @@ export const VirtualDataTable = forwardRef<
} = useSelectionContext();
const { getBinaryFormat, setBinaryFormat } = useBinaryFormatContext();
+ const { setDetail } = useSQLResultViewContext();
const getColumnTypeByIndex = useCallback(
(columnIndex: number) => columns[columnIndex]?.columnType ?? "",
@@ -386,6 +395,9 @@ export const VirtualDataTable = forwardRef<
key={virtualRow.key}
data-row-index={rowIndex}
className="flex absolute inset-x-0 group"
+ onDoubleClick={() =>
+ setDetail({ row: rowIndex, col: 0, view: "row" })
+ }
style={{
top: 0,
transform: `translateY(${virtualRow.start}px)`,
@@ -407,10 +419,27 @@ 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" });
+ }}
+ >
+ <ExpandIcon className="size-3" />
+ </Button>
+ </Tooltip>
+ </div>
<span
className={cn(
"textinfolabel pr-1 truncate",
- selectionDisabled ? "pl-1" : "pl-4"
+ 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"
)}
>
{rowIndex + 1}
@@ -462,7 +491,6 @@ export const VirtualDataTable = forwardRef<
colIndex={columnIndex}
allowSelect
columnType={getColumnTypeByIndex(columnIndex)}
- database={database}
/>
</div>
</div>
diff --git a/frontend/src/modules/sql-editor/components/ResultView/cell-value.ts b/frontend/src/modules/sql-editor/components/ResultView/cell-value.ts
index 791d8110ec..885900faea 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/cell-value.ts
+++ b/frontend/src/modules/sql-editor/components/ResultView/cell-value.ts
@@ -43,3 +43,12 @@ export const getPlainValue = (
if (value === undefined || value === null) return value;
return String(value);
};
+
+export const isLikelyJSON = (value: string | null | undefined) => {
+ if (!value) return false;
+ const trimmed = value.trim();
+ return (
+ (trimmed.startsWith("{") && trimmed.endsWith("}")) ||
+ (trimmed.startsWith("[") && trimmed.endsWith("]"))
+ );
+};
diff --git a/frontend/src/modules/sql-editor/components/ResultView/context.tsx b/frontend/src/modules/sql-editor/components/ResultView/context.tsx
index f27a595e8e..7c1428d413 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/context.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/context.tsx
@@ -37,12 +37,13 @@ import {
import type { ResultTableColumn, ResultTableRow } from "./types";
// =============================================================================
-// SQLResultViewContext (disallowCopyingData / detail-cell)
+// SQLResultViewContext (disallowCopyingData / detail view)
// =============================================================================
export interface ResultViewDetail {
row: number;
col: number;
+ view: "cell" | "row";
}
export interface SQLResultViewContext {
@@ -144,7 +145,7 @@ interface SQLResultViewProviderProps {
/**
* Per-instance provider for one `<ResultView>` mount. Owns:
- * - The disallowCopying flag + the detail-cell state
+ * - The disallowCopying flag + the detail-view state
* - The binary-format Map (per-cell and per-column overrides)
* - The selection state + row/column/cell toggles + clipboard copy
*
diff --git a/frontend/src/modules/sql-editor/components/ResultView/detail-panel-search.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/detail-panel-search.test.tsx
index fca8e7095c..e7a0ef0d58 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/detail-panel-search.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/detail-panel-search.test.tsx
@@ -1,5 +1,9 @@
+import { render } from "@testing-library/react";
import { describe, expect, test } from "vitest";
-import { highlightHtmlText } from "./detail-panel-search";
+import {
+ highlightHtmlText,
+ renderRowFieldsWithSearchMatches,
+} from "./detail-panel-search";
describe("detail panel search", () => {
test("highlights matches inside generated HTML without removing token markup", () => {
@@ -15,4 +19,31 @@ describe("detail panel search", () => {
expect(result.html).toContain("<mark");
expect(result.html).toContain("CREATE");
});
+
+ test("preserves named row fields and the global active match order", () => {
+ const result = renderRowFieldsWithSearchMatches(
+ [
+ { columnName: "name", value: "primary name" },
+ { columnName: "display_name", value: "Ada" },
+ ],
+ "name",
+ 2
+ );
+ const view = render(
+ <>
+ <span>{result.fields[0]?.columnName}</span>
+ <span>{result.fields[0]?.value}</span>
+ <span>{result.fields[1]?.columnName}</span>
+ <span>{result.fields[1]?.value}</span>
+ </>
+ );
+
+ const matches = view.container.querySelectorAll("mark");
+ expect(result.count).toBe(3);
+ expect(matches).toHaveLength(3);
+ expect(matches[2]).toHaveAttribute(
+ "data-detail-search-active-match",
+ "true"
+ );
+ });
});
diff --git a/frontend/src/modules/sql-editor/components/ResultView/detail-panel-search.tsx b/frontend/src/modules/sql-editor/components/ResultView/detail-panel-search.tsx
index ba79c56d82..ba2377347f 100644
--- a/frontend/src/modules/sql-editor/components/ResultView/detail-panel-search.tsx
+++ b/frontend/src/modules/sql-editor/components/ResultView/detail-panel-search.tsx
@@ -69,6 +69,33 @@ export function renderTextWithSearchMatches(
return { nodes, count: matches.length };
}
+export function renderRowFieldsWithSearchMatches(
+ fields: ReadonlyArray<{ columnName: string; value: string }>,
+ query: string,
+ activeIndex: number
+): {
+ fields: Array<{ columnName: ReactNode; value: ReactNode }>;
+ count: number;
+} {
+ let matchOffset = 0;
+ const renderedFields = fields.map((field) => {
+ const columnName = renderTextWithSearchMatches(
+ field.columnName,
+ query,
+ activeIndex - matchOffset
+ );
+ matchOffset += columnName.count;
+ const value = renderTextWithSearchMatches(
+ field.value,
+ query,
+ activeIndex - matchOffset
+ );
+ matchOffset += value.count;
+ return { columnName: columnName.nodes, value: value.nodes };
+ });
+ return { fields: renderedFields, count: matchOffset };
+}
+
const getTextNodes = (root: Node) => {
const nodes: Text[] = [];
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
diff --git a/frontend/src/routes/workspace/general/sql-editor-theme/ThemePreview.tsx b/frontend/src/routes/workspace/general/sql-editor-theme/ThemePreview.tsx
index f8de1d00b7..8aeb4d46e4 100644
--- a/frontend/src/routes/workspace/general/sql-editor-theme/ThemePreview.tsx
+++ b/frontend/src/routes/workspace/general/sql-editor-theme/ThemePreview.tsx
@@ -225,7 +225,6 @@ export function ThemePreview({ theme }: Readonly<ThemePreviewProps>) {
rows={SAMPLE_ROWS}
columns={SAMPLE_COLUMNS}
activeRowIndex={-1}
- isSensitiveColumn={() => false}
database={SAMPLE_DATABASE}
statement={PREVIEW_SQL}
search={EMPTY_SEARCH}
@@ -235,7 +234,6 @@ export function ThemePreview({ theme }: Readonly<ThemePreviewProps>) {
rows={SAMPLE_ROWS}
columns={SAMPLE_COLUMNS}
activeRowIndex={-1}
- isSensitiveColumn={() => false}
database={SAMPLE_DATABASE}
statement={PREVIEW_SQL}
search={EMPTY_SEARCH}
diff --git a/frontend/src/utils/sqlResult.ts b/frontend/src/utils/sqlResult.ts
index c4cd0d1c7e..1604f3199e 100644
--- a/frontend/src/utils/sqlResult.ts
+++ b/frontend/src/utils/sqlResult.ts
@@ -327,20 +327,13 @@ export interface NoSQLJSONViewResult {
documents: NoSQLJSONDocument[];
}
-export const formatNoSQLQueryResultForJSONView = (
- result: QueryResult
-): NoSQLJSONViewResult | undefined => {
+const formatNoSQLRows = (result: QueryResult): string[] | undefined => {
if (result.columnNames.length !== 1 || result.columnNames[0] !== "result") {
return undefined;
}
- if (result.rows.length === 0) {
- return { content: "[]", documents: [] };
- }
-
- const lines = ["["];
- const documents: NoSQLJSONDocument[] = [];
- for (const [index, row] of result.rows.entries()) {
+ const formattedRows: string[] = [];
+ for (const row of result.rows) {
if (row.values.length !== 1 || row.values[0].kind.case !== "stringValue") {
return undefined;
}
@@ -353,29 +346,82 @@ export const formatNoSQLQueryResultForJSONView = (
if (document === undefined) {
return undefined;
}
- const documentLines = document.split("\n").map((line) => ` ${line}`);
- if (index < result.rows.length - 1) {
- documentLines[documentLines.length - 1] += ",";
- }
- const startLineNumber = lines.length + 1;
- lines.push(...documentLines);
- documents.push({
- content: document,
- startLineNumber,
- endLineNumber: lines.length,
- });
+ formattedRows.push(document);
} catch {
return undefined;
}
}
- lines.push("]");
- return { content: lines.join("\n"), documents };
+ return formattedRows;
+};
+
+export const isNoSQLQueryResult = (result: QueryResult): boolean => {
+ if (result.columnNames.length !== 1 || result.columnNames[0] !== "result") {
+ return false;
+ }
+
+ return result.rows.every((row) => {
+ if (row.values.length !== 1 || row.values[0].kind.case !== "stringValue") {
+ return false;
+ }
+ try {
+ losslessParse(row.values[0].kind.value);
+ return true;
+ } catch {
+ return false;
+ }
+ });
+};
+
+const formatNoSQLDocumentsAsJSON = (documents: string[]): string => {
+ if (documents.length === 0) {
+ return "[]";
+ }
+
+ const lines = ["["];
+ for (const [index, document] of documents.entries()) {
+ const documentLines = document.split("\n").map((line) => ` ${line}`);
+ if (index < documents.length - 1) {
+ documentLines[documentLines.length - 1] += ",";
+ }
+ lines.push(...documentLines);
+ }
+ lines.push("]");
+ return lines.join("\n");
};
-export const formatNoSQLQueryResultAsJSON = (
+export const formatNoSQLQueryResultForJSONView = (
result: QueryResult
-): string | undefined => formatNoSQLQueryResultForJSONView(result)?.content;
+): NoSQLJSONViewResult | undefined => {
+ const formattedRows = formatNoSQLRows(result);
+ if (!formattedRows) {
+ return undefined;
+ }
+ let startLineNumber = 2;
+ const documents: NoSQLJSONDocument[] = [];
+ for (const document of formattedRows) {
+ const lineCount = document.split("\n").length;
+ documents.push({
+ content: document,
+ startLineNumber,
+ endLineNumber: startLineNumber + lineCount - 1,
+ });
+ startLineNumber += lineCount;
+ }
+
+ return {
+ content: formatNoSQLDocumentsAsJSON(formattedRows),
+ documents,
+ };
+};
+
+export const formatNoSQLQueryResultAsJSON = (result: QueryResult) => {
+ const formattedRows = formatNoSQLRows(result);
+ if (!formattedRows) {
+ return undefined;
+ }
+ return formatNoSQLDocumentsAsJSON(formattedRows);
+};
// Parses the hits array from an Elasticsearch _search QueryResult's "hits" column.
const parseESHitsArray = (result: QueryResult): unknown[] | undefined => {