Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: document db json view (#21200)
ecmadao24a196015ff7
diff --git a/frontend/src/components/ui/segmented-control.tsx b/frontend/src/components/ui/segmented-control.tsxindex b3d8a53a31..5d28797b84 100644--- a/frontend/src/components/ui/segmented-control.tsx+++ b/frontend/src/components/ui/segmented-control.tsx@@ -18,6 +18,7 @@ interface SegmentedControlProps<T extends string> {options: SegmentedControlOption<T>[];onValueChange: (value: T) => void;ariaLabel: string;+ appearance?: "solid" | "soft";disabled?: boolean;className?: string;/** Segment size — matches the shared control size tier names. Defaults to `md`. */@@ -29,6 +30,7 @@ export function SegmentedControl<T extends string>({options,onValueChange,ariaLabel,+ appearance = "solid",disabled = false,className,size = "md",@@ -62,7 +64,9 @@ export function SegmentedControl<T extends string>({!previousSelected &&"border-l border-control-border",selected- ? "bg-accent text-accent-text"+ ? appearance === "soft"+ ? "bg-accent/10 text-accent"+ : "bg-accent text-accent-text": "bg-background text-control hover:bg-control-bg",optionDisabled? "cursor-not-allowed opacity-50 hover:bg-background"diff --git a/frontend/src/hooks/useExecuteSQL.ts b/frontend/src/hooks/useExecuteSQL.tsindex 8cb75ae8f6..9134dbb31b 100644--- a/frontend/src/hooks/useExecuteSQL.ts+++ b/frontend/src/hooks/useExecuteSQL.ts@@ -22,7 +22,6 @@ import type {SQLResultSetV1,} from "@/types";import { isValidDatabaseName } from "@/types";-import { Engine } from "@/types/proto-es/v1/common_pb";import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";import type { Database } from "@/types/proto-es/v1/database_service_pb";import {@@ -34,10 +33,8 @@ import {import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import {getDatabaseProject,- getInstanceResource,hasPermissionToCreateChangeDatabaseIssueInProject,} from "@/utils";-import { flattenNoSQLResult } from "@/utils/sqlResult";// QUERY_INTERVAL_LIMIT is the minimal gap between two queriesconst QUERY_INTERVAL_LIMIT = 1000;@@ -384,11 +381,6 @@ export const useExecuteSQL = () => {void sqlEditorEvents.emit("query-executed");});- const instanceResource = getInstanceResource(database);- if (instanceResource.engine === Engine.COSMOSDB) {- flattenNoSQLResult(resultSet);- }-if (isDisallowChangeDatabaseError(resultSet)) {// Show a tips to navigate to issue creation// if the user is allowed to create issue in the project.diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 644a69cd55..663a9fc5a2 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -3030,6 +3030,7 @@}},"invalid-database": "Invalid database {{database}}",+ "json-view": "JSON view","last-synced": "Last synced: <time></time>","loading-data": "Loading Data...","loading-databases": "Loading Databases...",@@ -3062,6 +3063,7 @@},"request-aborted": "User aborted the request","request-access-grant": "Request access grant",+ "request-export": "Request export","result-detail": {"next-match": "Next match","previous-match": "Previous match",@@ -3070,6 +3072,7 @@"result-limit": {"self": "Result limit"},+ "result-view-mode": "Result view mode","revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?","rows": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex d723b48ba3..ba41109b3f 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -3030,6 +3030,7 @@}},"invalid-database": "Base de datos no válida {{database}}",+ "json-view": "Vista JSON","last-synced": "Última sincronización: <time></time>","loading-data": "Cargando datos...","loading-databases": "Cargando bases de datos...",@@ -3062,6 +3063,7 @@},"request-aborted": "El usuario abortó la solicitud","request-access-grant": "Solicitar concesión de acceso",+ "request-export": "Solicitar exportación","result-detail": {"next-match": "Siguiente coincidencia","previous-match": "Coincidencia anterior",@@ -3070,6 +3072,7 @@"result-limit": {"self": "Límite de resultados"},+ "result-view-mode": "Modo de vista de resultados","revoke-access": "Revocar","revoke-confirm": "¿Está seguro de que desea revocar esta concesión de acceso?","rows": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 5f42da6c5e..27cdbf904f 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -3030,6 +3030,7 @@}},"invalid-database": "無効なデータベース {{database}}",+ "json-view": "JSON ビュー","last-synced": "最終同期時間: <time></time>","loading-data": "データのロード...","loading-databases": "データベース情報をロードしています...",@@ -3062,6 +3063,7 @@},"request-aborted": "ユーザーがリクエストを中止しました","request-access-grant": "アクセス付与をリクエスト",+ "request-export": "エクスポートをリクエスト","result-detail": {"next-match": "次の一致","previous-match": "前の一致",@@ -3070,6 +3072,7 @@"result-limit": {"self": "結果の制限"},+ "result-view-mode": "結果表示モード","revoke-access": "取り消し","revoke-confirm": "このアクセス付与を取り消してもよろしいですか?","rows": {diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 9085d32941..e9506e2383 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -3030,6 +3030,7 @@}},"invalid-database": "Cơ sở dữ liệu không hợp lệ {{database}}",+ "json-view": "Chế độ xem JSON","last-synced": "Đã đồng bộ lần cuối: <time></time>","loading-data": "Đang tải Dữ liệu...","loading-databases": "Đang tải Cơ sở dữ liệu...",@@ -3062,6 +3063,7 @@},"request-aborted": "Người dùng đã hủy yêu cầu","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": {"next-match": "Kết quả tiếp theo","previous-match": "Kết quả trước",@@ -3070,6 +3072,7 @@"result-limit": {"self": "Giới hạn kết quả"},+ "result-view-mode": "Chế độ xem kết quả","revoke-access": "Thu hồi","revoke-confirm": "Bạn có chắc chắn muốn thu hồi cấp quyền truy cập này không?","rows": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 525993f484..2d10f932a3 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -3030,6 +3030,7 @@}},"invalid-database": "数据库 {{database}} 无效",+ "json-view": "JSON 视图","last-synced": "上次同步时间:<time></time>","loading-data": "加载数据中...","loading-databases": "加载数据库信息...",@@ -3062,6 +3063,7 @@},"request-aborted": "用户中止了请求","request-access-grant": "申请访问授权",+ "request-export": "申请导出","result-detail": {"next-match": "下一个匹配项","previous-match": "上一个匹配项",@@ -3070,6 +3072,7 @@"result-limit": {"self": "结果限制"},+ "result-view-mode": "结果视图模式","revoke-access": "撤销","revoke-confirm": "确定要撤销此访问授权吗?","rows": {diff --git a/frontend/src/modules/sql-editor/components/RequestExportButton.test.tsx b/frontend/src/modules/sql-editor/components/RequestExportButton.test.tsxnew file mode 100644index 0000000000..78426b9122--- /dev/null+++ b/frontend/src/modules/sql-editor/components/RequestExportButton.test.tsx@@ -0,0 +1,74 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, test, vi } from "vitest";+import { RequestExportButton } from "./RequestExportButton";++const mocks = vi.hoisted(() => ({+ loadSubscription: vi.fn(),+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/components/FeatureBadge", () => ({+ FeatureBadge: () => null,+}));++vi.mock("@/components/PermissionGuard", () => ({+ PermissionGuard: ({+ children,+ }: {+ children: (props: { disabled: boolean }) => React.ReactNode;+ }) => <>{children({ disabled: false })}</>,+}));++vi.mock("@/hooks/useAppProject", () => ({+ useAppProject: () => ({+ name: "projects/proj1",+ allowJustInTimeAccess: true,+ }),+}));++vi.mock("@/modules/sql-editor/store/editor", () => ({+ useSQLEditorEditorState: (selector: (state: { project: string }) => unknown) =>+ selector({ project: "projects/proj1" }),+}));++vi.mock("@/stores/app", () => ({+ useAppStore: (+ selector: (state: {+ loadSubscription: typeof mocks.loadSubscription;+ hasFeature: () => boolean;+ }) => unknown+ ) =>+ selector({+ loadSubscription: mocks.loadSubscription,+ hasFeature: () => true,+ }),+}));++vi.mock("./AccessGrantRequestDrawer", () => ({+ AccessGrantRequestDrawer: () => null,+}));++vi.mock("./RequestDrawerHost", () => ({+ useRequestDrawerHost: () => undefined,+}));++describe("RequestExportButton", () => {+ test("labels the export action instead of the access-grant mechanism", () => {+ render(+ <RequestExportButton+ statement="SELECT * FROM t"+ targets={["instances/i/databases/d"]}+ />+ );++ expect(screen.getByRole("button")).toHaveTextContent(+ "sql-editor.request-export"+ );+ expect(screen.getByRole("button")).not.toHaveTextContent(+ "sql-editor.request-access-grant"+ );+ });+});diff --git a/frontend/src/modules/sql-editor/components/RequestExportButton.tsx b/frontend/src/modules/sql-editor/components/RequestExportButton.tsxindex f8dd3a544e..b90ee872a9 100644--- a/frontend/src/modules/sql-editor/components/RequestExportButton.tsx+++ b/frontend/src/modules/sql-editor/components/RequestExportButton.tsx@@ -89,7 +89,7 @@ export function RequestExportButton({feature={PlanFeature.FEATURE_JIT}/>)}- {t("sql-editor.request-access-grant")}+ {t("sql-editor.request-export")}</Button>)}</PermissionGuard>diff --git a/frontend/src/modules/sql-editor/components/ResultView/DocumentJSONView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/DocumentJSONView.test.tsxnew file mode 100644index 0000000000..26a7667eff--- /dev/null+++ b/frontend/src/modules/sql-editor/components/ResultView/DocumentJSONView.test.tsx@@ -0,0 +1,183 @@+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { useEffect } from "react";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { DocumentJSONView } from "./DocumentJSONView";++const {+ editor,+ handlers,+ onMouseMove,+ recordMonacoProps,+ writeTextToClipboard,+} = vi.hoisted(() => {+ const handlers: { mouseMove?: (event: unknown) => void } = {};+ const onMouseMove = vi.fn((handler: (event: unknown) => void) => {+ handlers.mouseMove = handler;+ return { dispose: vi.fn() };+ });+ return {+ editor: {+ getModel: () => ({+ deltaDecorations: vi.fn(() => []),+ findMatches: vi.fn(() => []),+ }),+ getLayoutInfo: () => ({+ contentLeft: 48,+ contentWidth: 600,+ glyphMarginLeft: 0,+ glyphMarginWidth: 32,+ }),+ getScrollTop: () => 0,+ getTopForLineNumber: (lineNumber: number) => (lineNumber - 1) * 24,+ onDidChangeCursorPosition: vi.fn(() => ({ dispose: vi.fn() })),+ onDidScrollChange: vi.fn(() => ({ dispose: vi.fn() })),+ onMouseLeave: vi.fn(() => ({ dispose: vi.fn() })),+ onMouseMove,+ revealRangeInCenter: vi.fn(),+ },+ handlers,+ onMouseMove,+ recordMonacoProps: vi.fn(),+ writeTextToClipboard: vi.fn(async () => true),+ };+});++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/lib/clipboard", () => ({+ writeTextToClipboard,+}));++vi.mock("@/components/monaco/MonacoEditor", () => ({+ MonacoEditor: (props: {+ content: string;+ onReady?: (monaco: unknown, editor: unknown) => void;+ }) => {+ recordMonacoProps(props);+ useEffect(() => {+ props.onReady?.({}, editor);+ }, [props.onReady]);+ return <pre data-testid="json-editor">{props.content}</pre>;+ },+}));++describe("DocumentJSONView", () => {+ beforeEach(() => {+ handlers.mouseMove = undefined;+ onMouseMove.mockClear();+ writeTextToClipboard.mockClear();+ });++ test("renders formatted documents in a read-only JSON editor", () => {+ const content = '[\n {\n "id": "one"\n }\n]';++ render(+ <DocumentJSONView+ content={content}+ disallowCopyingData={false}+ compact={false}+ searchQuery=""+ activeMatchIndex={0}+ onMatchCountChange={vi.fn()}+ documents={[]}+ />+ );++ expect(+ screen.getByRole("region", { name: "sql-editor.json-view" })+ ).toHaveTextContent('"id": "one"');+ expect(recordMonacoProps).toHaveBeenCalledWith(+ expect.objectContaining({+ autoHeight: false,+ content,+ language: "json",+ readOnly: true,+ })+ );+ });++ test("prevents native copy events when result copying is disabled", () => {+ const { rerender } = render(+ <DocumentJSONView+ content="[]"+ disallowCopyingData+ compact={false}+ searchQuery=""+ activeMatchIndex={0}+ onMatchCountChange={vi.fn()}+ documents={[]}+ />+ );++ const blockedEvent = new Event("copy", {+ bubbles: true,+ cancelable: true,+ });+ screen.getByTestId("json-editor").dispatchEvent(blockedEvent);+ expect(blockedEvent.defaultPrevented).toBe(true);++ rerender(+ <DocumentJSONView+ content="[]"+ disallowCopyingData={false}+ compact={false}+ searchQuery=""+ activeMatchIndex={0}+ onMatchCountChange={vi.fn()}+ documents={[]}+ />+ );+ const allowedEvent = new Event("copy", {+ bubbles: true,+ cancelable: true,+ });+ fireEvent(screen.getByTestId("json-editor"), allowedEvent);+ expect(allowedEvent.defaultPrevented).toBe(false);+ });++ test("copies the top-level document under the pointer", async () => {+ const document = {+ content: '{\n "id": "one"\n}',+ startLineNumber: 2,+ endLineNumber: 4,+ };+ const view = render(+ <DocumentJSONView+ content={`[\n ${document.content.replaceAll("\n", "\n ")}\n]`}+ documents={[document]}+ disallowCopyingData={false}+ compact={false}+ searchQuery=""+ activeMatchIndex={0}+ onMatchCountChange={vi.fn()}+ />+ );++ await waitFor(() => expect(onMouseMove).toHaveBeenCalled());+ act(() => {+ handlers.mouseMove?.({ target: { position: { lineNumber: 3 } } });+ });++ const copyButton = screen.getByRole("button", { name: "common.copy" });+ expect(copyButton.parentElement?.parentElement).toHaveStyle({ left: "6px" });+ fireEvent.click(copyButton);+ expect(writeTextToClipboard).toHaveBeenCalledWith(document.content);++ view.rerender(+ <DocumentJSONView+ content={`[\n ${document.content.replaceAll("\n", "\n ")}\n]`}+ documents={[document]}+ disallowCopyingData+ compact={false}+ searchQuery=""+ activeMatchIndex={0}+ onMatchCountChange={vi.fn()}+ />+ );+ expect(+ screen.queryByRole("button", { name: "common.copy" })+ ).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/modules/sql-editor/components/ResultView/DocumentJSONView.tsx b/frontend/src/modules/sql-editor/components/ResultView/DocumentJSONView.tsxnew file mode 100644index 0000000000..384b79f35e--- /dev/null+++ b/frontend/src/modules/sql-editor/components/ResultView/DocumentJSONView.tsx@@ -0,0 +1,255 @@+import { CheckIcon, CopyIcon } from "lucide-react";+import { useCallback, useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { MonacoEditor } from "@/components/monaco/MonacoEditor";+import type {+ IStandaloneCodeEditor,+ ITextModel,+ MonacoModule,+} from "@/components/monaco/types";+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 { normalizeSearchQuery } from "./detail-panel-search";++interface DocumentJSONViewProps {+ content: string;+ documents: NoSQLJSONDocument[];+ disallowCopyingData: boolean;+ compact: boolean;+ searchQuery: string;+ activeMatchIndex: number;+ onMatchCountChange: (count: number) => void;+}++export function DocumentJSONView({+ content,+ documents,+ disallowCopyingData,+ compact,+ searchQuery,+ activeMatchIndex,+ onMatchCountChange,+}: DocumentJSONViewProps) {+ const { t } = useTranslation();+ const [editor, setEditor] = useState<IStandaloneCodeEditor | null>(null);+ const [copyAction, setCopyAction] = useState<{+ documentIndex: number;+ left: number;+ top: number;+ }>();+ const [copiedDocumentIndex, setCopiedDocumentIndex] = useState<number>();+ const decorationModelRef = useRef<ITextModel | null>(null);+ const decorationIdsRef = useRef<string[]>([]);+ const activeLineNumberRef = useRef<number | undefined>(undefined);+ const cursorLineNumberRef = useRef<number | undefined>(undefined);+ const copiedTimerRef = useRef<number | undefined>(undefined);++ const handleReady = useCallback(+ (_monaco: MonacoModule, readyEditor: IStandaloneCodeEditor) => {+ setEditor(readyEditor);+ },+ []+ );++ useEffect(() => {+ if (!editor) {+ return;+ }+ const model = editor.getModel();+ if (!model) {+ return;+ }++ const query = normalizeSearchQuery(searchQuery);+ const matches = query+ ? model.findMatches(query, false, false, false, null, false)+ : [];+ onMatchCountChange(matches.length);++ if (decorationModelRef.current !== model) {+ decorationModelRef.current?.deltaDecorations(+ decorationIdsRef.current,+ []+ );+ decorationModelRef.current = model;+ decorationIdsRef.current = [];+ }++ const selectedMatchIndex = Math.min(+ Math.max(activeMatchIndex, 0),+ matches.length - 1+ );+ decorationIdsRef.current = model.deltaDecorations(+ decorationIdsRef.current,+ matches.map((match, index) => ({+ range: match.range,+ options: {+ inlineClassName:+ index === selectedMatchIndex+ ? "rounded-[2px] bg-accent text-accent-text"+ : "rounded-[2px] bg-warning-bg text-main",+ },+ }))+ );++ const selectedMatch = matches[selectedMatchIndex];+ if (selectedMatch) {+ editor.revealRangeInCenter(selectedMatch.range);+ }+ }, [activeMatchIndex, content, editor, onMatchCountChange, searchQuery]);++ useEffect(() => {+ return () => {+ decorationModelRef.current?.deltaDecorations(+ decorationIdsRef.current,+ []+ );+ decorationModelRef.current = null;+ decorationIdsRef.current = [];+ };+ }, []);++ const updateCopyAction = useCallback(+ (lineNumber: number | undefined) => {+ activeLineNumberRef.current = lineNumber;+ if (!editor || disallowCopyingData || lineNumber === undefined) {+ setCopyAction(undefined);+ return;+ }+ const documentIndex = documents.findIndex(+ (document) =>+ lineNumber >= document.startLineNumber &&+ lineNumber <= document.endLineNumber+ );+ if (documentIndex < 0) {+ setCopyAction(undefined);+ return;+ }++ const document = documents[documentIndex];+ const layout = editor.getLayoutInfo();+ setCopyAction({+ documentIndex,+ left:+ layout.glyphMarginLeft ++ Math.max((layout.glyphMarginWidth - 24) / 2, 0) ++ 2,+ top:+ editor.getTopForLineNumber(document.startLineNumber) -+ editor.getScrollTop(),+ });+ },+ [disallowCopyingData, documents, editor]+ );++ useEffect(() => {+ if (!editor || disallowCopyingData || documents.length === 0) {+ setCopyAction(undefined);+ return;+ }++ const mouseMoveSubscription = editor.onMouseMove((event) => {+ const lineNumber =+ "position" in event.target+ ? event.target.position?.lineNumber+ : undefined;+ updateCopyAction(lineNumber);+ });+ const cursorSubscription = editor.onDidChangeCursorPosition((event) => {+ cursorLineNumberRef.current = event.position.lineNumber;+ updateCopyAction(event.position.lineNumber);+ });+ const scrollSubscription = editor.onDidScrollChange(() => {+ updateCopyAction(activeLineNumberRef.current);+ });++ return () => {+ mouseMoveSubscription.dispose();+ cursorSubscription.dispose();+ scrollSubscription.dispose();+ };+ }, [disallowCopyingData, documents.length, editor, updateCopyAction]);++ useEffect(() => {+ return () => window.clearTimeout(copiedTimerRef.current);+ }, []);++ const handleCopyDocument = async (documentIndex: number) => {+ const document = documents[documentIndex];+ if (!document || disallowCopyingData) {+ return;+ }+ if (await writeTextToClipboard(document.content)) {+ setCopiedDocumentIndex(documentIndex);+ window.clearTimeout(copiedTimerRef.current);+ copiedTimerRef.current = window.setTimeout(+ () => setCopiedDocumentIndex(undefined),+ 2000+ );+ }+ };++ return (+ <div+ role="region"+ aria-label={t("sql-editor.json-view")}+ className={cn(+ "relative w-full min-h-0 overflow-hidden border border-control-border",+ compact ? "h-80" : "flex-1"+ )}+ onMouseLeave={() => updateCopyAction(cursorLineNumberRef.current)}+ onCopyCapture={(event) => {+ if (!disallowCopyingData) {+ return;+ }+ event.preventDefault();+ event.stopPropagation();+ }}+ >+ <MonacoEditor+ content={content}+ language="json"+ readOnly+ autoFocus={false}+ autoHeight={false}+ onReady={handleReady}+ className="h-full"+ options={{+ contextmenu: !disallowCopyingData,+ folding: true,+ glyphMargin: !disallowCopyingData,+ lineNumbers: "on",+ minimap: {+ enabled: true,+ },+ wordWrap: "off",+ }}+ />+ {copyAction && !disallowCopyingData && (+ <div+ className="absolute z-10"+ style={{ left: copyAction.left, top: copyAction.top }}+ >+ <Tooltip content={t("common.copy")} side="left">+ <Button+ size="xs"+ appearance="outline"+ className="size-6 bg-background p-0 shadow-sm"+ aria-label={t("common.copy")}+ onClick={() => void handleCopyDocument(copyAction.documentIndex)}+ >+ {copiedDocumentIndex === copyAction.documentIndex ? (+ <CheckIcon className="size-3.5" />+ ) : (+ <CopyIcon className="size-3.5" />+ )}+ </Button>+ </Tooltip>+ </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.tsxnew file mode 100644index 0000000000..180e1cab4c--- /dev/null+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.test.tsx@@ -0,0 +1,552 @@+import { create } from "@bufbuild/protobuf";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { useEffect } from "react";+import { beforeEach, describe, expect, test, vi } from "vitest";+import type { SQLEditorQueryParams } from "@/types";+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 { SingleResultView } from "./SingleResultView";++const {+ deltaDecorations,+ findMatches,+ monacoEditor,+ revealRangeInCenter,+ translate,+ writeTextToClipboard,+} = vi.hoisted(() => {+ const ranges = [+ {+ startLineNumber: 2,+ startColumn: 6,+ endLineNumber: 2,+ endColumn: 9,+ },+ {+ startLineNumber: 4,+ startColumn: 6,+ endLineNumber: 4,+ endColumn: 9,+ },+ ];+ const findMatches = vi.fn((query: string) =>+ query ? ranges.map((range) => ({ range })) : []+ );+ const deltaDecorations = vi.fn(() => ["match-1", "match-2"]);+ const revealRangeInCenter = vi.fn();+ return {+ deltaDecorations,+ findMatches,+ monacoEditor: {+ getModel: () => ({ deltaDecorations, findMatches }),+ getLayoutInfo: () => ({+ contentLeft: 48,+ contentWidth: 600,+ glyphMarginLeft: 0,+ glyphMarginWidth: 32,+ }),+ getScrollTop: () => 0,+ getTopForLineNumber: (lineNumber: number) => (lineNumber - 1) * 24,+ onDidChangeCursorPosition: vi.fn(() => ({ dispose: vi.fn() })),+ onDidScrollChange: vi.fn(() => ({ dispose: vi.fn() })),+ onMouseMove: vi.fn(() => ({ dispose: vi.fn() })),+ revealRangeInCenter,+ },+ revealRangeInCenter,+ translate: (key: string) => key,+ writeTextToClipboard: vi.fn(),+ };+});++vi.mock("react-i18next", () => ({+ initReactI18next: {+ init: vi.fn(),+ type: "3rdParty",+ },+ useTranslation: () => ({ t: translate }),+}));++vi.mock("@/components/AdvancedSearch", () => ({+ AdvancedSearch: () => <div data-testid="result-search" />,+}));++vi.mock("@/components/DataExportButton", () => ({+ DataExportButton: () => null,+}));++vi.mock("@/components/DatabaseTargetDisplay", () => ({+ DatabaseTargetDisplay: () => null,+}));++vi.mock("@/components/monaco/MonacoEditor", () => ({+ MonacoEditor: ({+ content,+ onReady,+ }: {+ content: string;+ onReady?: (monaco: unknown, editor: unknown) => void;+ }) => {+ useEffect(() => {+ onReady?.({}, monacoEditor);+ }, [onReady]);+ return <pre data-testid="json-editor">{content}</pre>;+ },+}));++vi.mock("@/hooks/useExecuteSQL", () => ({+ useExecuteSQL: () => ({ runQuery: vi.fn() }),+}));++vi.mock("@/lib/clipboard", () => ({+ writeTextToClipboard,+}));++vi.mock("@/components/ui/alert", () => ({+ Alert: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+}));++vi.mock("@/components/ui/button", () => ({+ Button: ({+ children,+ onClick,+ disabled,+ "aria-label": ariaLabel,+ }: {+ children: React.ReactNode;+ onClick?: () => void;+ disabled?: boolean;+ "aria-label"?: string;+ }) => (+ <button+ type="button"+ aria-label={ariaLabel}+ disabled={disabled}+ onClick={onClick}+ >+ {children}+ </button>+ ),+}));++vi.mock("@/components/ui/dropdown-menu", () => ({+ DropdownMenu: ({ children }: { children: React.ReactNode }) => <>{children}</>,+ DropdownMenuContent: ({ children }: { children: React.ReactNode }) => (+ <>{children}</>+ ),+ DropdownMenuItem: ({+ children,+ onClick,+ }: {+ children: React.ReactNode;+ onClick?: () => void;+ }) => (+ <button type="button" onClick={onClick}>+ {children}+ </button>+ ),+ DropdownMenuTrigger: ({ render }: { render: React.ReactNode }) => render,+}));++vi.mock("@/components/ui/switch", () => ({+ Switch: ({+ checked,+ onCheckedChange,+ }: {+ checked: boolean;+ onCheckedChange: (checked: boolean) => void;+ }) => (+ <input+ type="checkbox"+ checked={checked}+ onChange={(event) => onCheckedChange(event.target.checked)}+ />+ ),+}));++vi.mock("@/components/ui/tooltip", () => ({+ Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}));++vi.mock("@/modules/sql-editor/hooks/useSQLEditorState", () => ({+ useSQLEditorQueryDataPolicy: () => ({ maximumResultRows: 1000 }),+}));++vi.mock("@/modules/sql-editor/store/editor", () => ({+ useSQLEditorEditorState: (+ selector: (state: { project: string; resultRowsLimit: number }) => unknown+ ) => selector({ project: "projects/prod", resultRowsLimit: 100 }),+}));++vi.mock("@/modules/sql-editor/store/tab", () => ({+ useSQLEditorTabState: (+ selector: (state: {+ currentTabId: string;+ tabsById: Map<string, { mode: string }>;+ }) => unknown+ ) =>+ selector({+ currentTabId: "tab-1",+ tabsById: new Map([["tab-1", { mode: "READ_ONLY" }]]),+ }),+}));++vi.mock("@/stores/app", () => ({+ useAppStore: {+ getState: () => ({ notify: vi.fn() }),+ },+}));++vi.mock("@/utils/pev2", () => ({+ createExplainToken: vi.fn(),+}));++vi.mock("@/utils/util", () => ({+ isNullOrUndefined: (value: unknown) => value === null || value === undefined,+}));++vi.mock("@/utils/v1/database", () => ({+ getInstanceResource: (database: Database) => database.instanceResource,+}));++vi.mock("@/utils/v1/sql", () => ({+ compareQueryRowValues: () => 0,+ extractSQLRowValuePlain: (value?: {+ kind?: { case: string; value?: unknown };+ }) => value?.kind?.value,+}));++vi.mock("./DetailPanel", () => ({+ DetailPanel: () => <div data-testid="detail-panel" />,+}));++vi.mock("./context", () => ({+ SQLResultViewProvider: ({ children }: { children: React.ReactNode }) => (+ <>{children}</>+ ),+ useSelectionContext: () => ({+ canCopyAsInsert: false,+ copy: vi.fn(),+ }),+}));++vi.mock("./EmptyView", () => ({+ EmptyView: () => <div data-testid="empty-view" />,+}));++vi.mock("./ErrorView", () => ({+ ErrorView: () => <div data-testid="error-view" />,+}));++vi.mock("./ResultStatusBar", () => ({+ ResultStatusBar: () => <div data-testid="result-status" />,+}));++vi.mock("./SelectionCopyTooltips", () => ({+ SelectionCopyTooltips: () => <div data-testid="selection-tooltips" />,+}));++vi.mock("./VirtualDataBlock", () => ({+ VirtualDataBlock: () => <div data-testid="result-block" />,+}));++vi.mock("./VirtualDataTable", () => ({+ VirtualDataTable: ({+ rows,+ columns,+ }: {+ rows: Array<{+ item: {+ values: Array<{ kind: { case: string; value?: unknown } }>;+ };+ }>;+ columns: Array<{ name: string }>;+ }) => (+ <div data-testid="result-table">+ {columns.map((column) => column.name).join(",")}+ {rows+ .flatMap((row) => row.item.values)+ .map((value) => String(value.kind.value ?? ""))+ .join(",")}+ </div>+ ),+}));++const params: SQLEditorQueryParams = {+ connection: {+ database: "instances/prod/databases/main",+ instance: "instances/prod",+ },+ engine: Engine.COSMOSDB,+ explain: false,+ selection: null,+ statement: "SELECT * FROM c",+};++const databaseForEngine = (engine: Engine) =>+ ({+ name: "instances/prod/databases/main",+ project: "projects/prod",+ instanceResource: {+ name: "instances/prod",+ engine,+ },+ }) as Database;++const documentResult = () =>+ create(QueryResultSchema, {+ columnNames: ["result"],+ columnTypeNames: ["TEXT"],+ rows: [+ create(QueryRowSchema, {+ values: [+ create(RowValueSchema, {+ kind: {+ case: "stringValue",+ value:+ '{"id":"one","profile":{"tags":["a","b"]},"ssn":"******"}',+ },+ }),+ ],+ }),+ ],+ });++describe("SingleResultView document view", () => {+ beforeEach(() => {+ localStorage.clear();+ deltaDecorations.mockClear();+ findMatches.mockClear();+ revealRangeInCenter.mockClear();+ writeTextToClipboard.mockClear();+ });++ test.each([Engine.COSMOSDB, Engine.MONGODB])(+ "defaults %s results to native JSON and switches to the table",+ (engine) => {+ render(+ <SingleResultView+ disallowCopyingData+ params={{ ...params, engine }}+ database={databaseForEngine(engine)}+ result={documentResult()}+ showExport={false}+ />+ );++ expect(screen.getByText("sql-editor.table-view")).toBeInTheDocument();+ expect(screen.getByText("sql-editor.json-view")).toBeInTheDocument();+ expect(+ screen.getByRole("radiogroup", {+ name: "sql-editor.result-view-mode",+ })+ ).toHaveClass("h-7");+ expect(+ screen.getByText("sql-editor.json-view").closest("label")+ ).toHaveClass("bg-accent/10", "text-accent");+ expect(+ screen.getByText("sql-editor.json-view").closest("label")+ ).not.toHaveClass("bg-accent", "text-accent-text");+ expect(document.querySelector(".lucide-table-2")).toBeInTheDocument();+ expect(document.querySelector(".lucide-braces")).toBeInTheDocument();+ expect(screen.getByText("sql-editor.table-view")).toHaveClass("sr-only");+ expect(screen.getByText("sql-editor.json-view")).toHaveClass("sr-only");+ expect(+ screen.getByRole("region", { name: "sql-editor.json-view" })+ ).toHaveTextContent('"tags": [');+ expect(screen.getByRole("region")).toHaveTextContent('"ssn": "******"');+ expect(screen.queryByTestId("result-table")).not.toBeInTheDocument();+ expect(screen.queryByTestId("result-search")).not.toBeInTheDocument();+ expect(+ screen.queryByText("sql-editor.vertical-display")+ ).not.toBeInTheDocument();+ expect(screen.queryByText("common.copy-all")).not.toBeInTheDocument();+ expect(screen.queryByTestId("selection-tooltips")).not.toBeInTheDocument();++ fireEvent.click(screen.getByText("sql-editor.table-view"));+ expect(screen.getByTestId("result-table")).toHaveTextContent(+ "id,profile,ssn"+ );+ expect(screen.getByTestId("result-table")).toHaveTextContent("******");+ }+ );++ test("does not persist the document view selection", () => {+ const props = {+ disallowCopyingData: true,+ params,+ database: databaseForEngine(Engine.COSMOSDB),+ result: documentResult(),+ showExport: false,+ };+ const view = render(<SingleResultView {...props} />);++ fireEvent.click(screen.getByText("sql-editor.table-view"));+ expect(screen.getByTestId("result-table")).toBeInTheDocument();++ view.unmount();+ render(<SingleResultView {...props} />);++ expect(+ screen.getByRole("region", { name: "sql-editor.json-view" })+ ).toBeInTheDocument();+ });++ test("does not offer JSON mode for relational or malformed results", () => {+ const relationalResult = create(QueryResultSchema, {+ columnNames: ["name"],+ columnTypeNames: ["TEXT"],+ rows: [+ create(QueryRowSchema, {+ values: [+ create(RowValueSchema, {+ kind: { case: "stringValue", value: "Ada" },+ }),+ ],+ }),+ ],+ });+ const { rerender } = render(+ <SingleResultView+ disallowCopyingData+ params={{ ...params, engine: Engine.POSTGRES }}+ database={databaseForEngine(Engine.POSTGRES)}+ result={relationalResult}+ showExport={false}+ />+ );++ expect(screen.queryByText("sql-editor.json-view")).not.toBeInTheDocument();++ rerender(+ <SingleResultView+ disallowCopyingData+ params={params}+ database={databaseForEngine(Engine.COSMOSDB)}+ result={+ create(QueryResultSchema, {+ columnNames: ["result"],+ rows: [+ create(QueryRowSchema, {+ values: [+ create(RowValueSchema, {+ kind: { case: "stringValue", value: "{" },+ }),+ ],+ }),+ ],+ })+ }+ showExport={false}+ />+ );++ expect(screen.queryByText("sql-editor.json-view")).not.toBeInTheDocument();+ });++ test("copies JSON", () => {+ render(+ <SingleResultView+ disallowCopyingData={false}+ params={params}+ database={databaseForEngine(Engine.COSMOSDB)}+ result={documentResult()}+ showExport={false}+ />+ );++ fireEvent.click(screen.getByText("common.copy-all"));++ expect(writeTextToClipboard).toHaveBeenCalledWith(+ expect.stringContaining('"ssn": "******"')+ );+ });++ test("searches JSON matches and moves the active match", async () => {+ render(+ <SingleResultView+ disallowCopyingData+ params={params}+ database={databaseForEngine(Engine.COSMOSDB)}+ result={documentResult()}+ showExport={false}+ />+ );++ fireEvent.click(screen.getByText("sql-editor.json-view"));+ const search = screen.getByRole("textbox", { name: "common.search" });+ expect(search.parentElement).toHaveClass("flex-1");+ fireEvent.change(search, { target: { value: "ssn" } });++ await waitFor(() => {+ expect(screen.getByText("1 / 2")).toBeInTheDocument();+ });+ expect(findMatches).toHaveBeenLastCalledWith(+ "ssn",+ false,+ false,+ false,+ null,+ false+ );+ expect(revealRangeInCenter).toHaveBeenLastCalledWith(+ expect.objectContaining({ startLineNumber: 2 })+ );++ fireEvent.click(+ screen.getByRole("button", {+ name: "sql-editor.result-detail.next-match",+ })+ );++ await waitFor(() => {+ expect(screen.getByText("2 / 2")).toBeInTheDocument();+ });+ expect(revealRangeInCenter).toHaveBeenLastCalledWith(+ expect.objectContaining({ startLineNumber: 4 })+ );+ });++ test("keeps the existing Elasticsearch table toggle", () => {+ const result = create(QueryResultSchema, {+ columnNames: ["hits"],+ columnTypeNames: ["JSON"],+ rows: [+ create(QueryRowSchema, {+ values: [+ create(RowValueSchema, {+ kind: {+ case: "stringValue",+ value:+ '{"hits":[{"_id":"one","_score":1,"_source":{"name":"Ada"}}]}',+ },+ }),+ ],+ }),+ ],+ });++ render(+ <SingleResultView+ disallowCopyingData+ params={{ ...params, engine: Engine.ELASTICSEARCH }}+ database={databaseForEngine(Engine.ELASTICSEARCH)}+ result={result}+ showExport={false}+ />+ );++ expect(screen.queryByText("sql-editor.json-view")).not.toBeInTheDocument();+ expect(screen.getByTestId("result-table")).toHaveTextContent(+ "_id,_score,name"+ );++ const [tableViewToggle] = screen.getAllByRole("checkbox");+ fireEvent.click(tableViewToggle);+ expect(screen.getByTestId("result-table")).toHaveTextContent("hits");+ });+});diff --git a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsxindex cab7191c2a..0d10ae4e5e 100644--- a/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/SingleResultView.tsx@@ -3,9 +3,11 @@ import { isEmpty } from "lodash-es";import {ArrowDownIcon,ArrowUpIcon,+ BracesIcon,ChevronDownIcon,CopyIcon,InfoIcon,+ Table2Icon,XIcon,} from "lucide-react";import {@@ -36,9 +38,11 @@ import {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";import { useExecuteSQL } from "@/hooks/useExecuteSQL";+import { writeTextToClipboard } from "@/lib/clipboard";import { cn } from "@/lib/utils";import { useSQLEditorQueryDataPolicy } from "@/modules/sql-editor/hooks/useSQLEditorState";import { useSQLEditorEditorState } from "@/modules/sql-editor/store/editor";@@ -60,6 +64,8 @@ import { createExplainToken } from "@/utils/pev2";import {flattenElasticsearchSearchResult,flattenNoSQLQueryResult,+ formatNoSQLQueryResultForJSONView,+ type NoSQLJSONDocument,} from "@/utils/sqlResult";import { STORAGE_KEY_SQL_EDITOR_NOSQL_TABLE_VIEW } from "@/utils/storage-keys";import { isNullOrUndefined } from "@/utils/util";@@ -68,10 +74,12 @@ import { compareQueryRowValues, extractSQLRowValuePlain } from "@/utils/v1/sql";import { SQLResultViewProvider, useSelectionContext } from "./context";import { formatAsCSV, formatAsSQL, formatAsText } from "./copy-formats";import { DetailPanel } from "./DetailPanel";+import { DocumentJSONView } from "./DocumentJSONView";import { EmptyView } from "./EmptyView";import { ErrorView } from "./ErrorView";import { ResultStatusBar } from "./ResultStatusBar";import { SelectionCopyTooltips } from "./SelectionCopyTooltips";+import { TextSearchControl } from "./TextSearchControl";import type { ResultTableColumn, ResultTableRow, SortState } from "./types";import {VirtualDataBlock,@@ -102,6 +110,7 @@ export interface SingleResultViewProps {}type ViewMode = "RESULT" | "EMPTY" | "AFFECTED-ROWS" | "ERROR";+type DocumentViewMode = "TABLE" | "JSON";/*** Per-result-set view. Owns the per-mount `<SQLResultViewProvider>` plus@@ -120,6 +129,7 @@ export function SingleResultView(props: SingleResultViewProps) {STORAGE_KEY_SQL_EDITOR_NOSQL_TABLE_VIEW,true);+ const [documentTableView, setDocumentTableView] = useState(false);// 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@@ -127,18 +137,36 @@ export function SingleResultView(props: SingleResultViewProps) {// the table rendered sorted rows, Cmd+C would copy the wrong row.const [sortState, setSortState] = useState<SortState | undefined>();+ const isDocumentEngine =+ engine === Engine.COSMOSDB || engine === Engine.MONGODB;const flattened = useMemo(() => {if (engine === Engine.ELASTICSEARCH) {return flattenElasticsearchSearchResult(result);}- if (engine === Engine.MONGODB) {+ if (isDocumentEngine) {return flattenNoSQLQueryResult(result);}return undefined;- }, [engine, result]);- const supportsTableViewToggle = flattened !== undefined;- const activeResult =- supportsTableViewToggle && noSQLTableView ? flattened : result;+ }, [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";+ const supportsTableViewToggle =+ engine === Engine.ELASTICSEARCH && flattened !== undefined;+ const activeResult = isDocumentEngine+ ? (flattened ?? result)+ : supportsTableViewToggle && noSQLTableView+ ? flattened+ : result;+ const flattenedTableView =+ flattened !== undefined && activeResult === flattened;const columns: ResultTableColumn[] = useMemo(() =>@@ -207,9 +235,15 @@ export function SingleResultView(props: SingleResultViewProps) {rows={rows}sortState={sortState}toggleSort={toggleSort}+ flattenedTableView={flattenedTableView}supportsTableViewToggle={supportsTableViewToggle}noSQLTableView={noSQLTableView}setNoSQLTableView={setNoSQLTableView}+ supportsDocumentJSONView={supportsDocumentJSONView}+ documentJSON={documentJSON}+ documentJSONDocuments={documentJSONViewResult?.documents ?? []}+ documentViewMode={documentViewMode}+ setDocumentViewMode={(mode) => setDocumentTableView(mode === "TABLE")}/></SQLResultViewProvider>);@@ -222,9 +256,15 @@ interface SingleResultViewInnerProps extends SingleResultViewProps {rows: ResultTableRow[];sortState: SortState | undefined;toggleSort: (columnIndex: number) => void;+ flattenedTableView: boolean;supportsTableViewToggle: boolean;noSQLTableView: boolean;setNoSQLTableView: (next: boolean) => void;+ supportsDocumentJSONView: boolean;+ documentJSON: string | undefined;+ documentJSONDocuments: NoSQLJSONDocument[];+ documentViewMode: DocumentViewMode;+ setDocumentViewMode: (mode: DocumentViewMode) => void;}function SingleResultViewInner({@@ -243,9 +283,15 @@ function SingleResultViewInner({rows,sortState,toggleSort,+ flattenedTableView,supportsTableViewToggle,noSQLTableView,setNoSQLTableView,+ supportsDocumentJSONView,+ documentJSON,+ documentJSONDocuments,+ documentViewMode,+ setDocumentViewMode,compact = false,}: SingleResultViewInnerProps) {const { t } = useTranslation();@@ -283,6 +329,28 @@ function SingleResultViewInner({const [searchCandidateRowIndexs, setSearchCandidateRowIndexs] = useState<number[]>([]);+ const [documentSearchQuery, setDocumentSearchQuery] = useState("");+ const [documentSearchActiveIndex, setDocumentSearchActiveIndex] = useState(0);+ const [documentSearchMatchCount, setDocumentSearchMatchCount] = useState(0);++ useEffect(() => {+ setDocumentSearchQuery("");+ setDocumentSearchActiveIndex(0);+ setDocumentSearchMatchCount(0);+ }, [documentJSON]);++ useEffect(() => {+ setDocumentSearchActiveIndex(0);+ }, [documentSearchQuery]);++ useEffect(() => {+ setDocumentSearchActiveIndex((current) => {+ if (documentSearchMatchCount === 0) {+ return 0;+ }+ return Math.min(current, documentSearchMatchCount - 1);+ });+ }, [documentSearchMatchCount]);// Reset search state when toggling NoSQL table view (sort reset is// handled by the wrapper, where sortState lives).@@ -433,7 +501,7 @@ function SingleResultViewInner({const isSensitiveColumn = useCallback((columnIndex: number): boolean => {- if (supportsTableViewToggle && noSQLTableView) return false;+ if (flattenedTableView) return false;const reason = result.masked?.[columnIndex];return (reason !== null &&@@ -442,12 +510,12 @@ function SingleResultViewInner({reason.semanticTypeId !== "");},- [result.masked, supportsTableViewToggle, noSQLTableView]+ [flattenedTableView, result.masked]);const getMaskingReason = useCallback((columnIndex: number) => {- if (supportsTableViewToggle && noSQLTableView) return undefined;+ if (flattenedTableView) return undefined;if (!result.masked || columnIndex >= result.masked.length) {return undefined;}@@ -455,7 +523,7 @@ function SingleResultViewInner({if (!reason || !reason.semanticTypeId) return undefined;return reason;},- [result.masked, supportsTableViewToggle, noSQLTableView]+ [flattenedTableView, result.masked]);const showVisualizeButton =@@ -490,6 +558,19 @@ function SingleResultViewInner({}, [result]);const resultRowsText = `${rows.length} ${t("sql-editor.rows.self")}`;+ const isJSONView =+ supportsDocumentJSONView &&+ documentViewMode === "JSON" &&+ documentJSON !== undefined;+ const moveDocumentSearchMatch = (offset: number) => {+ if (documentSearchMatchCount === 0) {+ return;+ }+ setDocumentSearchActiveIndex(+ (current) =>+ (current + offset + documentSearchMatchCount) % documentSearchMatchCount+ );+ };const handleExport = (req: DataExportRequest) => {// Forward the user-typed query (`params.statement`) rather than@@ -501,6 +582,13 @@ function SingleResultViewInner({onExport?.({ ...req, statement: params.statement });};+ const handleCopyJSON = () => {+ if (disallowCopyingData || !documentJSON) {+ return;+ }+ void writeTextToClipboard(documentJSON);+ };+// ---- Render branches by viewMode ----if (viewMode === "AFFECTED-ROWS") {@@ -545,13 +633,23 @@ function SingleResultViewInner({{/* Toolbar */}<div className="result-toolbar relative w-full shrink-0 flex flex-row gap-x-4 justify-between items-center mb-2 hide-scrollbar"><div className="flex flex-row justify-start items-center gap-x-2 mr-2 flex-1">- <AdvancedSearch- params={searchParams}- scopeOptions={searchScopeOptions}- placeholder=""- onParamsChange={setSearchParams}- onEnter={scrollToNextCandidate}- />+ {isJSONView ? (+ <TextSearchControl+ query={documentSearchQuery}+ activeMatchIndex={documentSearchActiveIndex}+ matchCount={documentSearchMatchCount}+ onQueryChange={setDocumentSearchQuery}+ onMove={moveDocumentSearchMatch}+ />+ ) : (+ <AdvancedSearch+ params={searchParams}+ scopeOptions={searchScopeOptions}+ placeholder=""+ onParamsChange={setSearchParams}+ onEnter={scrollToNextCandidate}+ />+ )}<Tooltipcontent={reachQueryLimit ? t("sql-editor.rows-upper-limit") : ""@@ -566,7 +664,42 @@ function SingleResultViewInner({</Tooltip></div><div className="flex justify-between items-center shrink-0 gap-x-2">- {supportsTableViewToggle && (+ {supportsDocumentJSONView ? (+ <SegmentedControl<DocumentViewMode>+ value={documentViewMode}+ options={[+ {+ value: "TABLE",+ label: (+ <span className="flex h-[26px] w-7 items-center justify-center">+ <Table2Icon className="size-4" aria-hidden />+ <span className="sr-only">+ {t("sql-editor.table-view")}+ </span>+ </span>+ ),+ tooltip: t("sql-editor.table-view"),+ },+ {+ value: "JSON",+ label: (+ <span className="flex h-[26px] w-7 items-center justify-center">+ <BracesIcon className="size-4" aria-hidden />+ <span className="sr-only">+ {t("sql-editor.json-view")}+ </span>+ </span>+ ),+ tooltip: t("sql-editor.json-view"),+ },+ ]}+ onValueChange={setDocumentViewMode}+ ariaLabel={t("sql-editor.result-view-mode")}+ appearance="soft"+ className="h-7 flex-nowrap"+ size="xs"+ />+ ) : supportsTableViewToggle ? (<div className="flex items-center gap-x-1"><Switchchecked={noSQLTableView}@@ -576,14 +709,27 @@ function SingleResultViewInner({{t("sql-editor.table-view")}</span></div>+ ) : null}+ {!isJSONView && (+ <div className="flex items-center gap-x-1">+ <Switch checked={vertical} onCheckedChange={setVertical} />+ <span className="whitespace-nowrap text-sm text-control-light">+ {t("sql-editor.vertical-display")}+ </span>+ </div>)}- <div className="flex items-center gap-x-1">- <Switch checked={vertical} onCheckedChange={setVertical} />- <span className="whitespace-nowrap text-sm text-control-light">- {t("sql-editor.vertical-display")}- </span>- </div>- {!disallowCopyingData && rows.length > 0 && (+ {!disallowCopyingData && rows.length > 0 && isJSONView && (+ <Button+ size="sm"+ appearance="outline"+ className="h-7 px-2 text-control border-control-border hover:bg-control-bg-hover"+ onClick={handleCopyJSON}+ >+ <CopyIcon className="size-4" />+ {t("common.copy-all")}+ </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">@@ -648,110 +794,122 @@ function SingleResultViewInner({requestExportSlot)}</div>- <SelectionCopyTooltips />+ {!isJSONView && <SelectionCopyTooltips />}</div>{/* Body */}- <div- className={cn(- "w-full flex flex-col relative",- compact- ? "h-80 overflow-hidden"- : "flex-1 min-h-0 overflow-y-auto"- )}- >- {vertical ? (- <VirtualDataBlock- ref={dataTableRef as React.RefObject<VirtualDataBlockHandle>}- rows={rows}- columns={columns}- isSensitiveColumn={isSensitiveColumn}- getMaskingReason={getMaskingReason}- database={database}- statement={params.statement}- activeRowIndex={activeRowIndex}- search={searchParams}- />- ) : (- <VirtualDataTable- ref={dataTableRef as React.RefObject<VirtualDataTableHandle>}- rows={rows}- columns={columns}- isSensitiveColumn={isSensitiveColumn}- getMaskingReason={getMaskingReason}- database={database}- statement={params.statement}- sortState={sortState}- activeRowIndex={activeRowIndex}- search={searchParams}- onToggleSort={toggleSort}- />- )}-- {/* Floating buttons */}- <div className="absolute bottom-2 right-4 flex items-end gap-x-2">- {searchCandidateRowIndexs.length > 0 && (- <div className="flex flex-row gap-x-2 border shadow rounded bg-background py-1 px-2">- <Button- size="sm"- appearance="secondary"- disabled={searchCandidateActiveIndex <= 0}- onClick={scrollToPreviousCandidate}- >- <ArrowUpIcon className="size-4" />- {t("sql-editor.previous-row")}- </Button>- <Button- size="sm"- appearance="secondary"- disabled={- searchCandidateActiveIndex >=- searchCandidateRowIndexs.length - 1- }- onClick={scrollToNextCandidate}- >- <ArrowDownIcon className="size-4" />- {t("sql-editor.next-row")}- </Button>- <Button- size="sm"- appearance="secondary"- className="size-7 p-0"- onClick={clearSearchCandidate}- >- <XIcon className="size-4" />- </Button>- </div>+ {isJSONView ? (+ <DocumentJSONView+ content={documentJSON}+ documents={documentJSONDocuments}+ disallowCopyingData={disallowCopyingData}+ compact={compact}+ searchQuery={documentSearchQuery}+ activeMatchIndex={documentSearchActiveIndex}+ onMatchCountChange={setDocumentSearchMatchCount}+ />+ ) : (+ <div+ className={cn(+ "w-full flex flex-col relative",+ compact+ ? "h-80 overflow-hidden"+ : "flex-1 min-h-0 overflow-y-auto"+ )}+ >+ {vertical ? (+ <VirtualDataBlock+ ref={dataTableRef as React.RefObject<VirtualDataBlockHandle>}+ rows={rows}+ columns={columns}+ isSensitiveColumn={isSensitiveColumn}+ getMaskingReason={getMaskingReason}+ database={database}+ statement={params.statement}+ activeRowIndex={activeRowIndex}+ search={searchParams}+ />+ ) : (+ <VirtualDataTable+ ref={dataTableRef as React.RefObject<VirtualDataTableHandle>}+ rows={rows}+ columns={columns}+ isSensitiveColumn={isSensitiveColumn}+ getMaskingReason={getMaskingReason}+ database={database}+ statement={params.statement}+ sortState={sortState}+ activeRowIndex={activeRowIndex}+ search={searchParams}+ onToggleSort={toggleSort}+ />)}- <div className="flex flex-col gap-y-2 result-scroll-buttons">- <Tooltip content={t("sql-editor.scroll-to-top")}>- <div className="rounded-full shadow bg-background">+ {/* Floating buttons */}+ <div className="absolute bottom-2 right-4 flex items-end gap-x-2">+ {searchCandidateRowIndexs.length > 0 && (+ <div className="flex flex-row gap-x-2 border shadow rounded bg-background py-1 px-2"><Buttonsize="sm"appearance="secondary"- className="size-9 p-0 rounded-full"- onClick={() => scrollToRow(0)}+ disabled={searchCandidateActiveIndex <= 0}+ onClick={scrollToPreviousCandidate}><ArrowUpIcon className="size-4" />+ {t("sql-editor.previous-row")}</Button>- </div>- </Tooltip>- <Tooltip content={t("sql-editor.scroll-to-bottom")}>- <div className="rounded-full shadow bg-background"><Buttonsize="sm"appearance="secondary"- className="size-9 p-0 rounded-full"- onClick={() => scrollToRow(rows.length - 1)}+ disabled={+ searchCandidateActiveIndex >=+ searchCandidateRowIndexs.length - 1+ }+ onClick={scrollToNextCandidate}><ArrowDownIcon className="size-4" />+ {t("sql-editor.next-row")}+ </Button>+ <Button+ size="sm"+ appearance="secondary"+ className="size-7 p-0"+ onClick={clearSearchCandidate}+ >+ <XIcon className="size-4" /></Button></div>- </Tooltip>+ )}++ <div className="flex flex-col gap-y-2 result-scroll-buttons">+ <Tooltip content={t("sql-editor.scroll-to-top")}>+ <div className="rounded-full shadow bg-background">+ <Button+ size="sm"+ appearance="secondary"+ className="size-9 p-0 rounded-full"+ onClick={() => scrollToRow(0)}+ >+ <ArrowUpIcon className="size-4" />+ </Button>+ </div>+ </Tooltip>+ <Tooltip content={t("sql-editor.scroll-to-bottom")}>+ <div className="rounded-full shadow bg-background">+ <Button+ size="sm"+ appearance="secondary"+ className="size-9 p-0 rounded-full"+ onClick={() => scrollToRow(rows.length - 1)}+ >+ <ArrowDownIcon className="size-4" />+ </Button>+ </div>+ </Tooltip>+ </div></div></div>- </div>+ )}{/* Status bar */}<ResultStatusBar@@ -764,7 +922,7 @@ function SingleResultViewInner({</>)}- <DetailPanel rows={rows} columns={columns} />+ {!isJSONView && <DetailPanel rows={rows} columns={columns} />}</>);}diff --git a/frontend/src/modules/sql-editor/components/ResultView/TextSearchControl.tsx b/frontend/src/modules/sql-editor/components/ResultView/TextSearchControl.tsxnew file mode 100644index 0000000000..5fc52d7bdc--- /dev/null+++ b/frontend/src/modules/sql-editor/components/ResultView/TextSearchControl.tsx@@ -0,0 +1,121 @@+import {+ ChevronDownIcon,+ ChevronUpIcon,+ SearchIcon,+ XIcon,+} from "lucide-react";+import { useEffect, useRef } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Tooltip } from "@/components/ui/tooltip";+import { cn } from "@/lib/utils";+import { searchMatchCountLabel } from "./detail-panel-search";++interface TextSearchControlProps {+ query: string;+ activeMatchIndex: number;+ matchCount: number;+ onQueryChange: (query: string) => void;+ onMove: (offset: number) => void;+}++export function TextSearchControl({+ query,+ activeMatchIndex,+ matchCount,+ onQueryChange,+ onMove,+}: TextSearchControlProps) {+ const { t } = useTranslation();+ const inputRef = useRef<HTMLInputElement>(null);+ const searchActive = query.trim().length > 0;++ useEffect(() => {+ const handler = (event: KeyboardEvent) => {+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "f") {+ event.preventDefault();+ event.stopPropagation();+ inputRef.current?.focus();+ inputRef.current?.select();+ }+ };+ document.addEventListener("keydown", handler, true);+ return () => document.removeEventListener("keydown", handler, true);+ }, []);++ return (+ <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"+ )}+ >+ <SearchIcon className="ml-2.5 size-4 shrink-0 text-control-placeholder" />+ <Input+ ref={inputRef}+ size="sm"+ aria-label={t("common.search")}+ className="h-7 min-w-0 flex-1 border-0 px-2 text-sm focus:ring-0"+ placeholder={t("common.search")}+ value={query}+ autoComplete="off"+ onChange={(event) => onQueryChange(event.target.value)}+ onKeyDown={(event) => {+ if (event.key !== "Enter") {+ return;+ }+ event.preventDefault();+ onMove(event.shiftKey ? -1 : 1);+ }}+ />+ {searchActive && (+ <span className="min-w-10 text-center text-xs text-control-light">+ {searchMatchCountLabel(activeMatchIndex, matchCount)}+ </span>+ )}+ {searchActive && (+ <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"+ aria-label={t("sql-editor.result-detail.previous-match")}+ disabled={matchCount === 0}+ onClick={() => onMove(-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"+ aria-label={t("sql-editor.result-detail.next-match")}+ disabled={matchCount === 0}+ onClick={() => onMove(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"+ aria-label={t("common.close")}+ onClick={() => {+ onQueryChange("");+ inputRef.current?.focus();+ }}+ >+ <XIcon className="size-4" />+ </Button>+ </Tooltip>+ </div>+ )}+ </div>+ );+}diff --git a/frontend/src/utils/sqlResult.test.ts b/frontend/src/utils/sqlResult.test.tsindex 47b673ffca..f953f148a6 100644--- a/frontend/src/utils/sqlResult.test.ts+++ b/frontend/src/utils/sqlResult.test.ts@@ -5,7 +5,11 @@ import {QueryRowSchema,RowValueSchema,} from "@/types/proto-es/v1/sql_service_pb";-import { flattenNoSQLQueryResult } from "./sqlResult";+import {+ flattenNoSQLQueryResult,+ formatNoSQLQueryResultAsJSON,+ formatNoSQLQueryResultForJSONView,+} from "./sqlResult";describe("flattenNoSQLQueryResult", () => {test("flattens raw MongoDB document rows into table columns on demand", () => {@@ -63,4 +67,142 @@ describe("flattenNoSQLQueryResult", () => {expect(flattenNoSQLQueryResult(result)).toBeUndefined();});++ test("returns undefined when any document row contains malformed JSON", () => {+ const result = createProto(QueryResultSchema, {+ columnNames: ["result"],+ rows: [+ createProto(QueryRowSchema, {+ values: [+ createProto(RowValueSchema, {+ kind: { case: "stringValue", value: '{"name":"Ada"}' },+ }),+ ],+ }),+ createProto(QueryRowSchema, {+ values: [+ createProto(RowValueSchema, {+ kind: { case: "stringValue", value: "{" },+ }),+ ],+ }),+ ],+ });++ expect(flattenNoSQLQueryResult(result)).toBeUndefined();+ });+});++describe("formatNoSQLQueryResultAsJSON", () => {+ test("formats document rows without changing field order or large numbers", () => {+ const result = createProto(QueryResultSchema, {+ columnNames: ["result"],+ columnTypeNames: ["TEXT"],+ rows: [+ createProto(QueryRowSchema, {+ values: [+ createProto(RowValueSchema, {+ kind: {+ case: "stringValue",+ value:+ '{"id":"one","profile":{"tags":["a","b"]},"counter":9007199254740993}',+ },+ }),+ ],+ }),+ createProto(QueryRowSchema, {+ values: [+ createProto(RowValueSchema, {+ kind: {+ case: "stringValue",+ value:+ '{"id":"two","value":{"$numberLong":"9007199254740994"}}',+ },+ }),+ ],+ }),+ ],+ });++ expect(formatNoSQLQueryResultAsJSON(result)).toBe(`[+ {+ "id": "one",+ "profile": {+ "tags": [+ "a",+ "b"+ ]+ },+ "counter": 9007199254740993+ },+ {+ "id": "two",+ "value": {+ "$numberLong": "9007199254740994"+ }+ }+]`);++ expect(formatNoSQLQueryResultForJSONView(result)?.documents).toEqual([+ {+ content: `{+ "id": "one",+ "profile": {+ "tags": [+ "a",+ "b"+ ]+ },+ "counter": 9007199254740993+}`,+ startLineNumber: 2,+ endLineNumber: 11,+ },+ {+ content: `{+ "id": "two",+ "value": {+ "$numberLong": "9007199254740994"+ }+}`,+ startLineNumber: 12,+ endLineNumber: 17,+ },+ ]);+ });++ test("rejects results that are not JSON document rows", () => {+ const wrongColumn = createProto(QueryResultSchema, {+ columnNames: ["name"],+ rows: [],+ });+ const nonStringValue = createProto(QueryResultSchema, {+ columnNames: ["result"],+ rows: [+ createProto(QueryRowSchema, {+ values: [+ createProto(RowValueSchema, {+ kind: { case: "int32Value", value: 1 },+ }),+ ],+ }),+ ],+ });+ const malformedJSON = createProto(QueryResultSchema, {+ columnNames: ["result"],+ rows: [+ createProto(QueryRowSchema, {+ values: [+ createProto(RowValueSchema, {+ kind: { case: "stringValue", value: "{" },+ }),+ ],+ }),+ ],+ });++ expect(formatNoSQLQueryResultAsJSON(wrongColumn)).toBeUndefined();+ expect(formatNoSQLQueryResultAsJSON(nonStringValue)).toBeUndefined();+ expect(formatNoSQLQueryResultAsJSON(malformedJSON)).toBeUndefined();+ });});diff --git a/frontend/src/utils/sqlResult.ts b/frontend/src/utils/sqlResult.tsindex 513ef396b1..c4cd0d1c7e 100644--- a/frontend/src/utils/sqlResult.ts+++ b/frontend/src/utils/sqlResult.ts@@ -5,9 +5,9 @@ import {isLosslessNumber,type LosslessNumber,parse as losslessParse,+ stringify as losslessStringify,} from "lossless-json";import { stringify } from "uuid";-import type { SQLResultSetV1 } from "@/types";import type {QueryResult,QueryRow,@@ -251,19 +251,6 @@ const convertAnyToRowValue = (}};-export const flattenNoSQLResult = (resultSet: SQLResultSetV1) => {- for (const result of resultSet.results) {- const flattened = flattenNoSQLQueryResult(result);- if (!flattened) {- continue;- }-- result.rows = flattened.rows;- result.columnNames = flattened.columnNames;- result.columnTypeNames = flattened.columnTypeNames;- }-};-export const flattenNoSQLQueryResult = (result: QueryResult): QueryResult | undefined => {@@ -275,7 +262,11 @@ export const flattenNoSQLQueryResult = (return undefined;}- const { columns, columnIndexMap } = getNoSQLColumns(result.rows);+ const columnInfo = getNoSQLColumns(result.rows);+ if (!columnInfo) {+ return undefined;+ }+ const { columns, columnIndexMap } = columnInfo;if (columns.length === 0) {return undefined;}@@ -286,16 +277,10 @@ export const flattenNoSQLQueryResult = ();for (const row of result.rows) {- if (row.values.length !== 1 || row.values[0].kind.case !== "stringValue") {+ const data = getNoSQLRows(row);+ if (!data) {return undefined;}-- // Use lossless-json to preserve precision for large integers (> 2^53-1)- const data = losslessParse(- row.values[0].kind.value,- null,- losslessReviver- ) as Record<string, unknown>;const values: RowValue[] = Array.from({ length: columns.length }).map(() =>createProto(RowValueSchema, {kind: {@@ -305,7 +290,7 @@ export const flattenNoSQLQueryResult = (}));- for (const [key, value] of Object.entries(data)) {+ for (const { key, value } of data) {const index = columnIndexMap.get(key) ?? 0;const { value: formatted, type } = convertAnyToRowValue(value, true);values[index] = formatted;@@ -331,6 +316,67 @@ export const flattenNoSQLQueryResult = (});};+export interface NoSQLJSONDocument {+ content: string;+ startLineNumber: number;+ endLineNumber: number;+}++export interface NoSQLJSONViewResult {+ content: string;+ documents: NoSQLJSONDocument[];+}++export const formatNoSQLQueryResultForJSONView = (+ result: QueryResult+): NoSQLJSONViewResult | 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()) {+ if (row.values.length !== 1 || row.values[0].kind.case !== "stringValue") {+ return undefined;+ }+ try {+ const document = losslessStringify(+ losslessParse(row.values[0].kind.value),+ null,+ 2+ );+ 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,+ });+ } catch {+ return undefined;+ }+ }+ lines.push("]");++ return { content: lines.join("\n"), documents };+};++export const formatNoSQLQueryResultAsJSON = (+ result: QueryResult+): string | undefined => formatNoSQLQueryResultForJSONView(result)?.content;+// Parses the hits array from an Elasticsearch _search QueryResult's "hits" column.const parseESHitsArray = (result: QueryResult): unknown[] | undefined => {const hitsColIdx = result.columnNames.indexOf("hits");@@ -460,7 +506,7 @@ const getNoSQLColumns = (rows: QueryRow[]) => {for (const row of rows) {const parsedRows = getNoSQLRows(row);if (!parsedRows) {- continue;+ return undefined;}for (const item of parsedRows) {columnSet.add(item.key);@@ -500,13 +546,19 @@ const getNoSQLRows = (row: QueryRow): NoSQLRowData[] | undefined => {return;}// Use lossless-json to preserve precision for large integers (> 2^53-1)- const parsedRow = losslessParse(- row.values[0].kind.value,- null,- losslessReviver- ) as {- [key: string]: Record<string, unknown>;- };+ let parsedRow: unknown;+ try {+ parsedRow = losslessParse(row.values[0].kind.value, null, losslessReviver);+ } catch {+ return undefined;+ }+ if (+ typeof parsedRow !== "object" ||+ parsedRow === null ||+ Array.isArray(parsedRow)+ ) {+ return undefined;+ }const results: NoSQLRowData[] = [];for (const [key, value] of Object.entries(parsedRow)) {