Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor(react): migrate result view (#20227)
ecmadaod486fdfbd205
diff --git a/docs/superpowers/specs/2026-05-07-sql-editor-react-migration-stage-20-design.md b/docs/superpowers/specs/2026-05-07-sql-editor-react-migration-stage-20-design.mdnew file mode 100644index 0000000000..32fd274f64--- /dev/null+++ b/docs/superpowers/specs/2026-05-07-sql-editor-react-migration-stage-20-design.md@@ -0,0 +1,322 @@+# SQL Editor React Migration — Stage 20 Design++**Date:** 2026-05-07+**Author:** [email protected]+**Status:** Draft++## 1. Goal & non-goals++**Goal:** Migrate the SQL Editor's `ResultView` subsystem (the result-set+display) plus its two direct hosts (`DatabaseQueryContext.vue` and the+`<ResultViewV1>` mount inside `TerminalPanel.vue`) from Vue to React.+This is the perf-critical headline of the migration: `VirtualDataTable`+is the piece users notice when running 10k+ row queries. After this+stage, only the host shells remain (`Stage 21`), and the Vue+`DataExportButton.vue` becomes deletable.++**Non-goals:**+- Host shells (`StandardPanel`, `TerminalPanel`, `ResultPanel`,+ `Panels`, `EditorPanel`, `SQLEditorHomePage`, `SQLEditorPage`) — Stage 21.+- Visual / behavioral changes — parity port only. No new features.+- Restoring the result-pane test coverage to 100%; the Vue tree has+ zero tests today, so we add a perf seed suite but don't backfill+ comprehensive unit tests.+- AI plugin port — separate effort.++## 2. Inventory++**In scope (~2,771 LOC):**++| File | LOC | Notes |+|---|---|---|+| `EditorCommon/ResultView/SingleResultViewV1.vue` | 833 | Heaviest. Single-result orchestrator: tabs (TABLE / VERTICAL), search box + scroll-to-row, export toolbar, selection summary, copy-tooltips host, vertical/table mode toggle, detail-panel drawer trigger. |+| `EditorCommon/ResultView/VirtualDataTable.vue` | 458 | Perf-critical. Sticky-header table layout with column resizing, binary-format buttons per column, row/column selection. Uses Naive UI `NVirtualList` with fixed 35px row height. Exposes `scrollTo(index)` via `defineExpose`. |+| `EditorCommon/ResultView/ResultViewV1.vue` | 359 | Multi-result tab router (a query can return multiple result sets). Mounts `SingleResultViewV1` per result. Routes errors to `ErrorView`. |+| `EditorCommon/ResultView/DetailPanel.vue` | 303 | Modal/drawer viewer for the full content of a single cell (long string, JSON pretty-print, binary hex/utf8/base64). |+| `EditorCommon/ResultView/TableCell.vue` | 233 | Per-cell formatter: string (escape + truncate), JSON (inline / collapse), binary (hex / utf8 / base64), sensitive-data masked icon, NULL placeholder. |+| `EditorCommon/ResultView/ErrorView.vue` | 146 | Generic error display with copy / Postgres-specific delegate. |+| `EditorCommon/ResultView/VirtualDataBlock.vue` | 144 | Vertical "card" mode: each row renders as a stacked block. Dynamic row height (`60 + columns.length * 28`), same `scrollTo(index)` API. |+| `EditorCommon/ResultView/BinaryFormatButton.vue` | 72 | Three-button group (hex / utf8 / base64) per binary column. |+| `EditorCommon/ResultView/SelectionCopyTooltips.vue` | 59 | Floating toolbar over the selected range — copy as TSV / JSON. |+| `EditorCommon/ResultView/PrettyJSON.vue` | 56 | JSON pretty-printer (used by `DetailPanel` and `TableCell`). |+| `EditorCommon/ResultView/SensitiveDataIcon.vue` | 41 | Lock-icon trigger that opens the React `MaskingReasonPopover` via `ReactPageMount`. |+| `EditorCommon/ResultView/PostgresError.vue` | 41 | PG-specific error message formatter (line/position highlight). |+| `EditorCommon/ResultView/ColumnSortedIcon.vue` | 19 | Sort-direction caret SVG. |+| `EditorCommon/ResultView/EmptyView.vue` | 14 | "No rows" placeholder. |+| `EditorCommon/ResultView/{context,binary-format-store,selection-logic,index}.ts` | ~190 | Shared state: SQLResultViewContext (provide/inject), binary format toggles, selection ranges, barrel exports. |+| `EditorPanel/ResultPanel/DatabaseQueryContext.vue` | 125 | Direct host of `<ResultViewV1>`. Wraps it with a status overlay (PENDING / EXECUTING / DONE / CANCELLED). Co-migrates because the imperative coupling is tight. |++**Total**: ~2,771 LOC across ~17 files.++### Out of scope (later stages)++```+StandardPanel.vue → Stage 21+TerminalPanel.vue (the wrapping shell) → Stage 21 (the inner ResultViewV1 mount migrates here)+ResultPanel.vue → Stage 21+Panels.vue → Stage 21+EditorPanel.vue → Stage 21+SQLEditorHomePage.vue → Stage 21+SQLEditorPage.vue → Stage 21+components/DataExportButton.vue → deletable after this stage+```++## 3. External deps & primitives++| Vue dep | React replacement | Status |+|---|---|---|+| `NVirtualList` (Naive UI virtualization) | `@tanstack/react-virtual` `useVirtualizer` | ✓ Already a peer (used by other React tables) |+| `NTabs` / `NTabPane` (multi-result tab strip) | shadcn `Tabs` (`@/react/components/ui/tabs`) | ✓ |+| `NSwitch` (table/vertical toggle) | shadcn `Switch` | ✓ |+| `NButton` / `NTooltip` | shadcn `Button` + shared `Tooltip` | ✓ |+| Naive UI `darkTheme` (terminal mode) | Tailwind `dark:` variants on the React components | ✓ |+| `NConfigProvider` (dark theme scope) | not needed — Tailwind variants travel with React tree | ✓ |+| Vue `provide` / `inject` for `SQLResultViewContext` | React context (one provider per `<ResultViewV1>` mount) | ✓ |+| `binary-format-store` (Vue reactive Map) | React state in the same context, mutators via callbacks | ✓ |+| `selection-logic` (custom Vue composable for row/col selection) | React hook + ref-driven imperative range management | ✓ |+| `useLocalStorage` (`@vueuse/core`) | shared React hook (or `useSyncExternalStore` over `localStorage`) — Stage 16/17 already has a pattern | ✓ |+| `useElementSize` | `ResizeObserver` in a `useEffect`, or a shared `useElementSize` React hook (peer Stage 17 pattern) | ✓ |+| `lucide-vue-next` icons | `lucide-react` | ✓ |+| `@bufbuild/protobuf` | same package | ✓ |+| `lodash-es`, `dayjs`, `uuid` | same packages | ✓ |+| Vue `defineExpose({ scrollTo })` on `VirtualDataTable`/`VirtualDataBlock` | `useImperativeHandle` + ref forwarding, OR direct `useVirtualizer` ref consumed by parent | Needs decision (§4) |++**Key call-out**: the React `DataExportButton.tsx` already exists (built in Stage 18). The two Vue `<DataExportButton>` mounts inside `ResultViewV1.vue` and `SingleResultViewV1.vue` swap to the React component as part of this stage, which finally lets us delete the Vue `DataExportButton.vue`.++## 4. Architecture & phases++### Pre-Stage — Perf baseline spike (~1 day, no code merge)++Before porting `VirtualDataTable`, capture a Vue baseline so we have+something to compare against:++- Run a query that returns **10,000 rows × 12 columns** (mix of string,+ number, JSON, NULL, binary).+- Capture: scroll FPS (Chrome devtools perf trace), heap size at idle,+ time-to-first-paint after results arrive, time to render after+ scrolling 5k rows down, memory delta after toggling table↔vertical+ mode 5 times.+- Repeat with **100,000 rows × 12 columns** to find the breaking point.+- Document the numbers in `docs/superpowers/specs/2026-05-XX-stage-20-perf-baseline.md`.++Spike output is the **acceptance criteria for the React port**: parity+or better on every metric, with no regression beyond noise (±5%) at the+10k row scale.++### Phase 1 — Foundations (types, context, leaves)++1. Port `types/*.ts` and the shared state modules:+ - `EditorCommon/ResultView/context.ts` → `react/components/sql-editor/ResultView/context.tsx`+ — React context (per `<ResultViewV1>` mount). Holds: `dark` flag,+ `disallowCopyingData` flag, `detail` (current cell open in detail+ panel), `dataIsTrimmed` flag, the binary-format Map, the selection+ ranges. Mirrors the per-instance pattern from Stage 19.+ - `binary-format-store.ts` → React state inside the context.+ - `selection-logic.ts` → React hook (`useResultSelection`) returning+ `{ ranges, addRange, clearRanges, isSelected(row, col) }`.++2. Port the small leaves 1:1. They're pure presentation:+ - `EmptyView.tsx`, `ColumnSortedIcon.tsx`, `SensitiveDataIcon.tsx`,+ `PostgresError.tsx`, `BinaryFormatButton.tsx`,+ `SelectionCopyTooltips.tsx`, `PrettyJSON.tsx`, `ErrorView.tsx`.++**Deliverables:** 8 React surfaces + 1 context + 2 hooks + 1 unit test (segment-overlap-style for `selection-logic`'s range merging math).++### Phase 2 — Cell rendering (`TableCell.tsx`)++`TableCell.vue` is 233 LOC of pure formatting logic — string escape ++truncate, JSON pretty-print toggle, binary format dispatch, sensitive+data lock icon, NULL placeholder. Most of this is straight 1:1.++The **only React-specific concern**: HTML escaping. The Vue version+uses `v-html` + a sanitizer. The React version uses+`dangerouslySetInnerHTML` + the same sanitizer (the shared+`getHighlightHTMLByRegExp` already does DOMPurify; reuse via the+`HighlightLabelText` rule from memory).++**Deliverables:** 1 React surface + 1 unit test (cell formatter dispatch by column type).++### Phase 3 — `DetailPanel.tsx`++The modal viewer for full cell content. Reuses `PrettyJSON` and+`BinaryFormatButton` from Phase 1. Mounts via the shared `Dialog`+primitive (not `Sheet` — this is read-only content viewing, per the+shadcn-skill rule: dialog for non-form interactions).++**Deliverables:** 1 React surface.++### Phase 4 — Virtualization (`VirtualDataTable.tsx` + `VirtualDataBlock.tsx`)++The headline. Both components use `@tanstack/react-virtual`'s+`useVirtualizer`. Decision points:++**Imperative API surface (`scrollTo(index)`):**+- Vue exposed `scrollTo(index)` via `defineExpose`. Callers (`SingleResultViewV1`) used it for search-result navigation and mode-toggle restore.+- React equivalent: forward the `useVirtualizer` ref directly via `useImperativeHandle`. Simpler than building a wrapper imperative API — `useVirtualizer` already exposes `scrollToIndex(index, { align })` natively.++**Row height:**+- `VirtualDataTable` — fixed 35px, `estimateSize: () => 35` is enough.+- `VirtualDataBlock` — dynamic. Use `measureElement()` per row + `estimateSize: () => 60 + columns.length * 28` as a starting hint.++**Column resizing:**+- Vue uses pointer-event handlers + a width Map. React port reuses the `useColumnWidths` hook from Stage 18's `DatabaseTableView` work (already proven).++**Selection (row/column checkboxes):**+- Driven by the `useResultSelection` hook from Phase 1.+- `SelectionCopyTooltips` (Phase 1) renders the floating toolbar.++**Deliverables:** 2 React surfaces + 1 unit test (virtualizer mount + scrollToIndex math) + perf benchmark comparing 10k-row scroll vs. Vue baseline.++### Phase 5 — `SingleResultViewV1.tsx` (the orchestrator)++The 833-LOC heavy. It composes everything:+- Mode toggle (table / vertical)+- Search input + match navigation (highlights cells, calls `scrollToIndex`)+- Export toolbar — mounts the React `DataExportButton` (already built in Stage 18)+- Selection summary + copy tooltips+- Detail panel mount+- Sensitive-data masking — already React via `ReactPageMount`; in the React tree this becomes a direct mount (no bridge)++**Risks:** the search-highlight loop runs over the full row set. On 10k rows this is O(rows × cols) per keystroke. The Vue version debounces; the React port must match (debounce 200ms + only highlight visible-window rows; full-table match is computed once and stored as a `Set<rowIndex>`).++**Deliverables:** 1 React surface + 1 unit test (search match index computation).++### Phase 6 — `ResultViewV1.tsx`++Multi-result tab router. Lightweight — wraps a `Tabs` primitive over an array of result sets. Each tab renders a `<SingleResultView>`. Errors route to `<ErrorView>`.++**Deliverables:** 1 React surface.++### Phase 7 — `DatabaseQueryContext.tsx` + `TerminalPanel` mount swap++1. Port `DatabaseQueryContext.vue` (125 LOC) → `DatabaseQueryContext.tsx`.+ The status-overlay state machine (PENDING / EXECUTING / DONE / CANCELLED) is read from `tabStore.currentTab.databaseQueryContexts` via `useVueState`. The execute / re-execute / cancel buttons call into `useExecuteSQL()` and the `events.cancel-query` channel.+2. Add a top-level page shim at `react/components/sql-editor/DatabaseQueryContext.tsx` for `mount.ts` lookup.+3. Swap the two Vue host points:+ - `ResultPanel.vue`'s `<DatabaseQueryContext>` mount → `<ReactPageMount page="DatabaseQueryContext" :page-props="{ database, context }" />`.+ - `TerminalPanel.vue`'s `<ResultViewV1>` mount → `<ReactPageMount page="TerminalResultView" ... />` (a thin wrapper that adapts the dark / loading props).++**Deliverables:** 1 React surface + 1 page shim + 1 wrapper + 2 host-side swaps.++### Phase 8 — Vue tree deletion++Delete the entire `frontend/src/views/sql-editor/EditorCommon/ResultView/` Vue tree (~17 files). Delete `frontend/src/views/sql-editor/EditorPanel/ResultPanel/DatabaseQueryContext.vue`. Delete `frontend/src/components/DataExportButton.vue` (last consumers gone). Update barrels and route imports. Run gates.++**Deliverables:** ~19 file deletions + barrel cleanups + green gates.++## 5. Per-phase checklist++### Phase 1 — Foundations+- [ ] `ResultView/context.tsx` (React context + provider)+- [ ] `useResultSelection` hook + segment-merge unit test+- [ ] `useBinaryFormat` hook (per-column format toggle)+- [ ] `EmptyView.tsx`, `ColumnSortedIcon.tsx`, `SensitiveDataIcon.tsx`,+ `PostgresError.tsx`, `BinaryFormatButton.tsx`,+ `SelectionCopyTooltips.tsx`, `PrettyJSON.tsx`, `ErrorView.tsx`++### Phase 2 — Cell+- [ ] `TableCell.tsx` (string / JSON / binary / sensitive / NULL formatter)+- [ ] Unit test for cell formatter dispatch++### Phase 3 — DetailPanel+- [ ] `DetailPanel.tsx` (Dialog primitive, JSON pretty-print + binary toggle)++### Phase 4 — Virtualization+- [ ] `VirtualDataTable.tsx` (`useVirtualizer`, fixed 35px rows, sticky header)+- [ ] `VirtualDataBlock.tsx` (`useVirtualizer` + `measureElement`, dynamic row height)+- [ ] `useImperativeHandle({ scrollToIndex })` on both+- [ ] Reuse `useColumnWidths` (Stage 18) for column drag-resize+- [ ] Unit test for `scrollToIndex` math+- [ ] **Perf benchmark** vs. Vue baseline at 10k and 100k rows++### Phase 5 — Single result+- [ ] `SingleResultView.tsx` (mode toggle, search, export toolbar, detail trigger, selection summary)+- [ ] Search-match index computation memoized; only visible-window cells receive highlight DOM+- [ ] Unit test for search-match index++### Phase 6 — Multi result+- [ ] `ResultView.tsx` (`Tabs` primitive over result sets)++### Phase 7 — Caller swap+- [ ] `DatabaseQueryContext.tsx` (status state machine + cancel)+- [ ] Page shim for `mount.ts`+- [ ] `ResultPanel.vue` swap to `<ReactPageMount page="DatabaseQueryContext">`+- [ ] `TerminalPanel.vue` swap (terminal-mode wrapper)++### Phase 8 — Cleanup+- [ ] Delete `EditorCommon/ResultView/` Vue tree+- [ ] Delete `ResultPanel/DatabaseQueryContext.vue`+- [ ] Delete `components/DataExportButton.vue` (last live caller gone)+- [ ] Gates green+- [ ] Manual UX verification (§6)++## 6. Manual UX verification++- **Run a 10k-row query** → result paints in < 500 ms, scroll FPS ≥ 55 (Chrome desktop, no extensions).+- **Run a 100k-row query** → result paints, scroll FPS ≥ 30. Memory at idle within 20% of Vue baseline.+- **Toggle table ↔ vertical** mode 10× quickly → no memory growth, no visible flicker.+- **Search** for a substring with 200+ matches → debounced; UI doesn't lag while typing.+- **Click a cell** → DetailPanel opens; toggle JSON / binary modes; close.+- **Multi-cell selection**: click + shift-click → selection range highlights, copy tooltips appear, copy-as-TSV / JSON write the right content.+- **Export** → DataExportButton drawer opens (now React, same behavior); CSV / JSON / SQL / XLSX downloads; password-protected ZIP works for batch query mode.+- **Multi-result set** (procedure that returns 3 result sets) → Tabs strip renders, switching tabs preserves scroll position per tab.+- **Error result** → `ErrorView` renders message + copy; PG errors show line/position highlight.+- **Sensitive data** → masked cells show lock icon; clicking opens the React `MaskingReasonPopover`.+- **Terminal mode** (`TerminalPanel`) → dark theme applies to the result view; result table renders correctly under dark colors.++## 7. Out of scope (deferred)++- The five host shells (`Panels`, `EditorPanel`, `StandardPanel`,+ `TerminalPanel`, `ResultPanel`, `SQLEditorHomePage`, `SQLEditorPage`)+ — Stage 21.+- AI plugin port — separate effort.+- Result-pane test coverage beyond the perf seed + targeted unit tests.++## 8. Risks & open questions++- **`@tanstack/react-virtual` dynamic-height differences vs. NVirtualList.**+ NVirtualList's `estimateRowHeight` callback is per-render. react-virtual+ uses a per-item measure via `measureElement`, which means heights+ stabilize after one render-and-measure round. For `VirtualDataBlock`'s+ card mode this means the first scroll past unrendered rows might+ shift — typical react-virtual behavior. Acceptable; widely accepted+ trade-off vs. a wrapper.++- **Perf parity.** The Vue NVirtualList is well-tuned; react-virtual is+ also well-tuned. Risk areas: search highlight loop, cell formatter+ cost, column-resize re-layout. Mitigations: debounce search; memoize+ cell formatter results per cell value (LRU); column-resize uses+ CSS `width` only on the colgroup, no row re-render.++- **Selection-range UX.** Vue's `selection-logic.ts` has subtle behavior+ for shift-click to extend, ctrl-click to toggle, drag-select. Port+ exactly — write the unit test against the Vue rules first to lock in+ behavior, then make the React hook pass.++- **Detail panel layering.** `DetailPanel` is a Dialog. It must mount+ via `getLayerRoot("overlay")` (per the React layering policy). Verify+ the AI side pane stacking still makes sense when the detail dialog is+ open + AI panel is open simultaneously.++- **Search highlighting on 100k rows.** Vue debounces but still loops+ over all rows once on commit. React port must do the same; the+ match-index `Set<number>` is then read-only at render time, only the+ windowed rows render highlights. No regression expected.++- **DataExportButton swap is the unlock.** Once `ResultViewV1` and+ `SingleResultViewV1` are React, both consumers of the Vue+ `DataExportButton.vue` are gone. Verify with `find-dead-vue.mjs`+ before deleting. Should be the last live caller.++- **TerminalPanel's dark mode.** Currently uses `NConfigProvider` ++ `darkTheme` at the Vue level. The React port relies on Tailwind+ `dark:` variants — but these are class-based, not theme-context-+ based. Need to either (a) toggle a `dark` class on the terminal's+ ResultView wrapper, or (b) pass a `dark` prop down through the+ context. Option (b) matches Vue's current `dark` prop flow and is+ the recommended path.++- **No existing tests.** Every test added in this stage is new. Don't+ block on full coverage — seed targeted suites for the math-heavy+ pieces (selection ranges, search index, scroll math), let the rest+ ride on manual UX verification.diff --git a/frontend/package.json b/frontend/package.jsonindex 854727f897..ae2b505357 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -40,6 +40,7 @@"@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2","@markdoc/markdoc": "0.5.5",+ "@tanstack/react-virtual": "^3.13.24","@vueuse/core": "14.2.1","bootstrap": "5.3.8","class-variance-authority": "^0.7.1",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex cc0a91b3ee..f4eddccd5b 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -63,6 +63,9 @@ importers:'@markdoc/markdoc':specifier: 0.5.5version: 0.5.5(@types/[email protected])([email protected])+ '@tanstack/react-virtual':+ specifier: ^3.13.24'@vueuse/core':specifier: 14.2.1version: 14.2.1([email protected]([email protected]))@@ -2146,6 +2149,15 @@ packages:peerDependencies:vite: ^5.2.0 || ^6 || ^7+ '@tanstack/[email protected]':+ resolution: {integrity: sha512-aIJvz5OSkhNIhZIpYivrxrPTKYsjW9Uzy+sP/mx0S3sev2HyvPb7xmjbYvokzEpfgYHy/HjzJ2zFAETuUfgCpg==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+ react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-JLANqGy/D6k4Ujmh8Tr25lGimuOXNiaVyXaCAZS0W+1390sADdGnyUdSWNIfd49gebtIxGMij4IktRVzrdr12Q==}+'@tsconfig/[email protected]':resolution: {integrity: sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==}@@ -7032,6 +7044,14 @@ snapshots:tailwindcss: 4.2.1vite: 7.3.2(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ dependencies:+ '@tanstack/virtual-core': 3.14.0+ react: 19.2.4+ react-dom: 19.2.4([email protected])++ '@tanstack/[email protected]': {}+'@tsconfig/[email protected]': {}'@tsconfig/[email protected]': {}diff --git a/frontend/src/AuthContext.vue b/frontend/src/AuthContext.vueindex 754df62a8b..053849a522 100644--- a/frontend/src/AuthContext.vue+++ b/frontend/src/AuthContext.vue@@ -44,7 +44,7 @@ const subscriptionStore = useSubscriptionV1Store();const ready = ref(false);-const authCheckIntervalId = ref<NodeJS.Timeout>();+const authCheckIntervalId = ref<ReturnType<typeof setInterval>>();const isAuthRoute = computed(() => {return (diff --git a/frontend/src/components/DataExportButton.vue b/frontend/src/components/DataExportButton.vuedeleted file mode 100644index ae135667fe..0000000000--- a/frontend/src/components/DataExportButton.vue+++ /dev/null@@ -1,414 +0,0 @@-<template>- <NDropdown- trigger="hover"- :options="exportDropdownOptions"- :disabled="viewMode === 'DRAWER' || disabled"- @select="tryExportViaDropdown"- >- <NTooltip :disabled="!tooltip">- <template #trigger>- <NButton- :quaternary="size === 'tiny'"- :size="size"- type="primary"- v-bind="$attrs"- :loading="state.isRequesting"- :disabled="state.isRequesting || disabled"- @click="handleClickExportButton"- >- <template #icon>- <DownloadIcon class="h-4 w-4" />- </template>- <span v-if="size !== 'tiny'">- {{ text }}- </span>- </NButton>- </template>- <span class="text-sm"> {{ tooltip }} </span>- </NTooltip>- </NDropdown>-- <Drawer v-if="viewMode === 'DRAWER'" v-model:show="state.showDrawer">- <DrawerContent- :title="$t('custom-approval.risk-rule.risk.namespace.data_export')"- class="w-200 max-w-[100vw] relative"- >- <template #default>- <NForm- ref="formRef"- :model="formData"- :rules="rules"- label-placement="left"- >- <slot name="form" />- <NFormItem path="limit" :label="$t('export-data.export-rows')">- <MaxRowCountSelect- ref="maxRowCountSelectRef"- :maximum="maximumExportCount"- v-model:value="formData.limit"- />- </NFormItem>- <NFormItem path="format" :label="$t('export-data.export-format')">- <NRadioGroup v-model:value="formData.format">- <NRadio- v-for="format in supportFormats"- :key="format"- :value="format"- >- {{ ExportFormat[format] }}- </NRadio>- </NRadioGroup>- </NFormItem>- <NFormItem- v-if="supportPassword"- path="password"- :label="$t('export-data.password-optional')"- >- <BBTextField- v-model:value="formData.password"- type="password"- :input-props="{ autocomplete: 'new-password' }"- />- </NFormItem>- </NForm>- </template>- <template #footer>- <div class="flex flex-row items-center justify-end gap-x-3">- <NButton @click="state.showDrawer = false">- {{ $t("common.cancel") }}- </NButton>- <ErrorTipsButton- :button-props="{- type: 'primary',- loading: state.isRequesting,- disabled:- formErrors.length > 0 ||- state.isRequesting ||- !validate(formData),- }"- :errors="formErrors"- @click="tryExportViaForm"- >- {{ $t("common.confirm") }}- </ErrorTipsButton>- </div>- </template>- </DrawerContent>- </Drawer>-- <BBModal- :show="state.showModal"- :title="$t('export-data.password-optional')"- class="shadow-inner outline-solid outline-gray-200"- @close="state.showModal = false"- >- <div class="w-80">- <span class="textinfolabel">{{ $t("export-data.password-info") }}</span>- <BBTextField- v-model:value="formData.password"- class="my-2"- :focus-on-mount="true"- />- </div>- <div class="w-full flex items-center justify-end mt-2 gap-x-3">- <NButton @click="state.showModal = false">- {{ $t("common.cancel") }}- </NButton>- <NButton type="primary" @click="exportViaDropdown">- {{ $t("common.export") }}- </NButton>- </div>- </BBModal>-</template>--<script lang="ts" setup>-import { asyncComputed } from "@vueuse/core";-import dayjs from "dayjs";-import saveAs from "file-saver";-import JSZip from "jszip";-import { DownloadIcon } from "lucide-vue-next";-import type { FormInst, FormRules } from "naive-ui";-import {- NButton,- NDropdown,- NForm,- NFormItem,- NRadio,- NRadioGroup,- NTooltip,-} from "naive-ui";-import { computed, nextTick, reactive, ref, watch } from "vue";-import { BBModal, BBTextField } from "@/bbkit";-import { t } from "@/plugins/i18n";-import { pushNotification } from "@/store";-import { ExportFormat } from "@/types/proto-es/v1/common_pb";-import { isNullOrUndefined } from "@/utils";-import MaxRowCountSelect from "./RoleGrantPanel/MaxRowCountSelect.vue";-import { Drawer, DrawerContent, ErrorTipsButton } from "./v2";--interface LocalState {- isRequesting: boolean;- showDrawer: boolean;- showModal: boolean;-}--export type DownloadContent = {- content: Uint8Array;- filename: string;-};--export interface ExportOption {- limit: number;- format: ExportFormat;- password: string;-}--const props = withDefaults(- defineProps<{- size?: "small" | "tiny" | "medium" | "large";- disabled?: boolean;- supportFormats: ExportFormat[];- supportPassword?: boolean;- viewMode: "DRAWER" | "DROPDOWN";- tooltip?: string;- text?: string;- validate?: (option: ExportOption) => boolean;- maximumExportCount?: number;- }>(),- {- size: "small",- disabled: false,- tooltip: undefined,- supportPassword: false,- text: () => t("common.export"),- validate: (_: ExportOption) => true,- maximumExportCount: Number.MAX_VALUE,- }-);--const maxRowCountSelectRef = ref<InstanceType<typeof MaxRowCountSelect>>();--const defaultFormData = (): ExportOption => ({- limit: Math.min(- maxRowCountSelectRef.value?.maximum ?? Number.MAX_VALUE,- 1000- ),- format: props.supportFormats[0],- password: "",-});--const emit = defineEmits<{- (- event: "export",- option: {- resolve: (content: DownloadContent[]) => void;- reject: (reason?: unknown) => void;- options: ExportOption;- }- ): Promise<void>;-}>();--const state = reactive<LocalState>({- isRequesting: false,- showDrawer: false,- showModal: false,-});-const formRef = ref<FormInst>();-const formData = ref<ExportOption>(defaultFormData());--const rules: FormRules = {- limit: [- {- required: true,- validator: (rule, value: number) => {- if (isNullOrUndefined(value)) {- return new Error(t("export-data.error.export-rows-required"));- }- if (value <= 0) {- return new Error(t("export-data.error.export-rows-must-gt-zero"));- }- return true;- },- trigger: ["input"],- },- ],- format: [- {- required: true,- },- ],-};--const exportDropdownOptions = computed(() => {- return props.supportFormats.map((format) => ({- label: t("sql-editor.download-as-file", {- file: ExportFormat[format],- }),- key: format,- }));-});--const tryExportViaDropdown = (format: ExportFormat) => {- formData.value.format = format;- if (props.supportPassword) {- state.showModal = true;- } else {- doExport();- }-};--const exportViaDropdown = () => {- state.showModal = false;- doExport();-};--const tryExportViaForm = (e: MouseEvent) => {- e.preventDefault();- formRef.value?.validate((errors) => {- if (errors) return;- doExport();- });-};--const formErrors = asyncComputed(() => {- if (!formRef.value) return [];- try {- return new Promise<string[]>((resolve) => {- formRef.value!.validate((errors) => {- resolve(- errors?.flatMap((err) => err.map((e) => e.message ?? "")) ?? []- );- });- });- } catch {- return [];- }-}, []);--const handleClickExportButton = (e: MouseEvent) => {- e.preventDefault();- if (props.viewMode === "DROPDOWN") return;-- state.showDrawer = true;-};--const doExport = () => {- if (state.isRequesting) {- return;- }-- state.isRequesting = true;- const options = { ...formData.value };-- new Promise<DownloadContent[]>((resolve, reject) => {- return emit("export", {- resolve,- reject,- options,- });- })- .then((content: DownloadContent[]) => {- return doDownload(content, options.format);- })- .then(() => {- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.succeed"),- description: t("audit-log.export-finished"),- });- })- .catch((error) => {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: `Failed to export data`,- description: JSON.stringify(error),- });- })- .finally(() => {- state.isRequesting = false;- state.showDrawer = false;- });-};--const getExportFileType = (format: ExportFormat) => {- switch (format) {- case ExportFormat.CSV:- return "text/csv";- case ExportFormat.JSON:- return "application/json";- case ExportFormat.SQL:- return "application/sql";- case ExportFormat.XLSX:- return "application/vnd.ms-excel";- }-};--const convertSingleFile = async (- { content, filename }: DownloadContent,- format: ExportFormat-) => {- const isZip = filename.endsWith(".zip");- const fileType = isZip ? "application/zip" : getExportFileType(format);-- // Create Blob from Uint8Array- const buffer = content.buffer.slice(- content.byteOffset,- content.byteOffset + content.byteLength- ) as ArrayBuffer; // TypeScript 5.9.2 requires explicit ArrayBuffer type- return new Blob([buffer], {- type: fileType,- });-};--const doDownloadSingleFile = async (- content: DownloadContent,- format: ExportFormat-) => {- const blob = await convertSingleFile(content, format);- const url = window.URL.createObjectURL(blob);-- const link = document.createElement("a");- link.download = content.filename;- link.href = url;- link.click();-};--const doDownload = async (content: DownloadContent[], format: ExportFormat) => {- if (content.length === 1) {- return doDownloadSingleFile(content[0], format);- }-- const zip = new JSZip();-- await Promise.all(- content.map(async (c) => {- const blob = await convertSingleFile(c, format);- zip.file(c.filename, blob);- })- );-- const zipFile = await zip.generateAsync({ type: "blob" });- const fileName = `download_${dayjs().format("YYYY-MM-DDTHH-mm-ss")}.zip`;- saveAs(zipFile, fileName);-};--watch(- () => [state.showDrawer, state.showModal],- ([showDrawer, showModal]) => {- if (showDrawer) {- formData.value = defaultFormData();- nextTick(() => {- formData.value.limit = Math.min(- maxRowCountSelectRef.value?.maximum ?? Number.MAX_VALUE,- formData.value.limit- );- });- } else if (showModal) {- formData.value.password = "";- }- },- { immediate: true }-);-</script>diff --git a/frontend/src/components/MonacoEditor/lsp-client.ts b/frontend/src/components/MonacoEditor/lsp-client.tsindex 7a319bd1fd..ed99030d3e 100644--- a/frontend/src/components/MonacoEditor/lsp-client.ts+++ b/frontend/src/components/MonacoEditor/lsp-client.ts@@ -27,7 +27,7 @@ export type ConnectionState = {lastCommand: ExecuteCommandParams | undefined;retries: number;heartbeat: {- timer: NodeJS.Timeout | undefined;+ timer: ReturnType<typeof setTimeout> | undefined;counter: number;timestamp: number;};diff --git a/frontend/src/layouts/BodyLayout.vue b/frontend/src/layouts/BodyLayout.vueindex 5d5e8915f1..15951daec5 100644--- a/frontend/src/layouts/BodyLayout.vue+++ b/frontend/src/layouts/BodyLayout.vue@@ -130,7 +130,7 @@ actuatorStore.tryToRemindRelease().then((openRemindModal) => {showReleaseModal.value = openRemindModal;});-const refreshRemindTimer = ref<NodeJS.Timeout>();+const refreshRemindTimer = ref<ReturnType<typeof setTimeout>>();onMounted(async () => {const remind = await actuatorStore.tryToRemindRefresh();if (remind) {diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 1c986b3ecf..2c692e9063 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -789,10 +789,7 @@"self": "Export Center"},"export-data": {- "error": {- "export-rows-must-gt-zero": "Export rows must greater than 0",- "export-rows-required": "Export rows required"- },+ "error": {},"export-format": "Export format","export-rows": "Export rows","password-info": "Provide a password to encrypt the export file.",@@ -1406,8 +1403,7 @@"self": "AI Assistant is not configured."},"send": "Send",- "text-to-sql-placeholder": "Use natural language and Bytebase will convert it into SQL",- "text2sql": "Text2SQL"+ "text-to-sql-placeholder": "Use natural language and Bytebase will convert it into SQL"}},"policy": {@@ -2414,7 +2410,6 @@"connection-lost": "Connection lost. Will try to reconnect when executing next query.","copy-all-column-names": "Copy all column names","copy-name": "Copy name",- "copy-selected-results": "Copy selected data by {action} or {button}","copy-url": "Copy URL","download-as-file": "Download as {file}","duration-day": "{days} day",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex fb7abde99e..910065d37c 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -789,10 +789,7 @@"self": "centro de exportacion"},"export-data": {- "error": {- "export-rows-must-gt-zero": "Las filas de exportación deben ser mayores que 0",- "export-rows-required": "Se requieren filas de exportación"- },+ "error": {},"export-format": "Formato de exportación","export-rows": "Exportar filas","password-info": "Proporcione una contraseña para cifrar el archivo de exportación.",@@ -1406,8 +1403,7 @@"self": "El Asistente AI no está configurado."},"send": "Enviar",- "text-to-sql-placeholder": "Utilice lenguaje natural y Bytebase lo convertirá en SQL",- "text2sql": "Text2SQL"+ "text-to-sql-placeholder": "Utilice lenguaje natural y Bytebase lo convertirá en SQL"}},"policy": {@@ -2414,7 +2410,6 @@"connection-lost": "Conexión perdida. \nIntentará volver a conectarse al ejecutar la siguiente consulta.","copy-all-column-names": "Copiar todos los nombres de las columnas","copy-name": "Copiar nombre",- "copy-selected-results": "Copiar datos seleccionados por {action} o {button}","copy-url": "Copiar URL","download-as-file": "Descargar como {file}","duration-day": "{days} day",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex a558f50066..496a76826a 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -789,10 +789,7 @@"self": "エクスポートセンター"},"export-data": {- "error": {- "export-rows-must-gt-zero": "エクスポート行の数は 0 より大きくなければなりません",- "export-rows-required": "エクスポート行数を指定する必要があります"- },+ "error": {},"export-format": "エクスポート形式","export-rows": "エクスポート行数","password-info": "エクスポートされたファイルを暗号化するためのパスワードを入力します",@@ -1406,8 +1403,7 @@"self": "AI アシスタントが設定されていません。"},"send": "送信",- "text-to-sql-placeholder": "ここに自然言語を入力すると、Bytebase はすぐにそれを SQL ステートメントに変換します。",- "text2sql": "Text2SQL"+ "text-to-sql-placeholder": "ここに自然言語を入力すると、Bytebase はすぐにそれを SQL ステートメントに変換します。"}},"policy": {@@ -2414,7 +2410,6 @@"connection-lost": "接続切断。次回クエリが実行されるときに再接続が試行されます。","copy-all-column-names": "すべての列名をコピーします","copy-name": "名前をコピーする",- "copy-selected-results": "選択したデータを{action}または{button}でコピーします","copy-url": "URLをコピー","download-as-file": "{file} 形式でダウンロード","duration-day": "{days} day",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 79b3f675ce..5e9a326499 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -789,10 +789,7 @@"self": "Trung tâm xuất"},"export-data": {- "error": {- "export-rows-must-gt-zero": "Số dòng xuất phải lớn hơn 0",- "export-rows-required": "Yêu cầu số dòng xuất"- },+ "error": {},"export-format": "Định dạng xuất","export-rows": "Xuất số dòng","password-info": "Cung cấp mật khẩu để mã hóa tệp xuất.",@@ -1406,8 +1403,7 @@"self": "Trợ lý AI chưa được định cấu hình."},"send": "Gửi",- "text-to-sql-placeholder": "Sử dụng ngôn ngữ tự nhiên và Bytebase sẽ chuyển đổi nó thành SQL",- "text2sql": "Chuyển văn bản thành SQL"+ "text-to-sql-placeholder": "Sử dụng ngôn ngữ tự nhiên và Bytebase sẽ chuyển đổi nó thành SQL"}},"policy": {@@ -2414,7 +2410,6 @@"connection-lost": "Mất kết nối. Sẽ thử kết nối lại khi thực hiện truy vấn tiếp theo.","copy-all-column-names": "Sao chép tất cả tên cột","copy-name": "Sao chép tên",- "copy-selected-results": "Sao chép dữ liệu đã chọn bằng {action} hoặc {button}","copy-url": "Sao chép URL","download-as-file": "Tải xuống dưới dạng {file}","duration-day": "{days} day",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex a983a9ecce..3815295ffa 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -789,10 +789,7 @@"self": "导出中心"},"export-data": {- "error": {- "export-rows-must-gt-zero": "导出行数必须大于 0",- "export-rows-required": "需要指定导出行数"- },+ "error": {},"export-format": "导出格式","export-rows": "导出行数","password-info": "提供密码来对导出的文件进行加密",@@ -1406,8 +1403,7 @@"self": "AI 助手尚未配置。"},"send": "发送",- "text-to-sql-placeholder": "在此输入自然语言后,Bytebase 会将其转换成 SQL 语句",- "text2sql": "Text2SQL"+ "text-to-sql-placeholder": "在此输入自然语言后,Bytebase 会将其转换成 SQL 语句"}},"policy": {@@ -2414,7 +2410,6 @@"connection-lost": "连接丢失。下一次执行查询时将尝试重新连接。","copy-all-column-names": "复制所有列名","copy-name": "复制名称",- "copy-selected-results": "通过 {action} 或 {button} 来快速复制选定的数据","copy-url": "复制 URL","download-as-file": "下载为 {file} 格式","duration-day": "{days} 天",diff --git a/frontend/src/react/components/AdvancedSearch.tsx b/frontend/src/react/components/AdvancedSearch.tsxindex 62bc631258..c78d3be0df 100644--- a/frontend/src/react/components/AdvancedSearch.tsx+++ b/frontend/src/react/components/AdvancedSearch.tsx@@ -58,6 +58,12 @@ interface AdvancedSearchProps {scopeOptions?: ScopeOption[];placeholder?: string;onParamsChange: (params: SearchParams) => void;+ /**+ * Fires on Enter while no scope/value dropdown is active. Hosts use this+ * for "press Enter to advance to the next match" — mirrors the Vue+ * `@keyup:enter` shortcut on the result-view search bar.+ */+ onEnter?: () => void;}const SCROLL_FADE_EPSILON = 1;@@ -151,6 +157,7 @@ export function AdvancedSearch({scopeOptions = [],placeholder,onParamsChange,+ onEnter,}: AdvancedSearchProps) {const { t } = useTranslation();const containerRef = useRef<HTMLDivElement>(null);@@ -561,6 +568,10 @@ export function AdvancedSearch({: raw;if (value) selectValue(value);}+ } else if (onEnter) {+ // No dropdown open — surface the Enter to the host (used by+ // result-view search to advance to the next matching row).+ onEnter();}}},@@ -578,6 +589,7 @@ export function AdvancedSearch({selectScope,selectValue,onParamsChange,+ onEnter,]);diff --git a/frontend/src/react/components/sql-editor/ResultView/BinaryFormatButton.tsx b/frontend/src/react/components/sql-editor/ResultView/BinaryFormatButton.tsxnew file mode 100644index 0000000000..e4a46dcb1e--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/BinaryFormatButton.tsx@@ -0,0 +1,66 @@+import { CodeIcon } from "lucide-react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/react/components/ui/popover";+import { RadioGroup, RadioGroupItem } from "@/react/components/ui/radio-group";+import { cn } from "@/react/lib/utils";+import type { BinaryFormat } from "./binary-format";++interface BinaryFormatButtonProps {+ format: BinaryFormat | undefined;+ onFormatChange: (format: BinaryFormat) => void;+}++export function BinaryFormatButton({+ format,+ onFormatChange,+}: BinaryFormatButtonProps) {+ const { t } = useTranslation();+ const current: BinaryFormat = format ?? "DEFAULT";+ const hasOverride = current !== "DEFAULT";++ const options: { value: BinaryFormat; label: string }[] = [+ { value: "DEFAULT", label: t("sql-editor.format-default") },+ { value: "BINARY", label: t("sql-editor.binary-format") },+ { value: "HEX", label: t("sql-editor.hex-format") },+ { value: "TEXT", label: t("sql-editor.text-format") },+ { value: "BOOLEAN", label: t("sql-editor.boolean-format") },+ ];++ return (+ <Popover>+ <PopoverTrigger+ render={+ <Button+ variant={hasOverride ? "default" : "outline"}+ size="sm"+ className={cn("ml-1 size-5 rounded-full p-0")}+ onClick={(e) => e.stopPropagation()}+ />+ }+ >+ <CodeIcon className="size-3" />+ </PopoverTrigger>+ <PopoverContent align="start" className="w-52 p-2">+ <div className="text-xs font-semibold mb-2">+ {t("sql-editor.column-display-format")}+ </div>+ <RadioGroup+ value={current}+ onValueChange={(next) => onFormatChange(next as BinaryFormat)}+ className="flex flex-col gap-2"+ >+ {options.map((option) => (+ <RadioGroupItem key={option.value} value={option.value}>+ {option.label}+ </RadioGroupItem>+ ))}+ </RadioGroup>+ </PopoverContent>+ </Popover>+ );+}diff --git a/frontend/src/react/components/sql-editor/ResultView/ColumnSortedIcon.tsx b/frontend/src/react/components/sql-editor/ResultView/ColumnSortedIcon.tsxnew file mode 100644index 0000000000..eaee3df4d6--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/ColumnSortedIcon.tsx@@ -0,0 +1,28 @@+import { ArrowDownWideNarrow, ArrowUpWideNarrow } from "lucide-react";+import { cn } from "@/react/lib/utils";+import type { SortDirection } from "./types";++interface ColumnSortedIconProps {+ isSorted: SortDirection;+}++export function ColumnSortedIcon({ isSorted }: ColumnSortedIconProps) {+ const showAsc = isSorted === "asc";+ // Explicit `size-3.5` on both wrapper and icon so Lucide's intrinsic+ // `width="24" height="24"` SVG attributes can't beat the CSS in any+ // browser. Matches the Vue version's compact 14px sort glyph.+ return (+ <span className="inline-flex size-3.5 opacity-80 shrink-0">+ {showAsc ? (+ <ArrowUpWideNarrow className="size-3.5 text-accent" />+ ) : (+ <ArrowDownWideNarrow+ className={cn(+ "size-3.5",+ isSorted === "desc" ? "text-accent" : "text-control-placeholder"+ )}+ />+ )}+ </span>+ );+}diff --git a/frontend/src/react/components/sql-editor/ResultView/DetailPanel.tsx b/frontend/src/react/components/sql-editor/ResultView/DetailPanel.tsxnew file mode 100644index 0000000000..0b7b4fed2f--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/DetailPanel.tsx@@ -0,0 +1,298 @@+import {+ parse as losslessParse,+ stringify as losslessStringify,+} from "lossless-json";+import {+ BracesIcon,+ CheckIcon,+ ChevronDownIcon,+ ChevronUpIcon,+ CopyIcon,+ WrapTextIcon,+} from "lucide-react";+import { useCallback, useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import {+ Sheet,+ SheetContent,+ SheetHeader,+ SheetTitle,+} from "@/react/components/ui/sheet";+import { Tooltip } from "@/react/components/ui/tooltip";+import { cn } from "@/react/lib/utils";+import {+ STORAGE_KEY_SQL_EDITOR_DETAIL_FORMAT,+ STORAGE_KEY_SQL_EDITOR_DETAIL_LINE_WRAP,+} from "@/utils/storage-keys";+import { BinaryFormatButton } from "./BinaryFormatButton";+import { getPlainValue } from "./cell-value";+import { useBinaryFormatContext, useSQLResultViewContext } from "./context";+import { PrettyJSON } from "./PrettyJSON";+import type { ResultTableColumn, ResultTableRow } from "./types";++interface DetailPanelProps {+ rows: ResultTableRow[];+ columns: ResultTableColumn[];+}++function useLocalStorageBoolean(+ key: string,+ defaultValue: boolean+): [boolean, (next: boolean) => void] {+ const [value, setValue] = useState<boolean>(() => {+ try {+ const raw = localStorage.getItem(key);+ if (raw === "true") return true;+ if (raw === "false") return false;+ } catch {+ // ignore+ }+ return defaultValue;+ });+ const update = useCallback(+ (next: boolean) => {+ setValue(next);+ try {+ localStorage.setItem(key, String(next));+ } catch {+ // ignore+ }+ },+ [key]+ );+ return [value, update];+}++export function DetailPanel({ rows, columns }: DetailPanelProps) {+ const { t } = useTranslation();+ const { dark, detail, disallowCopyingData, setDetail } =+ useSQLResultViewContext();+ const { getBinaryFormat, setBinaryFormat } = useBinaryFormatContext();+ const [copied, setCopied] = useState(false);++ const [format, setFormat] = useLocalStorageBoolean(+ STORAGE_KEY_SQL_EDITOR_DETAIL_FORMAT,+ false+ );+ const [wrap, setWrap] = useLocalStorageBoolean(+ STORAGE_KEY_SQL_EDITOR_DETAIL_LINE_WRAP,+ true+ );++ 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 isBinaryData = rawValue?.kind?.case === "bytesValue";++ const content = useMemo(+ () => getPlainValue(rawValue, columnType, binaryFormat),+ [rawValue, columnType, binaryFormat]+ );++ const guessedIsJSON = useMemo(() => {+ if (!content) return false;+ const trimmed = content.trim();+ return (+ (trimmed.startsWith("{") && trimmed.endsWith("}")) ||+ (trimmed.startsWith("[") && trimmed.endsWith("]"))+ );+ }, [content]);++ const move = useCallback(+ (offset: number) => {+ if (!detail) return;+ const target = detail.row + offset;+ if (target < 0 || target >= totalCount) return;+ setDetail({ ...detail, row: target });+ },+ [detail, totalCount, setDetail]+ );++ // Replicates Vue's onKeyStroke("ArrowUp"/"ArrowDown") row navigation while+ // the panel is open.+ useEffect(() => {+ if (!detail) return;+ const handler = (e: KeyboardEvent) => {+ if (e.key === "ArrowUp") {+ e.preventDefault();+ e.stopPropagation();+ move(-1);+ } else if (e.key === "ArrowDown") {+ e.preventDefault();+ e.stopPropagation();+ move(1);+ }+ };+ document.addEventListener("keydown", handler);+ return () => document.removeEventListener("keydown", handler);+ }, [detail, move]);++ const copyContent = useMemo(() => {+ const raw = content ?? "";+ if (guessedIsJSON && format) {+ try {+ const obj = losslessParse(raw);+ return losslessStringify(obj, null, " ") ?? raw;+ } catch {+ console.warn("[DetailPanel]", "failed to format JSON for copy");+ return raw;+ }+ }+ return raw;+ }, [content, guessedIsJSON, format]);++ const handleCopy = useCallback(async () => {+ try {+ await navigator.clipboard.writeText(copyContent);+ setCopied(true);+ window.setTimeout(() => setCopied(false), 2000);+ } catch {+ // ignore+ }+ }, [copyContent]);++ const isOpen = !!detail;+ const handleOpenChange = (next: boolean) => {+ if (!next) setDetail(undefined);+ };++ return (+ <Sheet open={isOpen} onOpenChange={handleOpenChange}>+ <SheetContent width="standard">+ <SheetHeader>+ <SheetTitle>{t("common.detail")}</SheetTitle>+ </SheetHeader>+ {detail && (+ <div+ className={cn(+ "h-full flex flex-col gap-y-2",+ dark ? "text-white" : "text-main"+ )}+ >+ <div className="flex items-center justify-between gap-x-4">+ <div className="flex items-center gap-x-2">+ <Tooltip+ content={t("sql-editor.previous-row")}+ delayDuration={500}+ >+ <Button+ size="sm"+ variant="outline"+ disabled={detail.row === 0}+ onClick={() => move(-1)}+ >+ <ChevronUpIcon className="size-4" />+ </Button>+ </Tooltip>+ <Tooltip content={t("sql-editor.next-row")} delayDuration={500}>+ <Button+ size="sm"+ variant="outline"+ disabled={detail.row === totalCount - 1}+ onClick={() => move(1)}+ >+ <ChevronDownIcon className="size-4" />+ </Button>+ </Tooltip>+ <div className="text-xs text-control-light flex items-center gap-x-1">+ <span>{detail.row + 1}</span>+ <span>/</span>+ <span>{totalCount}</span>+ <span>{t("sql-editor.rows.self")}</span>+ </div>+ </div>++ <div className="flex items-center gap-1">+ {guessedIsJSON && (+ <Tooltip content={t("sql-editor.format")}>+ <Button+ size="sm"+ variant={format ? "default" : "outline"}+ className="h-7 px-1.5"+ onClick={() => setFormat(!format)}+ >+ <BracesIcon className="size-4" />+ </Button>+ </Tooltip>+ )}++ {isBinaryData && (+ <BinaryFormatButton+ format={binaryFormat}+ onFormatChange={(next) =>+ setBinaryFormat({+ rowIndex: detail.row,+ colIndex: detail.col,+ format: next,+ })+ }+ />+ )}++ {!disallowCopyingData && (+ <Tooltip content={t("common.copy")}>+ <Button+ size="sm"+ variant="ghost"+ className="size-7 p-0"+ onClick={handleCopy}+ >+ {copied ? (+ <CheckIcon className="size-4" />+ ) : (+ <CopyIcon className="size-4" />+ )}+ </Button>+ </Tooltip>+ )}+ </div>+ </div>++ <div+ className={cn(+ "flex-1 overflow-auto text-sm font-mono border p-2 relative",+ disallowCopyingData && "select-none",+ guessedIsJSON && format && !wrap+ ? "whitespace-pre"+ : "whitespace-pre-wrap"+ )}+ >+ {guessedIsJSON && format ? (+ <>+ <div className="absolute right-2 top-2 flex justify-end items-center gap-1">+ <Tooltip content={t("common.text-wrap")}>+ <Button+ size="sm"+ variant={wrap ? "default" : "outline"}+ className="h-6 px-1"+ onClick={() => setWrap(!wrap)}+ >+ <WrapTextIcon className="size-3" />+ </Button>+ </Tooltip>+ </div>+ <PrettyJSON content={content ?? ""} />+ </>+ ) : content && content.length > 0 ? (+ <>{content}</>+ ) : (+ <br style={{ minWidth: "1rem", display: "inline-flex" }} />+ )}+ </div>+ </div>+ )}+ </SheetContent>+ </Sheet>+ );+}diff --git a/frontend/src/react/components/sql-editor/ResultView/EmptyView.tsx b/frontend/src/react/components/sql-editor/ResultView/EmptyView.tsxnew file mode 100644index 0000000000..d9b276de5b--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/EmptyView.tsx@@ -0,0 +1,20 @@+import { useTranslation } from "react-i18next";+import { cn } from "@/react/lib/utils";++interface EmptyViewProps {+ dark: boolean;+}++export function EmptyView({ dark }: EmptyViewProps) {+ const { t } = useTranslation();+ return (+ <div+ className={cn(+ "text-md font-normal",+ dark ? "text-matrix-green-hover" : "text-control-light"+ )}+ >+ {t("sql-editor.no-data-available")}+ </div>+ );+}diff --git a/frontend/src/react/components/sql-editor/ResultView/ErrorView.tsx b/frontend/src/react/components/sql-editor/ResultView/ErrorView.tsxnew file mode 100644index 0000000000..e9fd094501--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/ErrorView.tsx@@ -0,0 +1,127 @@+import { type IRange, Selection } from "monaco-editor";+import { type ReactNode, useMemo } from "react";+import { useTranslation } from "react-i18next";+import { positionWithOffset } from "@/components/MonacoEditor/utils";+import { Alert } from "@/react/components/ui/alert";+import { Button } from "@/react/components/ui/button";+import { cn } from "@/react/lib/utils";+import type { SQLEditorQueryParams, SQLResultSetV1 } from "@/types";+import { activeSQLEditorRef } from "@/views/sql-editor/EditorPanel/StandardPanel/state";+import { sqlEditorEvents } from "@/views/sql-editor/events";+import { PostgresError } from "./PostgresError";++interface ErrorViewProps {+ dark: boolean;+ error: string | undefined;+ executeParams?: SQLEditorQueryParams;+ resultSet?: SQLResultSetV1;+ suffix?: ReactNode;+}++export function ErrorView({+ dark,+ error,+ executeParams,+ resultSet,+ suffix,+}: ErrorViewProps) {+ const { t } = useTranslation();++ const failingStatement = useMemo(() => {+ const failed = resultSet?.results?.find((r) => r.error);+ return failed?.statement?.trim();+ }, [resultSet]);++ const errorPosition = useMemo(() => {+ const result = resultSet?.results?.[0];+ if (result?.detailedError.case === "syntaxError") {+ return result.detailedError.value.startPosition;+ }+ return undefined;+ }, [resultSet]);++ const hasErrorPosition = (errorPosition?.line ?? 0) > 0;+ const canShowInEditor = hasErrorPosition || !!failingStatement;++ const findStatementRange = (): IRange | undefined => {+ let statement = failingStatement;+ if (!statement) return undefined;++ const editor = activeSQLEditorRef.value;+ const model = editor?.getModel();+ if (!model) return undefined;++ statement = statement.replace(/\s+LIMIT\s+\d+\s*;?\s*$/i, "").trim();+ let matches = model.findMatches(+ statement,+ false,+ false,+ false,+ null,+ false+ );+ if (matches.length > 0) return matches[0].range;++ matches = model.findMatches(+ `${statement};`,+ false,+ false,+ false,+ null,+ false+ );+ if (matches.length > 0) return matches[0].range;+ return undefined;+ };++ const positionLabel = (() => {+ if (hasErrorPosition && errorPosition) {+ const [line, col] = positionWithOffset(+ errorPosition.line,+ errorPosition.column,+ executeParams?.selection+ );+ return `L${line}:C${col}`;+ }+ return t("sql-editor.show-in-editor");+ })();++ const showInEditor = () => {+ let range: IRange | undefined;+ if (hasErrorPosition && errorPosition) {+ const [line, col] = positionWithOffset(+ errorPosition.line,+ errorPosition.column,+ executeParams?.selection+ );+ range = new Selection(line, col, line, col);+ } else {+ range = findStatementRange();+ }+ if (range) {+ sqlEditorEvents.emit("set-editor-selection", range);+ }+ };++ return (+ <div+ className={cn(+ "w-full text-md font-normal flex flex-col gap-2 text-sm",+ dark ? "text-matrix-green-hover" : "text-control-light"+ )}+ >+ <Alert variant="error" className="w-full">+ <div className="flex items-center gap-2 w-full">+ <span className="flex-1">{error}</span>+ {canShowInEditor && (+ <Button size="sm" variant="ghost" onClick={showInEditor}>+ {positionLabel}+ </Button>+ )}+ </div>+ </Alert>+ {suffix && <div>{suffix}</div>}+ {resultSet && <PostgresError resultSet={resultSet} />}+ </div>+ );+}diff --git a/frontend/src/react/components/sql-editor/ResultView/PostgresError.tsx b/frontend/src/react/components/sql-editor/ResultView/PostgresError.tsxnew file mode 100644index 0000000000..66097e8307--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/PostgresError.tsx@@ -0,0 +1,50 @@+import { useMemo } from "react";+import type { SQLResultSetV1 } from "@/types";+import type { QueryResult_PostgresError } from "@/types/proto-es/v1/sql_service_pb";++interface PostgresErrorProps {+ resultSet: SQLResultSetV1;+}++export function PostgresError({ resultSet }: PostgresErrorProps) {+ const errors = useMemo<QueryResult_PostgresError[]>(() => {+ const out: QueryResult_PostgresError[] = [];+ for (const r of resultSet.results) {+ if (r.detailedError?.case === "postgresError") {+ out.push(r.detailedError.value);+ }+ }+ return out;+ }, [resultSet.results]);++ return (+ <>+ {errors.map((error, i) => (+ <div+ key={i}+ className="text-sm grid gap-1 pl-8"+ style={{ gridTemplateColumns: "auto 1fr" }}+ >+ {error.detail && (+ <>+ <div>DETAIL:</div>+ <div>{error.detail}</div>+ </>+ )}+ {error.hint && (+ <>+ <div>HINT:</div>+ <div>{error.hint}</div>+ </>+ )}+ {error.where && (+ <>+ <div>WHERE:</div>+ <div>{error.where}</div>+ </>+ )}+ </div>+ ))}+ </>+ );+}diff --git a/frontend/src/react/components/sql-editor/ResultView/PrettyJSON.tsx b/frontend/src/react/components/sql-editor/ResultView/PrettyJSON.tsxnew file mode 100644index 0000000000..1366768e6b--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/PrettyJSON.tsx@@ -0,0 +1,44 @@+import { escape } from "lodash-es";+import { useEffect, useState } from "react";++interface PrettyJSONProps {+ content: string;+}++/**+ * Pretty-prints a JSON string. Heavy deps (`pretty-print-json`,+ * `lossless-json`) load lazily so that JSON-cell hover doesn't pay+ * for them eagerly. An AbortController per `content` prevents the+ * older pretty-print result from racing in after a quick switch.+ */+export function PrettyJSON({ content }: PrettyJSONProps) {+ const [html, setHtml] = useState<string>("");++ useEffect(() => {+ const controller = new AbortController();+ (async () => {+ try {+ const [{ prettyPrintJson }, { parse }, { losslessReviver }] =+ await Promise.all([+ import("pretty-print-json"),+ import("lossless-json"),+ import("@/composables/utils"),+ ]);+ await import("./pretty-print-json.css");+ if (controller.signal.aborted) return;+ const obj = parse(content, null, losslessReviver);+ const next = prettyPrintJson.toHtml(obj, {+ quoteKeys: true,+ trailingCommas: false,+ });+ if (!controller.signal.aborted) setHtml(next);+ } catch (err) {+ console.warn("[PrettyJSON]", err);+ if (!controller.signal.aborted) setHtml(escape(content));+ }+ })();+ return () => controller.abort();+ }, [content]);++ return <div dangerouslySetInnerHTML={{ __html: html }} />;+}diff --git a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsxnew file mode 100644index 0000000000..3b865b0895--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx@@ -0,0 +1,379 @@+import { create } from "@bufbuild/protobuf";+import { ConnectError } from "@connectrpc/connect";+import dayjs from "dayjs";+import { InfoIcon, LoaderCircle } from "lucide-react";+import { type ReactNode, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { isDisallowChangeDatabaseError } from "@/composables/useExecuteSQL";+import {+ DataExportButton,+ type DataExportRequest,+} from "@/react/components/DataExportButton";+import { RequestQueryButton } from "@/react/components/sql-editor/RequestQueryButton";+import { Button } from "@/react/components/ui/button";+import {+ Tabs,+ TabsList,+ TabsPanel,+ TabsTrigger,+} from "@/react/components/ui/tabs";+import { Tooltip } from "@/react/components/ui/tooltip";+import { useVueState } from "@/react/hooks/useVueState";+import { cn } from "@/react/lib/utils";+import {+ pushNotification,+ useDatabaseV1Store,+ useDBSchemaV1Store,+ useSQLEditorStore,+ useSQLEditorTabStore,+ useSQLStore,+} from "@/store";+import { usePolicyV1Store } from "@/store/modules/v1/policy";+import type { SQLEditorQueryParams, SQLResultSetV1 } from "@/types";+import { isValidDatabaseName } from "@/types";+import {+ ExportFormat,+ type PermissionDeniedDetail,+} from "@/types/proto-es/v1/common_pb";+import type { Database } from "@/types/proto-es/v1/database_service_pb";+import { ExportRequestSchema } from "@/types/proto-es/v1/sql_service_pb";+import { hasProjectPermissionV2 } from "@/utils/iam/permission";+import {+ extractDatabaseResourceName,+ getDatabaseProject,+} from "@/utils/v1/database";+import { EmptyView } from "./EmptyView";+import { ErrorView } from "./ErrorView";+import { SingleResultView } from "./SingleResultView";++export interface ResultViewProps {+ executeParams: SQLEditorQueryParams;+ database: Database;+ resultSet?: SQLResultSetV1;+ loading?: boolean;+ dark?: boolean;+}++type ViewMode = "SINGLE-RESULT" | "MULTI-RESULT" | "EMPTY" | "ERROR";++/**+ * Top-level wrapper for one database's query result. Routes to a single+ * `SingleResultView`, a multi-tab list of them, an empty placeholder, or+ * a result-set-level error view (with optional access-request /+ * sync-database affordances). Phase 7's caller swap mounts this via+ * `<ReactPageMount page="ResultView" ...>`.+ */+export function ResultView({+ executeParams,+ database,+ resultSet,+ loading,+ dark = false,+}: ResultViewProps) {+ const { t } = useTranslation();+ const policyStore = usePolicyV1Store();+ const queryDataPolicy = useVueState(+ () => useSQLEditorStore().queryDataPolicy+ );+ const tabStore = useSQLEditorTabStore();++ const permissionDeniedError = useMemo<+ PermissionDeniedDetail | undefined+ >(() => {+ if (!resultSet || isDisallowChangeDatabaseError(resultSet)) {+ return undefined;+ }+ for (const result of resultSet.results) {+ if (result.detailedError.case === "permissionDenied") {+ return result.detailedError.value;+ }+ }+ return undefined;+ }, [resultSet]);++ const viewMode: ViewMode = useMemo(() => {+ if (!resultSet) return "EMPTY";+ if (resultSet.error) return "ERROR";+ const results = resultSet.results ?? [];+ if (results.length === 0) return "EMPTY";+ if (results.length === 1) return "SINGLE-RESULT";+ return "MULTI-RESULT";+ }, [resultSet]);++ const showPlaceholder = useMemo(() => {+ if (viewMode === "ERROR") return false;+ if (!resultSet) return true;+ if (loading) return true;+ return false;+ }, [viewMode, resultSet, loading]);++ const disallowCopyingData = useMemo(() => {+ if (queryDataPolicy?.disableCopyData) return true;+ const environment = database.effectiveEnvironment;+ if (+ environment &&+ policyStore.getQueryDataPolicyByParent(environment).disableCopyData+ ) {+ return true;+ }+ return false;+ }, [queryDataPolicy, database, policyStore]);++ const filteredResults = useMemo(() => {+ if (!resultSet) return [];+ return resultSet.results.filter(+ (r) => !r.statement.trim().toUpperCase().startsWith("SET")+ );+ }, [resultSet]);++ const tabName = (index: number) => `${t("common.query")} #${index + 1}`;++ const handleExport = async (+ req: DataExportRequest & { statement: string }+ ) => {+ const { options, resolve, reject, statement } = req;+ const admin = tabStore.currentTab?.mode === "ADMIN";+ try {+ const content = await useSQLStore().exportData(+ create(ExportRequestSchema, {+ name: database.name,+ ...(executeParams.connection.dataSourceId+ ? { dataSourceId: executeParams.connection.dataSourceId }+ : {}),+ format: options.format,+ statement,+ limit: options.limit,+ admin,+ password: options.password,+ schema: executeParams.connection.schema,+ })+ );+ resolve([+ {+ content,+ filename: `${extractDatabaseResourceName(database.name).databaseName}.${dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss")}.zip`,+ },+ ]);+ } catch (e) {+ reject(e);+ }+ };++ const errorViewSuffix = (statement?: string): ReactNode => {+ if (permissionDeniedError) {+ return (+ <RequestQueryButton+ text={false}+ statement={statement}+ permissionDeniedDetail={permissionDeniedError}+ />+ );+ }+ if (+ viewMode === "ERROR" &&+ resultSet?.error.includes("resource not found")+ ) {+ return <SyncDatabaseButton database={database} />;+ }+ return null;+ };++ return (+ <div+ className={cn(+ "relative flex flex-col justify-start items-start pb-1 overflow-y-auto h-full w-full",+ dark && "dark bg-dark-bg"+ )}+ >+ {executeParams && resultSet && !showPlaceholder && (+ <>+ {viewMode === "SINGLE-RESULT" &&+ (resultSet.results[0]?.error ? (+ <ErrorView+ dark={dark}+ error={resultSet.results[0].error}+ executeParams={executeParams}+ resultSet={resultSet}+ suffix={errorViewSuffix(executeParams.statement)}+ />+ ) : (+ <SingleResultView+ dark={dark}+ disallowCopyingData={disallowCopyingData}+ params={executeParams}+ database={database}+ result={resultSet.results[0]}+ showExport={!queryDataPolicy?.disableExport}+ maximumExportCount={queryDataPolicy?.maximumResultRows}+ onExport={handleExport}+ />+ ))}++ {viewMode === "MULTI-RESULT" && (+ <Tabs+ defaultValue={tabName(0)}+ className="flex-1 flex flex-col overflow-hidden w-full"+ >+ <div className="flex items-center justify-between gap-x-2">+ <TabsList>+ {filteredResults.map((result, i) => (+ <Tooltip key={i} content={result.statement}>+ <TabsTrigger value={tabName(i)}>+ <div className="flex items-center gap-x-2 mb-1">+ <span>{tabName(i)}</span>+ {result.error && (+ <InfoIcon className="size-4 text-warning" />+ )}+ </div>+ </TabsTrigger>+ </Tooltip>+ ))}+ </TabsList>+ {!queryDataPolicy?.disableExport && (+ <div className="mb-1">+ <DataExportButton+ size="sm"+ disabled={false}+ supportFormats={[+ ExportFormat.CSV,+ ExportFormat.JSON,+ ExportFormat.SQL,+ ExportFormat.XLSX,+ ]}+ viewMode="DRAWER"+ supportPassword+ maximumExportCount={queryDataPolicy?.maximumResultRows}+ onExport={(req) =>+ handleExport({+ ...req,+ statement: executeParams.statement,+ })+ }+ />+ </div>+ )}+ </div>+ {filteredResults.map((result, i) => (+ <TabsPanel+ key={i}+ value={tabName(i)}+ className="flex-1 flex flex-col overflow-hidden"+ >+ {result.error ? (+ <ErrorView+ dark={dark}+ error={result.error}+ executeParams={executeParams}+ resultSet={resultSet}+ suffix={errorViewSuffix(result.statement)}+ />+ ) : (+ <SingleResultView+ dark={dark}+ disallowCopyingData={disallowCopyingData}+ params={executeParams}+ database={database}+ result={result}+ showExport={false}+ maximumExportCount={queryDataPolicy?.maximumResultRows}+ onExport={handleExport}+ />+ )}+ </TabsPanel>+ ))}+ </Tabs>+ )}++ {viewMode === "EMPTY" && <EmptyView dark={dark} />}++ {viewMode === "ERROR" && (+ <ErrorView+ dark={dark}+ error={resultSet.error}+ executeParams={executeParams}+ resultSet={resultSet}+ suffix={errorViewSuffix(resultSet.results[0]?.statement)}+ />+ )}+ </>+ )}++ {showPlaceholder && (+ <div+ className={cn(+ "absolute inset-0 flex flex-col justify-center items-center z-10",+ loading && "bg-overlay/50"+ )}+ >+ {loading ? (+ <>+ <LoaderCircle className="size-6 animate-spin text-control-light" />+ {t("sql-editor.loading-data")}+ </>+ ) : !resultSet ? (+ t("sql-editor.table-empty-placeholder")+ ) : null}+ </div>+ )}+ </div>+ );+}++// ---------------------------------------------------------------------------+// Inline SyncDatabaseButton — replaces frontend/src/components/DatabaseDetail/SyncDatabaseButton.vue.+// Only used by the result-set-level "resource not found" branch above.+// ---------------------------------------------------------------------------++function SyncDatabaseButton({ database }: { database: Database }) {+ const { t } = useTranslation();+ const databaseStore = useDatabaseV1Store();+ const dbSchemaStore = useDBSchemaV1Store();+ const [syncing, setSyncing] = useState(false);++ if (!isValidDatabaseName(database.name)) return null;++ const project = getDatabaseProject(database);+ const canSync = hasProjectPermissionV2(project, "bb.databases.sync");+ if (!canSync) return null;++ const handleSync = async () => {+ setSyncing(true);+ const { databaseName } = extractDatabaseResourceName(database.name);+ try {+ await databaseStore.syncDatabase(database.name);+ await dbSchemaStore.getOrFetchDatabaseMetadata({+ database: database.name,+ skipCache: true,+ });+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t(+ "db.successfully-synced-schema-for-database-database-value-name",+ { name: databaseName }+ ),+ });+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("db.failed-to-sync-schema-for-database-database-value-name", {+ name: databaseName,+ }),+ description:+ error instanceof ConnectError+ ? error.message+ : (error as Error)?.message,+ });+ } finally {+ setSyncing(false);+ }+ };++ return (+ <Button size="sm" variant="link" disabled={syncing} onClick={handleSync}>+ {syncing && <LoaderCircle className="size-3 animate-spin" />}+ {t("database.sync-database")}+ </Button>+ );+}diff --git a/frontend/src/react/components/sql-editor/ResultView/SelectionCopyTooltips.tsx b/frontend/src/react/components/sql-editor/ResultView/SelectionCopyTooltips.tsxnew file mode 100644index 0000000000..3003c2eed4--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/SelectionCopyTooltips.tsx@@ -0,0 +1,69 @@+import { CopyIcon, InfoIcon } from "lucide-react";+import { Trans, useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import { useSelectionContext } from "./context";++export function SelectionCopyTooltips() {+ const { t } = useTranslation();+ const {+ state: { rows, columns },+ copySelected,+ deselect,+ } = useSelectionContext();++ if (rows.length === 0 && columns.length === 0) return null;++ const isMac = /mac/i.test(navigator.platform);++ return (+ <div+ className="w-full absolute h-full bg-background flex flex-row justify-start items-center text-control"+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ }}+ >+ <InfoIcon size={16} className="mr-2 text-control" />+ <p className="text-sm flex flex-row justify-start items-center gap-1">+ <Trans+ i18nKey="sql-editor.copy-selected-results"+ components={{+ action: (+ <Button+ size="sm"+ variant="outline"+ className="h-6 px-2 gap-x-1"+ disabled+ >+ {isMac ? (+ <span className="text-base leading-none">⌘</span>+ ) : (+ <span className="tracking-tighter text-xs leading-none">+ Ctrl+ </span>+ )}+ C+ </Button>+ ),+ button: (+ <Button+ size="sm"+ variant="default"+ className="h-6 px-2 gap-x-1"+ onClick={copySelected}+ >+ <CopyIcon className="size-3" />+ {t("common.copy")}+ </Button>+ ),+ }}+ />+ </p>+ <div className="ml-1">+ <Button size="sm" variant="ghost" onClick={deselect}>+ {t("sql-editor.cancel-selection")}+ </Button>+ </div>+ </div>+ );+}diff --git a/frontend/src/react/components/sql-editor/ResultView/SensitiveDataIcon.tsx b/frontend/src/react/components/sql-editor/ResultView/SensitiveDataIcon.tsxnew file mode 100644index 0000000000..805b35e532--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/SensitiveDataIcon.tsx@@ -0,0 +1,27 @@+import { EyeOffIcon } from "lucide-react";+import { useTranslation } from "react-i18next";+import { Tooltip } from "@/react/components/ui/tooltip";+import { cn } from "@/react/lib/utils";+import { router } from "@/router";+import { WORKSPACE_ROUTE_GLOBAL_MASKING } from "@/router/dashboard/workspaceRoutes";+import { hasWorkspacePermissionV2 } from "@/utils/iam/permission";++export function SensitiveDataIcon() {+ const { t } = useTranslation();+ const clickable = hasWorkspacePermissionV2("bb.policies.update");++ const handleClick = () => {+ if (!clickable) return;+ const url = router.resolve({ name: WORKSPACE_ROUTE_GLOBAL_MASKING });+ window.open(url.href, "_BLANK");+ };++ return (+ <Tooltip content={t("sensitive-data.self")} delayDuration={250}>+ <EyeOffIcon+ className={cn("size-3 -mb-0.5", clickable && "cursor-pointer")}+ onClick={handleClick}+ />+ </Tooltip>+ );+}diff --git a/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsxnew file mode 100644index 0000000000..f79ca31e0d--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx@@ -0,0 +1,830 @@+import { create } from "@bufbuild/protobuf";+import { isEmpty } from "lodash-es";+import {+ ArrowDownIcon,+ ArrowUpIcon,+ ChevronRightIcon,+ CopyIcon,+ InfoIcon,+ XIcon,+} from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { v4 as uuidv4 } from "uuid";+import { useExecuteSQL } from "@/composables/useExecuteSQL";+import {+ flattenElasticsearchSearchResult,+ flattenNoSQLQueryResult,+} from "@/composables/utils";+import {+ AdvancedSearch,+ type ScopeOption,+ type SearchParams,+} from "@/react/components/AdvancedSearch";+import {+ DataExportButton,+ type DataExportRequest,+} from "@/react/components/DataExportButton";+import { EngineIcon } from "@/react/components/EngineIcon";+import { Alert } from "@/react/components/ui/alert";+import { Button } from "@/react/components/ui/button";+import { EllipsisText } from "@/react/components/ui/ellipsis-text";+import { Switch } from "@/react/components/ui/switch";+import { Tooltip } from "@/react/components/ui/tooltip";+import { useVueState } from "@/react/hooks/useVueState";+import { cn } from "@/react/lib/utils";+import { useSQLEditorStore, useSQLEditorTabStore } from "@/store";+import type {+ SQLEditorDatabaseQueryContext,+ SQLEditorQueryParams,+} from "@/types";+import { Engine, ExportFormat } from "@/types/proto-es/v1/common_pb";+import type { Database } from "@/types/proto-es/v1/database_service_pb";+import {+ QueryOption_MSSQLExplainFormat,+ QueryOptionSchema,+ type QueryResult,+ type RowValue,+} from "@/types/proto-es/v1/sql_service_pb";+import { createExplainToken } from "@/utils/pev2";+import { STORAGE_KEY_SQL_EDITOR_NOSQL_TABLE_VIEW } from "@/utils/storage-keys";+import { isNullOrUndefined } from "@/utils/util";+import {+ extractDatabaseResourceName,+ getDatabaseEnvironment,+ getInstanceResource,+} from "@/utils/v1/database";+import { instanceV1Name } from "@/utils/v1/instance";+import { compareQueryRowValues, extractSQLRowValuePlain } from "@/utils/v1/sql";+import { SQLResultViewProvider, useSelectionContext } from "./context";+import { DetailPanel } from "./DetailPanel";+import { EmptyView } from "./EmptyView";+import { ErrorView } from "./ErrorView";+import { SelectionCopyTooltips } from "./SelectionCopyTooltips";+import type { ResultTableColumn, ResultTableRow, SortState } from "./types";+import {+ VirtualDataBlock,+ type VirtualDataBlockHandle,+} from "./VirtualDataBlock";+import {+ VirtualDataTable,+ type VirtualDataTableHandle,+} from "./VirtualDataTable";++export interface SingleResultViewProps {+ dark: boolean;+ disallowCopyingData: boolean;+ params: SQLEditorQueryParams;+ database: Database;+ result: QueryResult;+ showExport: boolean;+ maximumExportCount?: number;+ onExport?: (req: DataExportRequest & { statement: string }) => void;+}++type ViewMode = "RESULT" | "EMPTY" | "AFFECTED-ROWS" | "ERROR";++/**+ * Per-result-set view. Owns the per-mount `<SQLResultViewProvider>` plus+ * the result toolbar (search, switches, export, copy-all), the+ * VirtualDataTable / VirtualDataBlock body, the floating scroll ++ * search-candidate buttons, the bottom status bar, and the DetailPanel+ * sheet. The wrapper does the per-result derivations once (active result,+ * columns, base row wrappers, NoSQL flatten + toggle) so the inner+ * component and the provider share the same arrays — earlier we derived+ * them twice and doubled the 100k-row allocation on large result sets.+ */+export function SingleResultView(props: SingleResultViewProps) {+ const { dark, disallowCopyingData, database, result } = props;+ const engine = getInstanceResource(database).engine;+ const [noSQLTableView, setNoSQLTableView] = useLocalStorageBoolean(+ STORAGE_KEY_SQL_EDITOR_NOSQL_TABLE_VIEW,+ true+ );+ // 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+ // `rows[selectionIndex]` — if the provider held the unsorted array but+ // the table rendered sorted rows, Cmd+C would copy the wrong row.+ const [sortState, setSortState] = useState<SortState | undefined>();++ const flattened = useMemo(() => {+ if (engine === Engine.ELASTICSEARCH) {+ return flattenElasticsearchSearchResult(result);+ }+ if (engine === Engine.MONGODB) {+ return flattenNoSQLQueryResult(result);+ }+ return undefined;+ }, [engine, result]);+ const supportsTableViewToggle = flattened !== undefined;+ const activeResult =+ supportsTableViewToggle && noSQLTableView ? flattened : result;++ const columns: ResultTableColumn[] = useMemo(+ () =>+ activeResult.columnNames.map((columnName, index) => ({+ id: columnName,+ name: columnName,+ columnType: activeResult.columnTypeNames[index] ?? "",+ })),+ [activeResult]+ );++ const baseRows: ResultTableRow[] = useMemo(+ () =>+ activeResult.rows.map((item, index) => ({+ key: index,+ item,+ })),+ [activeResult]+ );++ const rows: ResultTableRow[] = useMemo(() => {+ if (!sortState || !sortState.direction) return baseRows;+ const { columnIndex, direction } = sortState;+ const columnType = columns[columnIndex]?.columnType ?? "";+ return [...baseRows].sort((a, b) => {+ const cmp = compareQueryRowValues(+ columnType,+ a.item.values[columnIndex],+ b.item.values[columnIndex]+ );+ return direction === "asc" ? cmp : -cmp;+ });+ }, [baseRows, sortState, columns]);++ // Reset sort whenever the user toggles the NoSQL table-view switch:+ // column indices don't carry over between flattened/raw shapes.+ useEffect(() => {+ setSortState(undefined);+ }, [noSQLTableView]);++ const toggleSort = useCallback((columnIndex: number) => {+ setSortState((current) => {+ if (!current || current.columnIndex !== columnIndex) {+ return { columnIndex, direction: "desc" };+ }+ if (current.direction === "desc") {+ return { columnIndex, direction: "asc" };+ }+ return undefined;+ });+ }, []);++ return (+ <SQLResultViewProvider+ dark={dark}+ disallowCopyingData={disallowCopyingData}+ rows={rows}+ columns={columns}+ >+ <SingleResultViewInner+ {...props}+ engine={engine}+ activeResult={activeResult}+ columns={columns}+ rows={rows}+ sortState={sortState}+ toggleSort={toggleSort}+ supportsTableViewToggle={supportsTableViewToggle}+ noSQLTableView={noSQLTableView}+ setNoSQLTableView={setNoSQLTableView}+ />+ </SQLResultViewProvider>+ );+}++interface SingleResultViewInnerProps extends SingleResultViewProps {+ engine: Engine;+ activeResult: QueryResult;+ columns: ResultTableColumn[];+ rows: ResultTableRow[];+ sortState: SortState | undefined;+ toggleSort: (columnIndex: number) => void;+ supportsTableViewToggle: boolean;+ noSQLTableView: boolean;+ setNoSQLTableView: (next: boolean) => void;+}++function SingleResultViewInner({+ dark,+ disallowCopyingData,+ params,+ database,+ result,+ showExport,+ maximumExportCount,+ onExport,+ engine,+ activeResult: _activeResult,+ columns,+ rows,+ sortState,+ toggleSort,+ supportsTableViewToggle,+ noSQLTableView,+ setNoSQLTableView,+}: SingleResultViewInnerProps) {+ const { t } = useTranslation();+ const tabStore = useSQLEditorTabStore();+ const editorStore = useSQLEditorStore();+ const currentTabMode = useVueState(() => tabStore.currentTab?.mode);+ const resultRowsLimit = useVueState(() => editorStore.resultRowsLimit);+ const policyMaxRows = useVueState(+ () => editorStore.queryDataPolicy.maximumResultRows+ );+ const { runQuery } = useExecuteSQL();+ const { copyAll } = useSelectionContext();++ const dataTableRef = useRef<+ VirtualDataTableHandle | VirtualDataBlockHandle | null+ >(null);++ const [vertical, setVertical] = useState(false);+ const [searchParams, setSearchParams] = useState<SearchParams>({+ query: "",+ scopes: [],+ });+ const [searchCandidateActiveIndex, setSearchCandidateActiveIndex] =+ useState(-1);+ const [searchCandidateRowIndexs, setSearchCandidateRowIndexs] = useState<+ number[]+ >([]);++ // Reset search state when toggling NoSQL table view (sort reset is+ // handled by the wrapper, where sortState lives).+ useEffect(() => {+ setSearchParams({ query: "", scopes: [] });+ setSearchCandidateActiveIndex(-1);+ setSearchCandidateRowIndexs([]);+ }, [noSQLTableView]);++ const viewMode: ViewMode = useMemo(() => {+ if (result.error && rows.length === 0) return "ERROR";+ const columnNames = result.columnNames;+ if (columnNames?.length === 0) return "EMPTY";+ if (columnNames?.length === 1 && columnNames[0] === "Affected Rows") {+ return "AFFECTED-ROWS";+ }+ return "RESULT";+ }, [result, rows.length]);++ const searchScopeOptions: ScopeOption[] = useMemo(() => {+ const opts: ScopeOption[] = [+ {+ id: "row-number",+ title: t("sql-editor.search-scope-row-number-title"),+ description: t("sql-editor.search-scope-row-number-description"),+ },+ ];+ for (const column of columns) {+ opts.push({+ id: column.id,+ title: column.name,+ description: t("sql-editor.search-scope-column-description", {+ type: column.columnType,+ }),+ });+ }+ return opts;+ }, [columns, t]);++ // Recompute candidates when search params change.+ const cellValueMatches = useCallback(+ (cell: RowValue, query: string): boolean => {+ const value = extractSQLRowValuePlain(cell);+ if (isNullOrUndefined(value)) return false;+ return String(value).toLowerCase().includes(query.toLowerCase());+ },+ []+ );++ const getNextCandidateRowIndex = useCallback(+ (from: number, sp: SearchParams): number => {+ if (sp.scopes.length === 0 && !sp.query) return -1;+ for (let i = from; i < rows.length; i++) {+ const row = rows[i];+ const scopeOk = sp.scopes.every((scope) => {+ if (!scope.value) return false;+ if (scope.id === "row-number") {+ return i + 1 === Number.parseInt(scope.value, 10);+ }+ const columnIndex = columns.findIndex((c) => c.name === scope.id);+ if (columnIndex < 0) return false;+ return cellValueMatches(row.item.values[columnIndex], scope.value);+ });+ if (!scopeOk) continue;+ if (sp.query) {+ const queryOk = row.item.values.some((cell) =>+ cellValueMatches(cell, sp.query)+ );+ if (!queryOk) continue;+ }+ return i;+ }+ return -1;+ },+ [rows, columns, cellValueMatches]+ );++ useEffect(() => {+ const next = getNextCandidateRowIndex(0, searchParams);+ const indexes: number[] = [];+ if (next >= 0) {+ indexes.push(next);+ const another = getNextCandidateRowIndex(next + 1, searchParams);+ if (another >= 0) indexes.push(another);+ }+ setSearchCandidateRowIndexs(indexes);+ setSearchCandidateActiveIndex(0);+ }, [searchParams, getNextCandidateRowIndex]);++ const activeRowIndex =+ searchCandidateRowIndexs[searchCandidateActiveIndex] ?? -1;++ const scrollToRow = useCallback((index: number | undefined) => {+ if (index === undefined || index < 0) return;+ requestAnimationFrame(() => dataTableRef.current?.scrollTo(index));+ }, []);++ // Re-scroll when the active candidate or vertical mode changes.+ useEffect(() => {+ scrollToRow(activeRowIndex);+ }, [activeRowIndex, vertical, scrollToRow]);++ const scrollToNextCandidate = () => {+ if (searchCandidateActiveIndex >= searchCandidateRowIndexs.length - 1) {+ return;+ }+ const next = searchCandidateActiveIndex + 1;+ setSearchCandidateActiveIndex(next);+ if (next === searchCandidateRowIndexs.length - 1) {+ const cur = searchCandidateRowIndexs[next];+ const more = getNextCandidateRowIndex(cur + 1, searchParams);+ if (more >= 0) {+ setSearchCandidateRowIndexs((prev) => [...prev, more]);+ }+ }+ };++ const scrollToPreviousCandidate = () => {+ if (searchCandidateActiveIndex <= 0) return;+ setSearchCandidateActiveIndex(searchCandidateActiveIndex - 1);+ };++ const clearSearchCandidate = () => {+ setSearchParams({ query: "", scopes: [] });+ };++ const reachQueryLimit =+ currentTabMode !== "ADMIN" &&+ (rows.length === resultRowsLimit || rows.length === policyMaxRows);++ const isSensitiveColumn = useCallback(+ (columnIndex: number): boolean => {+ if (supportsTableViewToggle && noSQLTableView) return false;+ const reason = result.masked?.[columnIndex];+ return (+ reason !== null &&+ reason !== undefined &&+ reason.semanticTypeId !== undefined &&+ reason.semanticTypeId !== ""+ );+ },+ [result.masked, supportsTableViewToggle, noSQLTableView]+ );++ const getMaskingReason = useCallback(+ (columnIndex: number) => {+ if (supportsTableViewToggle && noSQLTableView) return undefined;+ if (!result.masked || columnIndex >= result.masked.length) {+ return undefined;+ }+ const reason = result.masked[columnIndex];+ if (!reason || !reason.semanticTypeId) return undefined;+ return reason;+ },+ [result.masked, supportsTableViewToggle, noSQLTableView]+ );++ const showVisualizeButton =+ (engine === Engine.POSTGRES ||+ engine === Engine.MSSQL ||+ engine === Engine.SPANNER) &&+ !!params.explain;++ const visualizeExplain = async () => {+ let token: string | undefined;+ try {+ if (engine === Engine.POSTGRES || engine === Engine.SPANNER) {+ token = getExplainTokenFromResult(result, engine);+ } else if (engine === Engine.MSSQL) {+ token = await getExplainTokenForMSSQL(database, params, runQuery);+ }+ if (!token) return;+ window.open(`/explain-visualizer.html?token=${token}`, "_blank");+ } catch {+ // ignore+ }+ };++ const queryTime = useMemo(() => {+ const { latency } = result;+ if (!latency) return "-";+ const totalSeconds = Number(latency.seconds) + latency.nanos / 1e9;+ if (totalSeconds < 1) {+ return `${Math.round(totalSeconds * 1000)} ms`;+ }+ return `${totalSeconds.toFixed(2)} s`;+ }, [result]);++ const resultRowsText = `${rows.length} ${t("sql-editor.rows.self")}`;++ const handleExport = (req: DataExportRequest) => {+ // Forward the user-typed query (`params.statement`) rather than+ // `result.statement`. The backend may rewrite the result statement+ // with an auto-appended LIMIT for non-admin reads — re-running that+ // rewritten SQL on the export path silently caps the exported rows+ // even when the user asks for more. This matches the Vue+ // multi-result export, which already used `executeParams.statement`.+ onExport?.({ ...req, statement: params.statement });+ };++ // ---- Render branches by viewMode ----++ if (viewMode === "AFFECTED-ROWS") {+ return (+ <div+ className={cn(+ "text-md font-normal flex items-center gap-x-1",+ dark ? "text-matrix-green-hover" : "text-control-light"+ )}+ >+ <span>{String(extractSQLRowValuePlain(result.rows[0].values[0]))}</span>+ <span>{t("sql-editor.rows-affected")}</span>+ </div>+ );+ }++ if (viewMode === "EMPTY") {+ return <EmptyView dark={dark} />;+ }++ return (+ <>+ {/* Pre-toolbar messages */}+ {result.messages.length > 0 && (+ <>+ {result.messages.map((message, i) => (+ <div key={`message-${i}`} className="text-control-light">+ <div>{`[${message.level}] ${message.content}`}</div>+ </div>+ ))}+ </>+ )}++ {viewMode === "RESULT" && (+ <>+ {result.error && (+ <Alert variant="error" className="w-full mb-2">+ <ErrorView dark={dark} error={result.error} />+ </Alert>+ )}++ {/* 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}+ />+ <Tooltip+ content={+ reachQueryLimit ? t("sql-editor.rows-upper-limit") : ""+ }+ >+ <div className="flex items-center gap-x-1 whitespace-nowrap text-sm text-control-light">+ {reachQueryLimit && (+ <InfoIcon className="size-4 text-warning" />+ )}+ {resultRowsText}+ </div>+ </Tooltip>+ </div>+ <div className="flex justify-between items-center shrink-0 gap-x-2">+ {supportsTableViewToggle && (+ <div className="flex items-center gap-x-1">+ <Switch+ checked={noSQLTableView}+ onCheckedChange={setNoSQLTableView}+ />+ <span className="whitespace-nowrap text-sm text-control-light">+ {t("sql-editor.table-view")}+ </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 && (+ <Button+ size="sm"+ variant="outline"+ className="h-7 px-2"+ onClick={copyAll}+ >+ <CopyIcon className="size-4" />+ {t("common.copy")}+ </Button>+ )}+ {showExport && (+ <DataExportButton+ size="sm"+ disabled={!result || isEmpty(result)}+ supportFormats={[+ ExportFormat.CSV,+ ExportFormat.JSON,+ ExportFormat.SQL,+ ExportFormat.XLSX,+ ]}+ viewMode="DRAWER"+ supportPassword+ maximumExportCount={maximumExportCount}+ formContent={<DatabaseInfo database={database} />}+ onExport={handleExport}+ />+ )}+ </div>+ <SelectionCopyTooltips />+ </div>++ {/* Body */}+ <div+ className={cn(+ "w-full flex flex-col relative",+ dark ? "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"+ variant="ghost"+ disabled={searchCandidateActiveIndex <= 0}+ onClick={scrollToPreviousCandidate}+ >+ <ArrowUpIcon className="size-4" />+ {t("sql-editor.previous-row")}+ </Button>+ <Button+ size="sm"+ variant="ghost"+ disabled={+ searchCandidateActiveIndex >=+ searchCandidateRowIndexs.length - 1+ }+ onClick={scrollToNextCandidate}+ >+ <ArrowDownIcon className="size-4" />+ {t("sql-editor.next-row")}+ </Button>+ <Button+ size="sm"+ variant="ghost"+ className="size-7 p-0"+ onClick={clearSearchCandidate}+ >+ <XIcon className="size-4" />+ </Button>+ </div>+ )}++ <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"+ variant="ghost"+ 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"+ variant="ghost"+ className="size-9 p-0 rounded-full"+ onClick={() => scrollToRow(rows.length - 1)}+ >+ <ArrowDownIcon className="size-4" />+ </Button>+ </div>+ </Tooltip>+ </div>+ </div>+ </div>++ {/* Status bar */}+ <div className="w-full flex items-center justify-between text-xs mt-1 gap-x-4 text-control-light">+ <div className="flex items-center gap-x-2">+ <RichDatabaseName database={database} />+ <div className="flex items-center gap-x-1 min-w-0">+ <EllipsisText+ text={result.statement ?? ""}+ className="truncate"+ />+ <CopyInlineButton text={result.statement ?? ""} />+ </div>+ </div>+ <div className="flex shrink-0 items-center gap-x-2">+ {showVisualizeButton && (+ <Button+ size="sm"+ variant="link"+ className="h-auto px-0 text-xs"+ onClick={visualizeExplain}+ >+ {t("sql-editor.visualize-explain")}+ </Button>+ )}+ <span>+ {t("sql-editor.query-time")}: {queryTime}+ </span>+ </div>+ </div>+ </>+ )}++ <DetailPanel rows={rows} columns={columns} />+ </>+ );+}++// ---------------------------------------------------------------------------+// Inline helpers — small enough to live in this file.+// ---------------------------------------------------------------------------++function useLocalStorageBoolean(+ key: string,+ defaultValue: boolean+): [boolean, (next: boolean) => void] {+ const [value, setValue] = useState<boolean>(() => {+ try {+ const raw = localStorage.getItem(key);+ if (raw === "true") return true;+ if (raw === "false") return false;+ } catch {+ // ignore+ }+ return defaultValue;+ });+ const update = useCallback(+ (next: boolean) => {+ setValue(next);+ try {+ localStorage.setItem(key, String(next));+ } catch {+ // ignore+ }+ },+ [key]+ );+ return [value, update];+}++/**+ * Inline simplified renderer mirroring the visible output of Vue+ * `RichDatabaseName` with default props: engine icon + instance title ++ * chevron + environment + database. Skips the popover-on-hover branch+ * (only used by `tooltip="instance"` callers; result-view doesn't set it).+ */+function RichDatabaseName({ database }: { database: Database }) {+ const instance = getInstanceResource(database);+ const environment = getDatabaseEnvironment(database);+ const { databaseName } = extractDatabaseResourceName(database.name);+ return (+ <div className="flex flex-row justify-start items-center gap-x-1">+ <EngineIcon engine={instance.engine} className="size-4" />+ <span>{instanceV1Name(instance)}</span>+ <ChevronRightIcon className="size-3" />+ <span className="flex flex-row items-center gap-x-1">+ <span className="text-control-light">{environment.title}</span>+ <span>{databaseName}</span>+ </span>+ </div>+ );+}++/**+ * Inline simplified `DatabaseInfo` for the export drawer's form-prefix slot.+ * Vue version showed `[engine] instance > [env] database`; we mirror that.+ */+function DatabaseInfo({ database }: { database: Database }) {+ const { t } = useTranslation();+ return (+ <div className="flex flex-col gap-1 mb-3">+ <span className="text-xs text-control-light">{t("common.database")}</span>+ <RichDatabaseName database={database} />+ </div>+ );+}++function CopyInlineButton({ text }: { text: string }) {+ const [copied, setCopied] = useState(false);+ const handleCopy = async () => {+ try {+ await navigator.clipboard.writeText(text);+ setCopied(true);+ window.setTimeout(() => setCopied(false), 1500);+ } catch {+ // ignore+ }+ };+ return (+ <button+ type="button"+ onClick={handleCopy}+ className="text-control-light hover:text-control"+ aria-label="copy"+ >+ <CopyIcon className={cn("size-3", copied && "text-accent")} />+ </button>+ );+}++function getExplainTokenFromResult(+ result: QueryResult,+ engine: Engine+): string | undefined {+ const { statement } = result;+ if (!statement) return undefined;+ const lines = result.rows.map((row) =>+ row.values.map((value) => String(extractSQLRowValuePlain(value)))+ );+ const explain = lines.map((line) => line[0]).join("\n");+ if (!explain) return undefined;+ return createExplainToken({ statement, explain, engine });+}++async function getExplainTokenForMSSQL(+ database: Database,+ params: SQLEditorQueryParams,+ runQuery: ReturnType<typeof useExecuteSQL>["runQuery"]+): Promise<string | undefined> {+ const context: SQLEditorDatabaseQueryContext = {+ id: uuidv4(),+ params: {+ ...params,+ queryOption: create(QueryOptionSchema, {+ mssqlExplainFormat:+ QueryOption_MSSQLExplainFormat.MSSQL_EXPLAIN_FORMAT_XML,+ }),+ },+ status: "PENDING",+ };+ await runQuery(database, context);+ const result = context.resultSet?.results[0];+ if (!result) return undefined;+ return getExplainTokenFromResult(result, Engine.MSSQL);+}diff --git a/frontend/src/react/components/sql-editor/ResultView/TableCell.tsx b/frontend/src/react/components/sql-editor/ResultView/TableCell.tsxnew file mode 100644index 0000000000..ae61d55c84--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/TableCell.tsx@@ -0,0 +1,172 @@+import { ExpandIcon } from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";+import { HighlightLabelText } from "@/react/components/HighlightLabelText";+import { Button } from "@/react/components/ui/button";+import { cn } from "@/react/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 {+ useBinaryFormatContext,+ useSelectionContext,+ useSQLResultViewContext,+} from "./context";++interface TableCellProps {+ value: RowValue;+ rowIndex: number;+ colIndex: number;+ allowSelect?: boolean;+ columnType: string;+ database: Database;+ scope?: SearchScope;+ keyword: string;+}++export function TableCell({+ value,+ rowIndex,+ colIndex,+ allowSelect: allowSelectProp,+ columnType,+ database,+ scope,+ keyword,+}: TableCellProps) {+ const { setDetail } = useSQLResultViewContext();+ const { getBinaryFormat, setBinaryFormat } = useBinaryFormatContext();+ const {+ state: selectionState,+ disabled: selectionDisabled,+ toggleSelectCell,+ toggleSelectRow,+ } = useSelectionContext();++ const cellRef = useRef<HTMLDivElement>(null);+ const wrapperRef = useRef<HTMLDivElement>(null);+ const [truncated, setTruncated] = useState(false);++ const allowSelect = !!allowSelectProp && !selectionDisabled;+ const hasByteData = value.kind?.case === "bytesValue";++ const binaryFormat = getBinaryFormat({ rowIndex, colIndex });++ // ResizeObserver replaces Vue's `useResizeObserver(cellRef, ...)`.+ useEffect(() => {+ const cell = cellRef.current;+ const wrapper = wrapperRef.current;+ if (!cell || !wrapper) return;+ const measure = () => {+ const verticalTruncated = wrapper.scrollHeight > wrapper.offsetHeight + 2;+ const horizontalTruncated = wrapper.scrollWidth > cell.offsetWidth + 2;+ setTruncated(verticalTruncated || horizontalTruncated);+ };+ measure();+ const observer = new ResizeObserver(measure);+ observer.observe(cell);+ 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 selected = useMemo(() => {+ if (!allowSelect) return false;+ const { columns, rows } = selectionState;+ if (columns.length === 1 && rows.length === 1) {+ return columns[0] === colIndex && rows[0] === rowIndex;+ }+ 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 });+ };++ const handleClick = (e: React.MouseEvent) => {+ if (!allowSelect) return;+ if (window.getSelection()?.toString()) return;+ if (e.ctrlKey || e.metaKey) {+ toggleSelectRow(rowIndex);+ } else {+ toggleSelectCell(rowIndex, colIndex);+ }+ e.stopPropagation();+ };++ 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} />;+ }++ return (+ <div+ ref={cellRef}+ onClick={handleClick}+ onDoubleClick={showDetail}+ className={cn(+ "px-2 py-1 flex items-center",+ allowSelect ? "cursor-pointer hover:bg-accent/10" : "select-none",+ selected && "bg-accent/20!"+ )}+ >+ <div+ ref={wrapperRef}+ className="font-mono text-start wrap-break-word line-clamp-3"+ >+ {inner}+ </div>+ <div className="absolute right-1 top-1/2 -translate-y-[45%] flex items-center gap-1">+ {hasByteData && (+ <BinaryFormatButton+ format={binaryFormat}+ onFormatChange={(format: BinaryFormat) =>+ setBinaryFormat({ colIndex, rowIndex, format })+ }+ />+ )}+ {clickable && (+ <Button+ size="sm"+ variant="outline"+ className="size-6 p-0 rounded-full shadow opacity-90 hover:opacity-100"+ onClick={(e) => {+ e.stopPropagation();+ showDetail();+ }}+ >+ <ExpandIcon className="size-3" />+ </Button>+ )}+ </div>+ </div>+ );+}diff --git a/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.tsx b/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.tsxnew file mode 100644index 0000000000..1141064eba--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.tsx@@ -0,0 +1,235 @@+import { useVirtualizer } from "@tanstack/react-virtual";+import { CheckIcon, CopyIcon } from "lucide-react";+import {+ forwardRef,+ useCallback,+ useImperativeHandle,+ useRef,+ useState,+} from "react";+import { useTranslation } from "react-i18next";+import { MaskingReasonPopover } from "@/react/components/sql-editor/MaskingReasonPopover";+import { Button } from "@/react/components/ui/button";+import { Tooltip } from "@/react/components/ui/tooltip";+import { cn } from "@/react/lib/utils";+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 { TableCell } from "./TableCell";+import type { ResultTableColumn, ResultTableRow } from "./types";++export interface VirtualDataBlockHandle {+ scrollTo(index: number): void;+}++export interface VirtualDataBlockProps {+ rows: ResultTableRow[];+ columns: ResultTableColumn[];+ activeRowIndex: number;+ isSensitiveColumn: (index: number) => boolean;+ getMaskingReason?: (index: number) => MaskingReason | undefined;+ database: Database;+ statement?: string;+ search: SearchParams;+}++/**+ * Vertical "row blocks" view of the result set — each row renders as a+ * stacked card showing every column on its own line. Used when the user+ * toggles list mode in `SingleResultView`.+ */+export const VirtualDataBlock = forwardRef<+ VirtualDataBlockHandle,+ VirtualDataBlockProps+>(function VirtualDataBlock(+ {+ rows,+ columns,+ activeRowIndex,+ getMaskingReason,+ database,+ statement,+ search,+ },+ ref+) {+ const { t } = useTranslation();+ const containerRef = useRef<HTMLDivElement>(null);+ const { getBinaryFormat } = useBinaryFormatContext();++ // Estimate based on column count: header + (per-column line ≈ 28px) ++ // padding. Real measurements come from `measureElement` once mounted.+ const estimateRowHeight = useCallback(+ () => 60 + columns.length * 28,+ [columns.length]+ );++ const virtualizer = useVirtualizer({+ count: rows.length,+ getScrollElement: () => containerRef.current,+ estimateSize: estimateRowHeight,+ measureElement: (el) => el.getBoundingClientRect().height,+ overscan: 4,+ });++ useImperativeHandle(+ ref,+ () => ({+ scrollTo(index: number) {+ virtualizer.scrollToIndex(index, {+ align: "start",+ behavior: "smooth",+ });+ },+ }),+ [virtualizer]+ );++ const buildRowJSON = useCallback(+ (rowIndex: number): string => {+ const obj = columns.reduce(+ (acc, column, columnIndex) => {+ if (!column.name) return acc;+ const binaryFormat = getBinaryFormat({+ rowIndex,+ colIndex: columnIndex,+ });+ acc[column.name] = getPlainValue(+ rows[rowIndex].item.values[columnIndex],+ column.columnType,+ binaryFormat+ );+ return acc;+ },+ {} as Record<string, unknown>+ );+ return JSON.stringify(obj, null, 4);+ },+ [columns, rows, getBinaryFormat]+ );++ return (+ <div+ ref={containerRef}+ className="relative w-full flex-1 min-h-0 overflow-auto rounded-sm border"+ >+ <div+ style={{+ height: `${virtualizer.getTotalSize()}px`,+ position: "relative",+ }}+ >+ {virtualizer.getVirtualItems().map((virtualRow) => {+ const rowIndex = virtualRow.index;+ const row = rows[rowIndex];+ if (!row) return null;+ const isActive = activeRowIndex === rowIndex;+ return (+ <div+ key={virtualRow.key}+ ref={virtualizer.measureElement}+ data-index={rowIndex}+ className="font-mono mb-2 mx-2 absolute inset-x-0"+ style={{+ top: 0,+ transform: `translateY(${virtualRow.start}px)`,+ }}+ >+ <p className="font-bold text-control-light overflow-hidden whitespace-nowrap mb-1">+ ******************************** {rowIndex + 1}. row+ ********************************+ </p>+ <div+ className={cn(+ "py-2 px-3 bg-control-bg 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>+ </div>+ );+ })}+ </div>+ </div>+ );+});++function CopyJSONButton({+ getContent,+ label,+}: {+ getContent: () => string;+ label: string;+}) {+ const [copied, setCopied] = useState(false);+ const handleCopy = async () => {+ try {+ await navigator.clipboard.writeText(getContent());+ setCopied(true);+ window.setTimeout(() => setCopied(false), 2000);+ } catch {+ // ignore+ }+ };+ return (+ <div className="absolute right-2 top-2 z-10 opacity-70 hover:opacity-100">+ <Tooltip content={label}>+ <Button+ size="sm"+ variant="ghost"+ className="size-7 p-0"+ onClick={handleCopy}+ >+ {copied ? (+ <CheckIcon className="size-4" />+ ) : (+ <CopyIcon className="size-4" />+ )}+ </Button>+ </Tooltip>+ </div>+ );+}diff --git a/frontend/src/react/components/sql-editor/ResultView/VirtualDataTable.tsx b/frontend/src/react/components/sql-editor/ResultView/VirtualDataTable.tsxnew file mode 100644index 0000000000..f1d3cab5e5--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/VirtualDataTable.tsx@@ -0,0 +1,512 @@+import { useVirtualizer } from "@tanstack/react-virtual";+import { head, last } from "lodash-es";+import {+ forwardRef,+ useCallback,+ useEffect,+ useImperativeHandle,+ useMemo,+ useRef,+ useState,+} from "react";+import { MaskingReasonPopover } from "@/react/components/sql-editor/MaskingReasonPopover";+import { cn } from "@/react/lib/utils";+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 { BinaryFormatButton } from "./BinaryFormatButton";+import {+ type BinaryFormat,+ getBinaryFormatByColumnType,+} from "./binary-format";+import { ColumnSortedIcon } from "./ColumnSortedIcon";+import { getPlainValue } from "./cell-value";+import { useBinaryFormatContext, useSelectionContext } from "./context";+import { TableCell } from "./TableCell";+import type {+ ResultTableColumn,+ ResultTableRow,+ SortDirection,+ SortState,+} from "./types";+import { useTableResize } from "./useTableResize";++const ROW_HEIGHT = 35;+const MIN_COL_WIDTH = 64;+const MAX_COL_WIDTH = 640;++export interface VirtualDataTableHandle {+ scrollTo(index: number): void;+}++export interface VirtualDataTableProps {+ rows: ResultTableRow[];+ columns: ResultTableColumn[];+ activeRowIndex: number;+ isSensitiveColumn: (index: number) => boolean;+ getMaskingReason?: (index: number) => MaskingReason | undefined;+ database: Database;+ statement?: string;+ sortState?: SortState;+ search: SearchParams;+ onToggleSort: (columnIndex: number) => void;+}++/**+ * Virtualized result-table grid. Replaces the Naive UI `NVirtualList` host+ * with `@tanstack/react-virtual`'s `useVirtualizer`. The header is a+ * separate sticky row outside the virtual scroller so it can stay fixed+ * during vertical scroll without fighting the virtualizer's internal+ * positioning.+ */+export const VirtualDataTable = forwardRef<+ VirtualDataTableHandle,+ VirtualDataTableProps+>(function VirtualDataTable(+ {+ rows,+ columns,+ activeRowIndex,+ getMaskingReason,+ database,+ statement,+ sortState,+ search,+ onToggleSort,+ },+ ref+) {+ const containerRef = useRef<HTMLDivElement>(null);+ const [containerWidth, setContainerWidth] = useState(0);++ // Track container width for last-column extra-space distribution.+ useEffect(() => {+ const el = containerRef.current;+ if (!el) return;+ const update = () => setContainerWidth(el.clientWidth);+ update();+ const observer = new ResizeObserver(update);+ observer.observe(el);+ return () => observer.disconnect();+ }, []);++ const {+ state: selectionState,+ disabled: selectionDisabled,+ toggleSelectColumn,+ toggleSelectRow,+ deselect,+ } = useSelectionContext();++ const { getBinaryFormat, setBinaryFormat } = useBinaryFormatContext();++ const getColumnTypeByIndex = useCallback(+ (columnIndex: number) => columns[columnIndex]?.columnType ?? "",+ [columns]+ );++ const getRowCellContent = useCallback(+ (columnIndex: number): string | undefined => {+ // Sample up to 3 rows for column-width estimation.+ for (let i = 0; i < Math.min(3, rows.length); i++) {+ const sampleRow = rows[i];+ if (!sampleRow) continue;+ const cell = sampleRow.item.values[columnIndex];+ if (!cell) continue;+ const plain = getPlainValue(+ cell,+ getColumnTypeByIndex(columnIndex),+ "DEFAULT"+ );+ if (plain) return plain;+ }+ return undefined;+ },+ [rows, getColumnTypeByIndex]+ );++ const tableResize = useTableResize({+ columns,+ rows,+ containerWidth,+ minWidth: MIN_COL_WIDTH,+ maxWidth: MAX_COL_WIDTH,+ getRowCellContent,+ });++ const virtualizer = useVirtualizer({+ count: rows.length,+ getScrollElement: () => containerRef.current,+ estimateSize: () => ROW_HEIGHT,+ overscan: 8,+ });++ useImperativeHandle(+ ref,+ () => ({+ scrollTo(index: number) {+ virtualizer.scrollToIndex(Math.max(0, index - 1), {+ align: "start",+ behavior: "smooth",+ });+ },+ }),+ [virtualizer]+ );++ const getColumnSortDirection = (columnIndex: number): SortDirection => {+ if (!sortState || sortState.columnIndex !== columnIndex) return false;+ return sortState.direction;+ };++ const hasRowSelect =+ selectionState.columns.length === 0 && selectionState.rows.length > 0;+ const hasColumnSelect =+ selectionState.columns.length > 0 && selectionState.rows.length === 0;++ const handleSelectRow = (e: React.MouseEvent, index: number) => {+ e.stopPropagation();+ if ((e.metaKey || e.ctrlKey) && hasRowSelect) {+ const firstRowIndex = head(selectionState.rows);+ const lastRowIndex = last(selectionState.rows);+ if (lastRowIndex !== undefined && index > lastRowIndex) {+ for (let i = lastRowIndex + 1; i <= index; i++) toggleSelectRow(i);+ } else if (firstRowIndex !== undefined && index < firstRowIndex) {+ deselect();+ for (let i = index; i <= firstRowIndex; i++) toggleSelectRow(i);+ }+ return;+ }+ toggleSelectRow(index);+ };++ const handleSelectColumn = (e: React.MouseEvent, index: number) => {+ e.stopPropagation();+ if ((e.metaKey || e.ctrlKey) && hasColumnSelect) {+ const firstCol = head(selectionState.columns);+ const lastCol = last(selectionState.columns);+ if (lastCol !== undefined && index > lastCol) {+ for (let i = lastCol + 1; i <= index; i++) toggleSelectColumn(i);+ } else if (firstCol !== undefined && index < firstCol) {+ deselect();+ for (let i = index; i <= firstCol; i++) toggleSelectColumn(i);+ }+ return;+ }+ toggleSelectColumn(index);+ };++ // Precompute the set of column indices that hold any binary cell value.+ // Done once per `rows` / `columns` change instead of per-header-render —+ // the per-header form was O(rows × columns) on every VirtualDataTable+ // render and stalled the main thread on large result sets.+ const binaryColumnSet = useMemo(() => {+ const candidates: number[] = [];+ for (let i = 0; i < columns.length; i++) {+ if (getBinaryFormatByColumnType(columns[i]?.columnType)) {+ candidates.push(i);+ }+ }+ if (candidates.length === 0) return new Set<number>();+ const out = new Set<number>();+ const remaining = new Set(candidates);+ for (const row of rows) {+ if (remaining.size === 0) break;+ for (const colIdx of [...remaining]) {+ const cell = row.item.values[colIdx];+ if (cell?.kind?.case === "bytesValue") {+ out.add(colIdx);+ remaining.delete(colIdx);+ }+ }+ }+ return out;+ }, [columns, rows]);++ // Shift+wheel for mouse + trackpad horizontal swipes.+ useEffect(() => {+ const container = containerRef.current;+ if (!container) return;+ const handleWheel = (event: WheelEvent) => {+ const hasHorizontalOverflow =+ container.scrollWidth > container.clientWidth;+ if (!hasHorizontalOverflow) return;+ if (event.shiftKey) {+ event.preventDefault();+ event.stopPropagation();+ container.scrollLeft += event.deltaY || event.deltaX;+ return;+ }+ if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) {+ event.preventDefault();+ event.stopPropagation();+ container.scrollLeft += event.deltaX;+ }+ };+ container.addEventListener("wheel", handleWheel, {+ passive: false,+ capture: true,+ });+ return () => {+ container.removeEventListener("wheel", handleWheel, { capture: true });+ };+ }, []);++ const totalRows = rows.length;+ const indexColWidth = tableResize.getColumnWidth(0);++ // The header row sits outside the virtualizer so it stays sticky during+ // vertical scroll. Same min-width as body rows so horizontal scroll+ // syncs visually.+ const minRowWidth = useMemo(+ () => `${tableResize.effectiveWidth}px`,+ [tableResize.effectiveWidth]+ );++ return (+ <div+ ref={containerRef}+ className="relative w-full flex-1 min-h-0 overflow-auto rounded-sm border"+ >+ {/* Header */}+ <div+ className="sticky top-0 z-1 bg-control-bg flex shadow-sm"+ style={{ minWidth: minRowWidth }}+ >+ {/* Index header */}+ <HeaderCell+ width={indexColWidth}+ onResizeStart={(e) => tableResize.onResizeStart(0, e)}+ >+ <div+ className={cn(+ "textinfolabel pr-1 opacity-0",+ selectionDisabled ? "pl-1" : "pl-4"+ )}+ >+ {totalRows}+ </div>+ </HeaderCell>++ {/* Data column headers */}+ {columns.map((header, columnIndex) => {+ const slotWidth = tableResize.getColumnWidth(columnIndex + 1);+ const isLast = columnIndex === columns.length - 1;+ const isSelected =+ selectionState.rows.length === 0 &&+ selectionState.columns.includes(columnIndex);+ const reason = getMaskingReason?.(columnIndex);+ return (+ <HeaderCell+ key={`${columnIndex}-${header.id}`}+ width={slotWidth}+ borderRight={!isLast}+ onResizeStart={(e) =>+ tableResize.onResizeStart(columnIndex + 1, e)+ }+ onClick={(e) => handleSelectColumn(e, columnIndex)}+ className={cn(+ "px-3 py-1.5 min-w-8 text-left text-xs font-medium text-control-light tracking-wider",+ !selectionDisabled &&+ "cursor-pointer hover:bg-control-bg-hover",+ isSelected && "bg-accent/10!"+ )}+ >+ <div className="flex items-center min-w-0 gap-x-1">+ <span className="min-w-0 truncate select-none">+ {String(header.name).length > 0 ? (+ header.name+ ) : (+ <br className="min-h-4 inline-flex" />+ )}+ </span>+ {reason && (+ <span className="shrink-0">+ <MaskingReasonPopover+ reason={reason}+ statement={statement}+ database={database.name}+ />+ </span>+ )}+ <span+ onClick={(e) => {+ e.stopPropagation();+ onToggleSort(columnIndex);+ }}+ role="button"+ tabIndex={-1}+ className="shrink-0 inline-flex"+ >+ <ColumnSortedIcon+ isSorted={getColumnSortDirection(columnIndex)}+ />+ </span>+ {binaryColumnSet.has(columnIndex) && (+ <span+ onClick={(e) => e.stopPropagation()}+ className="shrink-0"+ >+ <BinaryFormatButton+ format={getBinaryFormat({ colIndex: columnIndex })}+ onFormatChange={(format: BinaryFormat) =>+ setBinaryFormat({ colIndex: columnIndex, format })+ }+ />+ </span>+ )}+ </div>+ </HeaderCell>+ );+ })}+ </div>++ {/* Virtualized body */}+ <div+ style={{+ height: `${virtualizer.getTotalSize()}px`,+ minWidth: minRowWidth,+ position: "relative",+ }}+ >+ {virtualizer.getVirtualItems().map((virtualRow) => {+ const rowIndex = virtualRow.index;+ const row = rows[rowIndex];+ if (!row) return null;+ const isActive = activeRowIndex === rowIndex;+ const rowSelected =+ selectionState.columns.length === 0 &&+ selectionState.rows.includes(rowIndex);+ return (+ <div+ key={virtualRow.key}+ data-row-index={rowIndex}+ className="flex absolute inset-x-0 group"+ style={{+ top: 0,+ transform: `translateY(${virtualRow.start}px)`,+ height: `${ROW_HEIGHT}px`,+ minWidth: minRowWidth,+ }}+ >+ {/* Index cell */}+ <div+ className={cn(+ "relative flex items-center shrink-0 text-sm leading-5 whitespace-nowrap break-all border-block-border border-r border-b group-even:bg-control-bg/40",+ isActive && "bg-accent/10!",+ rowSelected && "bg-accent/20!"+ )}+ data-col-index={0}+ style={{+ height: `${ROW_HEIGHT}px`,+ width: `${indexColWidth}px`,+ }}+ >+ <span+ className={cn(+ "textinfolabel pr-1 truncate",+ selectionDisabled ? "pl-1" : "pl-4"+ )}+ >+ {rowIndex + 1}+ </span>+ {!selectionDisabled && (+ <button+ type="button"+ aria-label={`Select row ${rowIndex + 1}`}+ onClick={(e) => handleSelectRow(e, rowIndex)}+ className={cn(+ "absolute inset-y-0 left-0 w-3 cursor-pointer bg-accent/5 hover:bg-accent/10",+ rowSelected && "bg-accent/20!"+ )}+ />+ )}+ </div>++ {/* Data cells */}+ {row.item.values.map((cell, columnIndex) => {+ const cellWidth = tableResize.getColumnWidth(columnIndex + 1);+ const isLastCol = columnIndex === row.item.values.length - 1;+ return (+ <div+ key={`${rowIndex}-${columnIndex + 1}`}+ className={cn(+ "relative shrink-0 text-sm leading-5 whitespace-nowrap break-all border-block-border border-b group-even:bg-control-bg/40",+ !isLastCol && "border-r",+ // Match the Vue version: an active (search-matched) row+ // highlights every cell in that row, not just the index+ // column.+ isActive && "bg-accent/10!"+ )}+ data-col-index={columnIndex + 1}+ style={{+ height: `${ROW_HEIGHT}px`,+ width: `${cellWidth}px`,+ }}+ >+ <div className="h-full flex items-center overflow-hidden">+ <TableCell+ value={cell}+ keyword={search.query}+ scope={search.scopes.find(+ (s) => s.id === columns[columnIndex]?.id+ )}+ rowIndex={rowIndex}+ colIndex={columnIndex}+ allowSelect+ columnType={getColumnTypeByIndex(columnIndex)}+ database={database}+ />+ </div>+ </div>+ );+ })}+ </div>+ );+ })}+ </div>+ </div>+ );+});++interface HeaderCellProps {+ width: number;+ borderRight?: boolean;+ onResizeStart: (e: React.PointerEvent) => void;+ onClick?: (e: React.MouseEvent) => void;+ className?: string;+ children?: React.ReactNode;+}++function HeaderCell({+ width,+ borderRight,+ onResizeStart,+ onClick,+ className,+ children,+}: HeaderCellProps) {+ return (+ <div+ onClick={onClick}+ className={cn(+ "group relative shrink-0 border-block-border",+ borderRight ? "border-x" : "border-l",+ className+ )}+ style={{ width: `${width}px` }}+ >+ {children}+ <span+ role="separator"+ aria-orientation="vertical"+ onPointerDown={onResizeStart}+ onClick={(e) => {+ e.stopPropagation();+ e.preventDefault();+ }}+ className="absolute w-2 right-0 top-0 bottom-0 cursor-col-resize"+ />+ </div>+ );+}diff --git a/frontend/src/react/components/sql-editor/ResultView/binary-format.ts b/frontend/src/react/components/sql-editor/ResultView/binary-format.tsnew file mode 100644index 0000000000..85428446d5--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/binary-format.ts@@ -0,0 +1,155 @@+/**+ * Binary-format helpers ported 1:1 from+ * `frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/binary-format-store.ts`.+ * Pure logic; the React-flavoured Map state lives in `context.tsx`.+ */++export type BinaryFormat = "DEFAULT" | "BINARY" | "HEX" | "TEXT" | "BOOLEAN";++interface ColumnKeyParams {+ colIndex: number;+}++interface CellKeyParams extends ColumnKeyParams {+ rowIndex: number;+}++export const getCellKey = (params: CellKeyParams): string => {+ const { rowIndex } = params;+ return `row_${rowIndex}:${getColumnKey(params)}`;+};++export const getColumnKey = (params: ColumnKeyParams): string => {+ const { colIndex } = params;+ return `col_${colIndex}`;+};++export interface GetBinaryFormatParams {+ rowIndex?: number;+ colIndex: number;+}++export interface BinaryFormatParams extends GetBinaryFormatParams {+ format: BinaryFormat;+}++export const detectBinaryFormat = (params: {+ bytesValue: Uint8Array | undefined;+ columnType: string;+}): BinaryFormat => {+ const { bytesValue, columnType = "" } = params;+ if (!bytesValue || bytesValue.length === 0 || columnType === "") {+ return "DEFAULT";+ }++ const byteArray = Array.from(bytesValue);++ // For single-bit values (could be boolean).+ if (byteArray.length === 1 && (byteArray[0] === 0 || byteArray[0] === 1)) {+ return "BOOLEAN";+ }++ // Readable ASCII text → display as text.+ const isReadableText = byteArray.every((byte) => byte >= 32 && byte <= 126);+ if (isReadableText) {+ return "TEXT";+ }++ return getBinaryFormatByColumnType(columnType) ?? "DEFAULT";+};++export const formatBinaryValue = ({+ bytesValue,+ format,+}: {+ bytesValue: Uint8Array | undefined;+ format: BinaryFormat;+}): string => {+ if (!bytesValue || bytesValue.length === 0) {+ return "";+ }++ const byteArray = Array.from(bytesValue);+ const binaryValue = byteArray+ .map((byte) => byte.toString(2).padStart(8, "0"))+ .join("");++ switch (format) {+ case "BINARY":+ return binaryValue;+ case "TEXT":+ try {+ return new TextDecoder().decode(new Uint8Array(byteArray));+ } catch {+ return binaryValue;+ }+ case "HEX":+ return (+ "0x" ++ byteArray+ .map((byte) => byte.toString(16).toUpperCase().padStart(2, "0"))+ .join("")+ );+ case "BOOLEAN":+ if (+ byteArray.length === 1 &&+ (byteArray[0] === 0 || byteArray[0] === 1)+ ) {+ return byteArray[0] === 1 ? "true" : "false";+ }+ // fallthrough+ default:+ return binaryValue;+ }+};++/**+ * Pick the natural format for a column based on its declared type.+ * BIT-family columns default to BINARY, BYTEA-family to HEX. Unknown+ * types return undefined (the caller falls back to content sniffing).+ */+export const getBinaryFormatByColumnType = (+ rawType: string | undefined+): BinaryFormat | undefined => {+ if (!rawType) return undefined;+ const columnType = rawType.toLowerCase();+ if (!columnType) return undefined;++ // BIT family — display as binary digits.+ const isBitColumn =+ columnType === "bit" ||+ columnType.startsWith("bit(") ||+ (columnType.includes("bit") && !columnType.includes("binary")) ||+ columnType === "varbit" ||+ columnType === "bit varying";++ if (isBitColumn) return "BINARY";++ // BINARY / BYTEA / BLOB / spatial — display as hex.+ const isBinaryColumn =+ columnType === "binary" ||+ columnType.includes("binary") ||+ columnType.startsWith("binary(") ||+ columnType.startsWith("varbinary") ||+ columnType.includes("blob") ||+ columnType === "longblob" ||+ columnType === "mediumblob" ||+ columnType === "tinyblob" ||+ columnType === "bytea" ||+ columnType === "image" ||+ columnType === "varbinary(max)" ||+ columnType === "raw" ||+ columnType === "long raw" ||+ columnType === "geometry" ||+ columnType === "geography" ||+ columnType === "point" ||+ columnType === "linestring" ||+ columnType === "polygon" ||+ columnType === "multipoint" ||+ columnType === "multilinestring" ||+ columnType === "multipolygon" ||+ columnType === "geometrycollection";++ if (isBinaryColumn) return "HEX";+ return undefined;+};diff --git a/frontend/src/react/components/sql-editor/ResultView/cell-value.ts b/frontend/src/react/components/sql-editor/ResultView/cell-value.tsnew file mode 100644index 0000000000..791d8110ec--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/cell-value.ts@@ -0,0 +1,45 @@+import type { RowValue } from "@/types/proto-es/v1/sql_service_pb";+import { extractSQLRowValuePlain } from "@/utils/v1/sql";+import {+ type BinaryFormat,+ detectBinaryFormat,+ formatBinaryValue,+} from "./binary-format";++const getFormattedValue = (+ rowValue: RowValue,+ columnType: string,+ binaryFormat: BinaryFormat | undefined+): RowValue => {+ const bytesValue =+ rowValue.kind?.case === "bytesValue" ? rowValue.kind.value : undefined;+ if (!bytesValue) return rowValue;++ // Override > auto-detect.+ let actualFormat = binaryFormat ?? "DEFAULT";+ if (actualFormat === "DEFAULT") {+ actualFormat = detectBinaryFormat({ bytesValue, columnType });+ }+ const stringValue = formatBinaryValue({ bytesValue, format: actualFormat });+ return {+ ...rowValue,+ kind: { case: "stringValue" as const, value: stringValue },+ };+};++/**+ * Plain-string view of a cell, honouring the active binary format+ * override. Used by selection copy + export paths so the clipboard /+ * file mirrors what the user sees.+ */+export const getPlainValue = (+ rowValue: RowValue | undefined,+ columnType: string,+ binaryFormat: BinaryFormat | undefined+): string | undefined | null => {+ if (!rowValue) return undefined;+ const formatted = getFormattedValue(rowValue, columnType, binaryFormat);+ const value = extractSQLRowValuePlain(formatted);+ if (value === undefined || value === null) return value;+ return String(value);+};diff --git a/frontend/src/react/components/sql-editor/ResultView/context.tsx b/frontend/src/react/components/sql-editor/ResultView/context.tsxnew file mode 100644index 0000000000..3b7e9a7b6b--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/context.tsx@@ -0,0 +1,439 @@+import {+ createContext,+ type ReactNode,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useState,+} from "react";+import { useTranslation } from "react-i18next";+import { pushNotification } from "@/store";+import type { RowValue } from "@/types/proto-es/v1/sql_service_pb";+import { isDescendantOf } from "@/utils/dom";+import { extractSQLRowValuePlain } from "@/utils/v1/sql";+import {+ type BinaryFormat,+ type BinaryFormatParams,+ detectBinaryFormat,+ formatBinaryValue,+ type GetBinaryFormatParams,+ getCellKey,+ getColumnKey,+} from "./binary-format";+import {+ isSingleCellSelected,+ type SelectionState,+ toggleCellInSelection,+ toggleColumnInSelection,+ toggleRowInSelection,+} from "./selection-math";+import type { ResultTableColumn, ResultTableRow } from "./types";++// =============================================================================+// SQLResultViewContext (dark / disallowCopyingData / detail-cell)+// =============================================================================++export interface ResultViewDetail {+ row: number;+ col: number;+}++export interface SQLResultViewContext {+ dark: boolean;+ disallowCopyingData: boolean;+ detail: ResultViewDetail | undefined;+ setDetail: (detail: ResultViewDetail | undefined) => void;+}++const SQLResultViewCtx = createContext<SQLResultViewContext | null>(null);++export function useSQLResultViewContext(): SQLResultViewContext {+ const ctx = useContext(SQLResultViewCtx);+ if (!ctx) {+ throw new Error(+ "useSQLResultViewContext must be called inside <SQLResultViewProvider>"+ );+ }+ return ctx;+}++// =============================================================================+// BinaryFormatContext (per-cell + per-column binary-format Map)+// =============================================================================++export interface BinaryFormatContext {+ getBinaryFormat: (params: GetBinaryFormatParams) => BinaryFormat | undefined;+ setBinaryFormat: (params: BinaryFormatParams) => void;+}++const BinaryFormatCtx = createContext<BinaryFormatContext | null>(null);++export function useBinaryFormatContext(): BinaryFormatContext {+ const ctx = useContext(BinaryFormatCtx);+ if (!ctx) {+ throw new Error(+ "useBinaryFormatContext must be called inside <SQLResultViewProvider>"+ );+ }+ return ctx;+}++// =============================================================================+// SelectionContext (row/column/cell selection + clipboard copy)+// =============================================================================++export type { SelectionState };++export interface SelectionContext {+ state: SelectionState;+ disabled: boolean;+ toggleSelectRow: (row: number) => void;+ toggleSelectColumn: (column: number) => void;+ toggleSelectCell: (row: number, column: number) => void;+ deselect: () => void;+ copySelected: () => void;+ copyAll: () => void;+}++const SelectionCtx = createContext<SelectionContext | null>(null);++export function useSelectionContext(): SelectionContext {+ const ctx = useContext(SelectionCtx);+ if (!ctx) {+ throw new Error(+ "useSelectionContext must be called inside <SQLResultViewProvider>"+ );+ }+ return ctx;+}++// =============================================================================+// Combined provider — mounts all three contexts in nested order.+// =============================================================================++interface SQLResultViewProviderProps {+ dark?: boolean;+ disallowCopyingData?: boolean;+ rows: ResultTableRow[];+ columns: ResultTableColumn[];+ children: ReactNode;+}++/**+ * Per-instance provider for one `<ResultView>` mount. Owns:+ * - The dark/disallowCopying flags + the detail-cell state+ * - The binary-format Map (per-cell and per-column overrides)+ * - The selection state + row/column/cell toggles + clipboard copy+ *+ * Children read these via `useSQLResultViewContext`,+ * `useBinaryFormatContext`, and `useSelectionContext`.+ */+export function SQLResultViewProvider({+ dark = false,+ disallowCopyingData = false,+ rows,+ columns,+ children,+}: SQLResultViewProviderProps) {+ const { t } = useTranslation();++ // ---- SQLResultViewContext ----+ const [detail, setDetail] = useState<ResultViewDetail | undefined>(undefined);+ const sqlResultView = useMemo<SQLResultViewContext>(+ () => ({ dark, disallowCopyingData, detail, setDetail }),+ [dark, disallowCopyingData, detail]+ );++ // ---- BinaryFormatContext ----+ // Live Map kept inside state so updates re-render consumers. Mutators+ // produce a new Map reference each call so React's setState detects+ // the change.+ const [binaryFormatMap, setBinaryFormatMap] = useState<+ Map<string, BinaryFormat>+ >(() => new Map());++ const getBinaryFormat = useCallback(+ (params: GetBinaryFormatParams): BinaryFormat | undefined => {+ const { rowIndex, colIndex } = params;+ if (rowIndex !== undefined) {+ const cellKey = getCellKey({ rowIndex, colIndex });+ if (binaryFormatMap.has(cellKey)) {+ return binaryFormatMap.get(cellKey);+ }+ }+ return binaryFormatMap.get(getColumnKey({ colIndex }));+ },+ [binaryFormatMap]+ );++ const setBinaryFormat = useCallback((params: BinaryFormatParams): void => {+ const { rowIndex, colIndex, format } = params;+ const key =+ rowIndex !== undefined+ ? getCellKey({ rowIndex, colIndex })+ : getColumnKey({ colIndex });+ setBinaryFormatMap((prev) => {+ const next = new Map(prev);+ // DEFAULT means "fall back to column / auto-detect" — drop the entry+ // rather than setting "DEFAULT".+ if (format === "DEFAULT") {+ next.delete(key);+ } else {+ next.set(key, format);+ }+ return next;+ });+ }, []);++ const binaryFormat = useMemo<BinaryFormatContext>(+ () => ({ getBinaryFormat, setBinaryFormat }),+ [getBinaryFormat, setBinaryFormat]+ );++ // ---- SelectionContext ----+ const [selectionState, setSelectionState] = useState<SelectionState>({+ rows: [],+ columns: [],+ });+ const [copying, setCopying] = useState(false);+ const selectionDisabled = disallowCopyingData;++ const deselect = useCallback(() => {+ setSelectionState({ rows: [], columns: [] });+ }, []);++ const toggleSelectRow = useCallback(+ (row: number) => {+ if (selectionDisabled) return;+ setSelectionState((prev) => toggleRowInSelection(prev, row));+ },+ [selectionDisabled]+ );++ const toggleSelectColumn = useCallback(+ (column: number) => {+ if (selectionDisabled) return;+ setSelectionState((prev) => toggleColumnInSelection(prev, column));+ },+ [selectionDisabled]+ );++ const toggleSelectCell = useCallback(+ (row: number, column: number) => {+ if (selectionDisabled) return;+ setSelectionState((prev) => toggleCellInSelection(prev, row, column));+ },+ [selectionDisabled]+ );++ // ----- copy helpers -----+ const escapeTSVValue = (val: string): string => {+ if (val.includes("\t") || val.includes("\n") || val.includes('"')) {+ return `"${val.replaceAll('"', '""')}"`;+ }+ return val;+ };++ const getFormattedValue = useCallback(+ ({+ value,+ colIndex,+ rowIndex,+ }: {+ value: RowValue;+ colIndex: number;+ rowIndex: number;+ }): string => {+ // Binary cells honour any active format override, otherwise sniff+ // by content / column type.+ if (value && value.kind?.case === "bytesValue") {+ const overridden = getBinaryFormat({ colIndex, rowIndex });+ if (overridden) {+ return formatBinaryValue({+ bytesValue: value.kind.value,+ format: overridden,+ });+ }+ const detected = detectBinaryFormat({+ bytesValue: value.kind.value,+ columnType: columns[colIndex]?.columnType ?? "",+ });+ return formatBinaryValue({+ bytesValue: value.kind.value,+ format: detected,+ });+ }+ return String(extractSQLRowValuePlain(value));+ },+ [columns, getBinaryFormat]+ );++ const buildClipboardPayload = useCallback(+ (state: SelectionState): string => {+ if (isSingleCellSelected(state)) {+ const row = rows[state.rows[0]];+ if (!row) return "";+ const cell = row.item.values[state.columns[0]];+ if (!cell) return "";+ return getFormattedValue({+ value: cell,+ colIndex: state.columns[0],+ rowIndex: state.rows[0],+ });+ }++ if (state.rows.length > 0) {+ const columnNames = ["index", ...columns.map((c) => c.name)];+ const lines: string[] = [];+ for (const rowIndex of state.rows) {+ const queryRow = rows[rowIndex]?.item;+ if (!queryRow) continue;+ const cells = queryRow.values+ .map((cell, colIdx) =>+ escapeTSVValue(+ getFormattedValue({ value: cell, colIndex: colIdx, rowIndex })+ )+ )+ .join("\t");+ lines.push(`${rowIndex}\t${cells}`);+ }+ if (lines.length === 0) return "";+ return `${columnNames.join("\t")}\n${lines.join("\n")}`;+ }++ if (state.columns.length > 0) {+ const columnNames = state.columns.map((i) => columns[i]?.name ?? "");+ const lines: string[] = [];+ for (let rowIdx = 0; rowIdx < rows.length; rowIdx++) {+ const cells = state.columns.map((columnIndex, colIdx) => {+ const cell = rows[rowIdx].item.values[columnIndex];+ if (!cell) return "";+ return escapeTSVValue(+ getFormattedValue({+ value: cell,+ rowIndex: rowIdx,+ colIndex: state.columns[colIdx],+ })+ );+ });+ lines.push(cells.join("\t"));+ }+ if (lines.length === 0) return "";+ return `${columnNames.join("\t")}\n${lines.join("\n")}`;+ }++ return "";+ },+ [columns, rows, getFormattedValue]+ );++ const copyToClipboard = useCallback(+ async (state: SelectionState) => {+ if (selectionDisabled || copying) return;+ const payload = buildClipboardPayload(state);+ if (!payload) return;+ setCopying(true);+ try {+ await navigator.clipboard.writeText(payload);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.copied"),+ });+ } catch (err) {+ const errors = [t("common.failed")];+ if (err instanceof Error) errors.push(err.message);+ pushNotification({+ module: "bytebase",+ style: "WARN",+ title: errors.join(": "),+ });+ } finally {+ // Defer so we don't immediately re-permit copy via a+ // bubbled keyboard repeat.+ requestAnimationFrame(() => setCopying(false));+ }+ },+ [selectionDisabled, copying, buildClipboardPayload, t]+ );++ const copySelected = useCallback(() => {+ void copyToClipboard(selectionState);+ }, [copyToClipboard, selectionState]);++ const copyAll = useCallback(() => {+ void copyToClipboard({+ rows: rows.map((_, i) => i),+ columns: [],+ });+ }, [copyToClipboard, rows]);++ // Click outside the result-scroll buttons → deselect (mirrors Vue+ // global click listener in `selection-logic.ts`).+ useEffect(() => {+ if (copying) return;+ const handler = (e: MouseEvent) => {+ if (isDescendantOf(e.target as Element, ".result-scroll-buttons")) {+ return;+ }+ deselect();+ };+ document.addEventListener("click", handler);+ return () => document.removeEventListener("click", handler);+ }, [copying, deselect]);++ // Esc → deselect; Cmd/Ctrl+C → copy selected.+ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if (selectionDisabled) return;+ if (+ selectionState.columns.length === 0 &&+ selectionState.rows.length === 0+ ) {+ return;+ }+ if (e.key === "Escape") {+ deselect();+ }+ if ((e.key === "c" || e.key === "C") && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ e.stopImmediatePropagation();+ copySelected();+ }+ };+ document.addEventListener("keydown", handler);+ return () => document.removeEventListener("keydown", handler);+ }, [selectionDisabled, selectionState, deselect, copySelected]);++ const selection = useMemo<SelectionContext>(+ () => ({+ state: selectionState,+ disabled: selectionDisabled,+ toggleSelectRow,+ toggleSelectColumn,+ toggleSelectCell,+ deselect,+ copySelected,+ copyAll,+ }),+ [+ selectionState,+ selectionDisabled,+ toggleSelectRow,+ toggleSelectColumn,+ toggleSelectCell,+ deselect,+ copySelected,+ copyAll,+ ]+ );++ return (+ <SQLResultViewCtx value={sqlResultView}>+ <BinaryFormatCtx value={binaryFormat}>+ <SelectionCtx value={selection}>{children}</SelectionCtx>+ </BinaryFormatCtx>+ </SQLResultViewCtx>+ );+}diff --git a/frontend/src/react/components/sql-editor/ResultView/index.ts b/frontend/src/react/components/sql-editor/ResultView/index.tsnew file mode 100644index 0000000000..ce57ec4785--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/index.ts@@ -0,0 +1,65 @@+export type {+ BinaryFormatContext,+ ResultViewDetail,+ SelectionContext,+ SelectionState,+ SQLResultViewContext,+} from "./context";+export {+ SQLResultViewProvider,+ useBinaryFormatContext,+ useSelectionContext,+ useSQLResultViewContext,+} from "./context";++export type { BinaryFormat } from "./binary-format";+export {+ detectBinaryFormat,+ formatBinaryValue,+ getBinaryFormatByColumnType,+ getCellKey,+ getColumnKey,+} from "./binary-format";++export { getPlainValue } from "./cell-value";++export type {+ ResultTableColumn,+ ResultTableRow,+ SortDirection,+ SortState,+} from "./types";++export {+ isSingleCellSelected,+ toggleCellInSelection,+ toggleColumnInSelection,+ toggleRowInSelection,+} from "./selection-math";++// Leaf components+export { BinaryFormatButton } from "./BinaryFormatButton";+export { ColumnSortedIcon } from "./ColumnSortedIcon";+export { EmptyView } from "./EmptyView";+export { ErrorView } from "./ErrorView";+export { PostgresError } from "./PostgresError";+export { PrettyJSON } from "./PrettyJSON";+export { SelectionCopyTooltips } from "./SelectionCopyTooltips";+export { SensitiveDataIcon } from "./SensitiveDataIcon";+export { TableCell } from "./TableCell";+export { DetailPanel } from "./DetailPanel";+export {+ VirtualDataTable,+ type VirtualDataTableHandle,+ type VirtualDataTableProps,+} from "./VirtualDataTable";+export {+ VirtualDataBlock,+ type VirtualDataBlockHandle,+ type VirtualDataBlockProps,+} from "./VirtualDataBlock";+export {+ SingleResultView,+ type SingleResultViewProps,+} from "./SingleResultView";+export { ResultView, type ResultViewProps } from "./ResultView";diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/pretty-print-json.css b/frontend/src/react/components/sql-editor/ResultView/pretty-print-json.csssimilarity index 100%rename from frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/pretty-print-json.cssrename to frontend/src/react/components/sql-editor/ResultView/pretty-print-json.cssdiff --git a/frontend/src/react/components/sql-editor/ResultView/selection-math.test.ts b/frontend/src/react/components/sql-editor/ResultView/selection-math.test.tsnew file mode 100644index 0000000000..845b58f4de--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/selection-math.test.ts@@ -0,0 +1,131 @@+import { describe, expect, it } from "vitest";+import {+ isSingleCellSelected,+ type SelectionState,+ toggleCellInSelection,+ toggleColumnInSelection,+ toggleRowInSelection,+} from "./selection-math";++const empty: SelectionState = { rows: [], columns: [] };++describe("isSingleCellSelected", () => {+ it("is true only for exactly one row × one column", () => {+ expect(isSingleCellSelected(empty)).toBe(false);+ expect(isSingleCellSelected({ rows: [3], columns: [1] })).toBe(true);+ expect(isSingleCellSelected({ rows: [3], columns: [] })).toBe(false);+ expect(isSingleCellSelected({ rows: [], columns: [1] })).toBe(false);+ expect(isSingleCellSelected({ rows: [3, 4], columns: [1] })).toBe(false);+ expect(isSingleCellSelected({ rows: [3], columns: [1, 2] })).toBe(false);+ });+});++describe("toggleRowInSelection", () => {+ it("adds a new row in sorted order", () => {+ expect(toggleRowInSelection({ rows: [1, 4], columns: [] }, 2)).toEqual({+ rows: [1, 2, 4],+ columns: [],+ });+ });++ it("removes an already-selected row", () => {+ expect(toggleRowInSelection({ rows: [1, 2, 4], columns: [] }, 2)).toEqual({+ rows: [1, 4],+ columns: [],+ });+ });++ it("clears columns when selecting rows (mode switch)", () => {+ expect(toggleRowInSelection({ rows: [], columns: [0, 3] }, 1)).toEqual({+ rows: [1],+ columns: [],+ });+ });++ it("treats prior single-cell selection as a fresh start", () => {+ // Prior: cell (3,1). Toggling row 5 should NOT keep row 3.+ expect(toggleRowInSelection({ rows: [3], columns: [1] }, 5)).toEqual({+ rows: [5],+ columns: [],+ });+ });++ it("preserves multi-row selection when extending", () => {+ expect(toggleRowInSelection({ rows: [1, 2], columns: [] }, 5)).toEqual({+ rows: [1, 2, 5],+ columns: [],+ });+ });+});++describe("toggleColumnInSelection", () => {+ it("adds a new column in sorted order", () => {+ expect(toggleColumnInSelection({ rows: [], columns: [0, 3] }, 2)).toEqual({+ rows: [],+ columns: [0, 2, 3],+ });+ });++ it("removes an already-selected column", () => {+ expect(+ toggleColumnInSelection({ rows: [], columns: [0, 2, 3] }, 2)+ ).toEqual({+ rows: [],+ columns: [0, 3],+ });+ });++ it("clears rows when selecting columns (mode switch)", () => {+ expect(toggleColumnInSelection({ rows: [1, 2], columns: [] }, 0)).toEqual({+ rows: [],+ columns: [0],+ });+ });++ it("treats prior single-cell selection as a fresh start", () => {+ expect(toggleColumnInSelection({ rows: [3], columns: [1] }, 4)).toEqual({+ rows: [],+ columns: [4],+ });+ });+});++describe("toggleCellInSelection", () => {+ it("selects a cell from empty", () => {+ expect(toggleCellInSelection(empty, 3, 1)).toEqual({+ rows: [3],+ columns: [1],+ });+ });++ it("toggles off when clicking the same cell", () => {+ expect(toggleCellInSelection({ rows: [3], columns: [1] }, 3, 1)).toEqual(+ empty+ );+ });++ it("replaces a different cell selection", () => {+ expect(toggleCellInSelection({ rows: [3], columns: [1] }, 5, 2)).toEqual({+ rows: [5],+ columns: [2],+ });+ });++ it("replaces a row-mode selection with a single cell", () => {+ expect(+ toggleCellInSelection({ rows: [1, 2, 4], columns: [] }, 3, 0)+ ).toEqual({+ rows: [3],+ columns: [0],+ });+ });++ it("toggles off when clicking inside a multi-row × multi-column rectangle", () => {+ // Prior multi-row + multi-column: (1,3) × (0,2) intersection includes (1,0).+ // Clicking that intersection should toggle off (current logic uses+ // membership in BOTH lists).+ expect(+ toggleCellInSelection({ rows: [1, 3], columns: [0, 2] }, 1, 0)+ ).toEqual(empty);+ });+});diff --git a/frontend/src/react/components/sql-editor/ResultView/selection-math.ts b/frontend/src/react/components/sql-editor/ResultView/selection-math.tsnew file mode 100644index 0000000000..34d3daa44c--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/selection-math.ts@@ -0,0 +1,50 @@+import { sortBy } from "lodash-es";++export interface SelectionState {+ rows: number[];+ columns: number[];+}++export const isSingleCellSelected = (s: SelectionState): boolean =>+ s.rows.length === 1 && s.columns.length === 1;++export const toggleRowInSelection = (+ prev: SelectionState,+ row: number+): SelectionState => {+ const baseRows = isSingleCellSelected(prev) ? [] : prev.rows;+ return {+ rows: sortBy(+ baseRows.includes(row)+ ? baseRows.filter((r) => r !== row)+ : [...baseRows, row]+ ),+ columns: [],+ };+};++export const toggleColumnInSelection = (+ prev: SelectionState,+ column: number+): SelectionState => {+ const baseCols = isSingleCellSelected(prev) ? [] : prev.columns;+ return {+ rows: [],+ columns: sortBy(+ baseCols.includes(column)+ ? baseCols.filter((c) => c !== column)+ : [...baseCols, column]+ ),+ };+};++export const toggleCellInSelection = (+ prev: SelectionState,+ row: number,+ column: number+): SelectionState => {+ if (prev.rows.includes(row) && prev.columns.includes(column)) {+ return { rows: [], columns: [] };+ }+ return { rows: [row], columns: [column] };+};diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/types.ts b/frontend/src/react/components/sql-editor/ResultView/types.tssimilarity index 100%rename from frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/types.tsrename to frontend/src/react/components/sql-editor/ResultView/types.tsdiff --git a/frontend/src/react/components/sql-editor/ResultView/useTableResize.ts b/frontend/src/react/components/sql-editor/ResultView/useTableResize.tsnew file mode 100644index 0000000000..07d6125c2f--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultView/useTableResize.ts@@ -0,0 +1,180 @@+import { sum } from "lodash-es";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import type { ResultTableColumn, ResultTableRow } from "./types";++export interface TableResizeOptions {+ columns: ResultTableColumn[];+ rows: ResultTableRow[];+ containerWidth: number;+ minWidth: number;+ maxWidth: number;+ /**+ * Plain-text view of cell at (rowIndex 0..2, columnIndex). Used to size+ * the first few sample rows so columns roughly fit their actual content.+ */+ getRowCellContent: (columnIndex: number) => string | undefined;+}++interface DragState {+ colIndex: number;+ startX: number;+ startWidth: number;+}++const HEADER_FONT = "12px ui-sans-serif, system-ui, sans-serif";+const CELL_FONT = "14px ui-monospace, monospace";+// Reserved width inside the header for everything other than the title:+// px-3 padding (24, both sides) + gap-x-1 (4) + sort icon size-3.5 (14) ++// gap-x-1 (4) + binary-format button size-5 (20) + a few px breathing+// room. We assume the worst case (binary button present) so columns+// without one have a small slack at the trailing edge — better than+// short titles being clipped behind the sort icon.+const HEADER_EXTRA = 72;+const CELL_PADDING = 16; // px-2 cell padding × 2++let measureCanvas: HTMLCanvasElement | null = null;+const measureTextWidth = (text: string, font: string): number => {+ if (!measureCanvas) measureCanvas = document.createElement("canvas");+ const ctx = measureCanvas.getContext("2d");+ if (!ctx) return 0;+ ctx.font = font;+ return ctx.measureText(text).width;+};++/**+ * Measures and tracks per-column widths for the virtualized result-table+ * grid. Replaces Vue's `useTableResize` composable. Returns widths inclusive+ * of the leading index column at slot 0.+ */+export function useTableResize({+ columns,+ rows,+ containerWidth,+ minWidth,+ maxWidth,+ getRowCellContent,+}: TableResizeOptions) {+ const computeInitialWidths = useCallback((): number[] => {+ // Index column: enough to fit the largest row number.+ const indexWidth =+ Math.ceil(measureTextWidth(String(rows.length || 1), CELL_FONT)) + 32; // padding + select strip++ // Data columns: max(header text, sample content rows) clamped to [min, max].+ const dataWidths = columns.map((col, idx) => {+ const headerText = String(col.name ?? "");+ const headerWidth =+ Math.ceil(measureTextWidth(headerText, HEADER_FONT)) + HEADER_EXTRA;++ let bestSample = 0;+ const sample = getRowCellContent(idx);+ if (sample !== undefined && sample.length > 0) {+ bestSample =+ Math.ceil(measureTextWidth(sample, CELL_FONT)) + CELL_PADDING;+ }+ const candidate = Math.max(headerWidth, bestSample);+ if (columns.length === 1) {+ return Math.max(minWidth, Math.min(containerWidth - 1, candidate));+ }+ return Math.max(minWidth, Math.min(maxWidth, candidate));+ });++ return [indexWidth, ...dataWidths];+ }, [+ columns,+ rows.length,+ containerWidth,+ minWidth,+ maxWidth,+ getRowCellContent,+ ]);++ const [widths, setWidths] = useState<number[]>(() => computeInitialWidths());+ const dragRef = useRef<DragState | null>(null);++ const reset = useCallback(() => {+ setWidths(computeInitialWidths());+ }, [computeInitialWidths]);++ // Recompute when columns change identity OR window/container width changes.+ // We deliberately key on columns.length+col ids, not deep-watch, since the+ // Vue version did the same via `watchDebounced` of column references.+ const columnsKey = useMemo(+ () => `${columns.length}:${columns.map((c) => c.id).join(",")}`,+ [columns]+ );+ useEffect(() => {+ setWidths(computeInitialWidths());+ }, [columnsKey, computeInitialWidths]);++ const onResizeStart = useCallback(+ (colIndex: number, e: React.PointerEvent) => {+ e.preventDefault();+ e.stopPropagation();+ const startWidth = widths[colIndex];+ if (startWidth === undefined) return;+ dragRef.current = {+ colIndex,+ startX: e.clientX,+ startWidth,+ };++ const isLast = colIndex === widths.length - 1;+ const handleMove = (ev: PointerEvent) => {+ const drag = dragRef.current;+ if (!drag) return;+ const offset = ev.clientX - drag.startX;+ let next = drag.startWidth + offset;+ if (widths.length === 1) {+ next = Math.max(minWidth, Math.min(containerWidth - 1, next));+ } else {+ next = Math.max(minWidth, Math.min(maxWidth, next));+ }+ setWidths((prev) => {+ const out = [...prev];+ out[drag.colIndex] = next;+ return out;+ });+ };+ const handleUp = () => {+ dragRef.current = null;+ document.removeEventListener("pointermove", handleMove);+ document.removeEventListener("pointerup", handleUp);+ document.body.classList.remove("cursor-col-resize");+ };+ document.addEventListener("pointermove", handleMove);+ document.addEventListener("pointerup", handleUp);+ document.body.classList.add("cursor-col-resize");+ // satisfy linter for unused var on cleanup path+ void isLast;+ },+ [widths, minWidth, maxWidth, containerWidth]+ );++ const totalWidth = sum(widths);+ const effectiveWidth = Math.max(totalWidth, containerWidth);++ /**+ * Pixel width for the column at this index. The last column absorbs any+ * extra space between totalWidth and containerWidth so the row never has+ * a trailing gap.+ */+ const getColumnWidth = useCallback(+ (index: number): number => {+ const w = widths[index];+ if (w === undefined) return 0;+ const isLast = index === widths.length - 1;+ const extra = Math.max(0, containerWidth - totalWidth);+ return isLast ? w + extra : w;+ },+ [widths, containerWidth, totalWidth]+ );++ return {+ widths,+ totalWidth,+ effectiveWidth,+ onResizeStart,+ reset,+ getColumnWidth,+ };+}diff --git a/frontend/src/react/components/sql-editor/ResultViewPage.tsx b/frontend/src/react/components/sql-editor/ResultViewPage.tsxnew file mode 100644index 0000000000..3df351e959--- /dev/null+++ b/frontend/src/react/components/sql-editor/ResultViewPage.tsx@@ -0,0 +1,12 @@+/**+ * Top-level page shim so `ReactPageMount` can locate the `<ResultView>`+ * root via `mount.ts`'s `pageDirs` lookup (it scans for `<page>.tsx`+ * files at the registered roots, not subdirectories).+ *+ * Vue callers mount this with `<ReactPageMount page="ResultViewPage"+ * :page-props="{ executeParams, database, resultSet, loading, dark }">`+ * to render the React result-view stack inside the still-Vue+ * `DatabaseQueryContext.vue` and `TerminalPanel.vue` shells. Phase 21+ * flips those Vue hosts to React, after which this shim can be deleted.+ */+export { ResultView as ResultViewPage } from "./ResultView/ResultView";diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex e589089f34..1301610cd7 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -341,6 +341,7 @@"previous": "Previous","project": "Project","projects": "Projects",+ "query": "Query","read-only": "Read-only","reason": "Reason","recent": "Recent",@@ -399,6 +400,7 @@"succeed": "Succeed","system": "System","table": "Table",+ "text-wrap": "Text Wrap","title": "Title","to": "To","total": "Total",@@ -788,6 +790,7 @@"selected-n-databases": "{{n}} database(s) selected","successfully-transferred-databases": "Successfully transferred databases","sync-complete-for-instance": "Sync complete for instance '{{0}}'",+ "sync-database": "Sync Database","sync-schema": {"copy-schema": "Copy schema","description": "Bytebase supports synchronizing a schema to one or multiple target databases. (MySQL, PostgreSQL, Oracle, MSSQL, TiDB only)",@@ -857,6 +860,7 @@"extensions": "Extensions","external-tables": "External tables","failed-to-sync-schema": "Failed to sync schema",+ "failed-to-sync-schema-for-database-database-value-name": "Failed to sync schema for database \"{{name}}\".","functions": "Functions","n-databases-had-sync-errors": "{{0}} database(s) had sync errors","packages": "Packages",@@ -879,6 +883,7 @@"start-to-sync-schema": "Start to sync schema","streams": "Streams","successfully-synced-schema": "Successfully synced schema",+ "successfully-synced-schema-for-database-database-value-name": "Successfully synced schema for database \"{{name}}\".","syncing-databases-for-instance": "Syncing databases for {{0}}...","tables": "Tables","tasks": "Tasks",@@ -2041,6 +2046,9 @@"select": "Select classification"}},+ "sensitive-data": {+ "self": "Sensitive Data"+ },"setting": {"label": {"key-placeholder": "Label key...",@@ -2634,14 +2642,19 @@},"show-or-hide-empty-query-results": "Show / hide empty query results"},+ "binary-format": "Binary format",+ "boolean-format": "Boolean format",+ "cancel-selection": "Cancel selection","choose-folder": "Choose or create folder","choose-folder-tips": "You can create a new folder by entering a non-existent path. The folders should be joined with a \"/\".","click-to-sync-now": "Click to sync now","close-sheet": "Close sheet",+ "column-display-format": "Column Display Format","connect-in-admin-mode": "Connect in admin mode","connect-to-a-database": "Connect to database","copy-all-column-names": "Copy all column names","copy-name": "Copy name",+ "copy-selected-results": "Copy selected data by <action></action> or <button></button>","copy-url": "Copy URL","ddl-dml-requires-data-change-plan": "To execute DDL/DML statements in <environment></environment>, please submit a Data Change Plan for approval.","download-as-file": "Download as {{file}}",@@ -2652,9 +2665,11 @@"expire-in": "Expire in {{time}}","expired": "Expired","format": "Format",+ "format-default": "Default","format-sql": "Format SQL","generate-sql": "Generate SQL","grant-type-unmask": "Unmask",+ "hex-format": "Hexadecimal format","hint-tips": {"confirm-to-close-unsaved-sheet": {"content": "Close the sheet and lose any unsaved data?",@@ -2664,9 +2679,12 @@"jit": "Just-In-Time Access","last-synced": "Last synced: <time></time>","link-access": "Link access",+ "loading-data": "Loading Data...","loading-databases": "Loading Databases...","manage-connections": "Manage connections",+ "next-row": "Next Row","no-access-requests": "No access requests",+ "no-data-available": "No data available","no-database-selected": "No database selected","no-history-found": "No history found","no-project": {@@ -2678,6 +2696,7 @@"only-select-allowed": "Only read-only statements are allowed to execute.","open-in-new-tab": "Open in new tab","preview-table-data": "Preview table data",+ "previous-row": "Previous Row","private": "Private","private-desc": "Only you can access this sheet","project-read": "Project read",@@ -2687,6 +2706,7 @@"query-context": {"admin-data-source-is-disallowed-to-query": "Admin data source is disallowed to query."},+ "query-time": "Query time","re-request": "Re-request","redis-command": {"all-nodes": "All nodes",@@ -2703,13 +2723,24 @@},"revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?",+ "rows": {+ "self": "rows"+ },+ "rows-affected": "rows affected",+ "rows-upper-limit": "reached the limit of query results","save-sheet": "Save Sheet","save-sheet-input-placeholder": "Please input a sheet name",+ "scroll-to-bottom": "Scroll to the bottom",+ "scroll-to-top": "Scroll to the top","search-history-by-statement": "Search by statement",+ "search-scope-column-description": "Column with {{type}} type. Enter a value and press Enter to jump to the matching row.",+ "search-scope-row-number-description": "Enter a row number to jump to that row.",+ "search-scope-row-number-title": "Row number","select-a-database-to-start": "Select a database to start","select-encoding": "Select encoding","self": "SQL Editor","show-databases-without-query-permission": "Show databases without query permissions",+ "show-in-editor": "Show in Editor","sync-in-progress": "Sync in progress","tab": {"context-menu": {@@ -2726,13 +2757,18 @@}}},+ "table-empty-placeholder": "Click Run to execute the query.",+ "table-view": "Table view",+ "text-format": "Text format","unmask-warning": "The query result may include unmasked sensitive data.","upload-file": "Upload file","url-copied-to-clipboard": "The URL is copied to your clipboard",+ "vertical-display": "Vertical display","view-database-detail": "View database detail","view-detail": "View detail","view-issue": "View Issue","view-schema-text": "View schema text",+ "visualize-explain": "Visualize Explain","web-socket": {"errors": {"description": "Auto Completion might be limited or disabled.",diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex b4e54be541..6ffaad3fa0 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -336,6 +336,7 @@"previous": "Previous","project": "Proyecto","projects": "Proyectos",+ "query": "Consulta","read-only": "Solo lectura","reason": "Razón","refresh": "Actualizar",@@ -393,6 +394,7 @@"succeed": "Tener éxito","system": "Sistema","table": "Tabla",+ "text-wrap": "Ajuste de texto","title": "Título","to": "Hasta","total": "Total",@@ -781,6 +783,7 @@"selected-n-databases": "{{n}} base(s) de datos seleccionada(s)","successfully-transferred-databases": "Bases de datos transferidas exitosamente","sync-complete-for-instance": "Sincronización completada para la instancia '{{0}}'",+ "sync-database": "Sincronizar base de datos","sync-schema": {"copy-schema": "Copy schema","description": "Bytebase supports synchronizing a schema to one or multiple target databases. (MySQL, PostgreSQL, Oracle, MSSQL, TiDB only)",@@ -850,6 +853,7 @@"extensions": "Extensiones","external-tables": "Tablas externas","failed-to-sync-schema": "Error al sincronizar el esquema",+ "failed-to-sync-schema-for-database-database-value-name": "Error al sincronizar el esquema para la base de datos \"{{name}}\".","functions": "Funciones","n-databases-had-sync-errors": "{{0}} base(s) de datos tuvieron errores de sincronización","packages": "Paquetes",@@ -872,6 +876,7 @@"start-to-sync-schema": "Comenzar a sincronizar el esquema","streams": "Streams","successfully-synced-schema": "Esquema sincronizado exitosamente",+ "successfully-synced-schema-for-database-database-value-name": "Esquema sincronizado correctamente para la base de datos \"{{name}}\".","syncing-databases-for-instance": "Sincronizando bases de datos para {{0}}...","tables": "Tablas","tasks": "Tareas",@@ -2028,6 +2033,9 @@"select": "Seleccionar clasificación"}},+ "sensitive-data": {+ "self": "Datos Sensibles"+ },"setting": {"label": {"key-placeholder": "Clave de etiqueta...",@@ -2620,14 +2628,19 @@},"show-or-hide-empty-query-results": "Mostrar/ocultar resultados de consulta vacíos"},+ "binary-format": "Formato binario",+ "boolean-format": "Formato booleano",+ "cancel-selection": "Cancelar selección","choose-folder": "Seleccionar o crear una carpeta","choose-folder-tips": "Puedes crear una nueva carpeta introduciendo una ruta que no exista. Las carpetas deben unirse con una barra diagonal (\"/\").","click-to-sync-now": "Haga clic para sincronizar ahora","close-sheet": "Cerrar hoja",+ "column-display-format": "Formato de visualización de columna","connect-in-admin-mode": "Conectar en modo administrador","connect-to-a-database": "Conectar a base de datos","copy-all-column-names": "Copiar todos los nombres de las columnas","copy-name": "Copiar nombre",+ "copy-selected-results": "Copiar datos seleccionados por <action></action> o <button></button>","copy-url": "Copiar URL","ddl-dml-requires-data-change-plan": "Para ejecutar sentencias DDL/DML en <environment></environment>, envíe un Plan de Cambio de Datos para su aprobación.","download-as-file": "Descargar como {{file}}",@@ -2638,9 +2651,11 @@"expire-in": "Expire in {{time}}","expired": "Expired","format": "Formato",+ "format-default": "Predeterminado","format-sql": "Format SQL","generate-sql": "Generar SQL","grant-type-unmask": "Unmask",+ "hex-format": "Formato hexadecimal","hint-tips": {"confirm-to-close-unsaved-sheet": {"content": "¿Cerrar la hoja y perder cualquier dato no guardado?",@@ -2650,9 +2665,12 @@"jit": "Just-In-Time Access","last-synced": "Última sincronización: <time></time>","link-access": "Acceso al enlace",+ "loading-data": "Cargando datos...","loading-databases": "Cargando bases de datos...","manage-connections": "Gestionar las conexiones",+ "next-row": "Siguiente fila","no-access-requests": "No access requests",+ "no-data-available": "No hay datos disponibles","no-database-selected": "No se ha seleccionado una base de datos","no-history-found": "No se encontró historial","no-project": {@@ -2664,6 +2682,7 @@"only-select-allowed": "Solo se permiten ejecutar declaraciones de solo lectura.","open-in-new-tab": "Abrir en nueva pestaña","preview-table-data": "Vista previa de datos de la tabla",+ "previous-row": "Fila anterior","private": "Privado","private-desc": "Solo tú puedes acceder a esta hoja","project-read": "Lectura del proyecto",@@ -2673,6 +2692,7 @@"query-context": {"admin-data-source-is-disallowed-to-query": "No se permite realizar consultas a la fuente de datos del administrador."},+ "query-time": "Tiempo de consulta","re-request": "Volver a solicitar","redis-command": {"all-nodes": "Todos los nodos",@@ -2689,13 +2709,24 @@},"revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?",+ "rows": {+ "self": "filas"+ },+ "rows-affected": "filas afectadas",+ "rows-upper-limit": "se ha alcanzado el límite de resultados de la consulta","save-sheet": "Guardar hoja","save-sheet-input-placeholder": "Por favor, ingresa un nombre para la hoja",+ "scroll-to-bottom": "Desplazarse hacia abajo",+ "scroll-to-top": "Desplazarse hacia arriba","search-history-by-statement": "Búsqueda por enunciado",+ "search-scope-column-description": "Columna de tipo {{type}}. Ingrese un valor y presione Enter para saltar a la fila coincidente.",+ "search-scope-row-number-description": "Ingrese un número de fila para saltar a esa fila.",+ "search-scope-row-number-title": "Número de fila","select-a-database-to-start": "Seleccione una base de datos para comenzar","select-encoding": "Seleccionar codificación","self": "Editor de SQL","show-databases-without-query-permission": "Muestra las bases de datos que no tienen permisos de consulta",+ "show-in-editor": "Mostrar en editor","sync-in-progress": "Sincronización en progreso","tab": {"context-menu": {@@ -2712,13 +2743,18 @@}}},+ "table-empty-placeholder": "Haga clic en Ejecutar para ejecutar la consulta.",+ "table-view": "Vista de tabla",+ "text-format": "Formato de texto","unmask-warning": "The query result may include unmasked sensitive data.","upload-file": "Subir archivo","url-copied-to-clipboard": "La URL se copia al portapapeles.",+ "vertical-display": "Pantalla vertical","view-database-detail": "Ver detalle de la base de datos","view-detail": "Ver detalle","view-issue": "View Issue","view-schema-text": "Ver texto del esquema",+ "visualize-explain": "Visualizar explicación","web-socket": {"errors": {"description": "Auto Completion might be limited or disabled.",diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex 0cb5a20533..c48df54e30 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -336,6 +336,7 @@"previous": "Previous","project": "プロジェクト","projects": "プロジェクト",+ "query": "クエリ","read-only": "読み取り専用","reason": "理由","refresh": "リフレッシュ",@@ -393,6 +394,7 @@"succeed": "成功する","system": "システム","table": "テーブル",+ "text-wrap": "テキストの折り返し","title": "タイトル","to": "終了","total": "Total",@@ -781,6 +783,7 @@"selected-n-databases": "{{n}} 個のデータベースが選択されました","successfully-transferred-databases": "データベースの転送に成功しました","sync-complete-for-instance": "インスタンス '{{0}}' の同期が完了しました",+ "sync-database": "データベース同期","sync-schema": {"copy-schema": "Copy schema","description": "Bytebase supports synchronizing a schema to one or multiple target databases. (MySQL, PostgreSQL, Oracle, MSSQL, TiDB only)",@@ -850,6 +853,7 @@"extensions": "拡張機能","external-tables": "外部テーブル","failed-to-sync-schema": "スキーマの同期に失敗しました",+ "failed-to-sync-schema-for-database-database-value-name": "データベース \"{{name}}\" のスキーマの同期に失敗しました。","functions": "関数","n-databases-had-sync-errors": "{{0}} 個のデータベースで同期エラーが発生しました","packages": "パッケージ",@@ -872,6 +876,7 @@"start-to-sync-schema": "スキーマの同期を開始します","streams": "ストリーム","successfully-synced-schema": "スキーマの同期に成功しました",+ "successfully-synced-schema-for-database-database-value-name": "データベース \"{{name}}\" のスキーマを正常に同期しました。","syncing-databases-for-instance": "{{0}} のデータベースを同期中...","tables": "テーブル","tasks": "タスク",@@ -2028,6 +2033,9 @@"select": "分類を選択"}},+ "sensitive-data": {+ "self": "機密データ"+ },"setting": {"label": {"key-placeholder": "タグキー...",@@ -2620,14 +2628,19 @@},"show-or-hide-empty-query-results": "空のクエリ結果の表示/非表示"},+ "binary-format": "バイナリ形式",+ "boolean-format": "ブール形式",+ "cancel-selection": "選択をキャンセル","choose-folder": "フォルダを選択または作成","choose-folder-tips": "存在しないパスを入力することで新しいフォルダを作成できます。フォルダは「/」で結合する必要があります。","click-to-sync-now": "クリックして今すぐ同期します","close-sheet": "ワークシートを閉じる",+ "column-display-format": "列の表示形式","connect-in-admin-mode": "管理者モードで接続する","connect-to-a-database": "データベースに接続","copy-all-column-names": "すべての列名をコピーします","copy-name": "名前をコピーする",+ "copy-selected-results": "選択したデータを<action></action>または<button></button>でコピーします","copy-url": "URLをコピー","ddl-dml-requires-data-change-plan": "<environment></environment> で DDL/DML ステートメントを実行するには、承認のためデータ変更プランを送信してください。","download-as-file": "{{file}} 形式でダウンロード",@@ -2638,9 +2651,11 @@"expire-in": "Expire in {{time}}","expired": "Expired","format": "フォーマット",+ "format-default": "デフォルト","format-sql": "Format SQL","generate-sql": "SQLの生成","grant-type-unmask": "Unmask",+ "hex-format": "16進形式","hint-tips": {"confirm-to-close-unsaved-sheet": {"content": "現在のワークシートを閉じると、保存されていないデータはすべて失われますか?",@@ -2650,9 +2665,12 @@"jit": "Just-In-Time Access","last-synced": "最終同期時間: <time></time>","link-access": "リンクアクセス",+ "loading-data": "データのロード...","loading-databases": "データベース情報をロードしています...","manage-connections": "接続を管理する",+ "next-row": "次の行","no-access-requests": "No access requests",+ "no-data-available": "データがありません","no-database-selected": "データベースが選択されていません","no-history-found": "まだ履歴がありません","no-project": {@@ -2664,6 +2682,7 @@"only-select-allowed": "読み取り専用ステートメントのみが実行を許可されます","open-in-new-tab": "新しいタブで開く","preview-table-data": "テーブルデータのプレビュー",+ "previous-row": "前の行","private": "プライベート","private-desc": "このシートにアクセスできるのはあなただけです","project-read": "プロジェクト内で読み取り可能",@@ -2673,6 +2692,7 @@"query-context": {"admin-data-source-is-disallowed-to-query": "管理者データ ソースはクエリできません。"},+ "query-time": "クエリ時間","re-request": "再申請","redis-command": {"all-nodes": "すべてのノード",@@ -2689,13 +2709,24 @@},"revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?",+ "rows": {+ "self": "行"+ },+ "rows-affected": "行に影響",+ "rows-upper-limit": "クエリ結果の数が上限に達しました","save-sheet": "ワークシートの保存","save-sheet-input-placeholder": "ワークシート名を入力してください",+ "scroll-to-bottom": "末尾へスクロール",+ "scroll-to-top": "先頭へスクロール","search-history-by-statement": "ステートメントで検索",+ "search-scope-column-description": "{{type}}型の列。値を入力してEnterを押すと一致する行にジャンプします。",+ "search-scope-row-number-description": "行番号を入力してその行にジャンプします。",+ "search-scope-row-number-title": "行番号","select-a-database-to-start": "開始するにはデータベースを選択してください","select-encoding": "エンコーディングの選択","self": "SQLエディタ","show-databases-without-query-permission": "クエリ権限のないデータベースを表示します",+ "show-in-editor": "エディタに表示","sync-in-progress": "同期中","tab": {"context-menu": {@@ -2712,13 +2743,18 @@}}},+ "table-empty-placeholder": "「実行」をクリックしてクエリを実行します。",+ "table-view": "テーブルビュー",+ "text-format": "テキスト形式","unmask-warning": "The query result may include unmasked sensitive data.","upload-file": "ファイルをアップロードする","url-copied-to-clipboard": "URLがクリップボードにコピーされました",+ "vertical-display": "縦型表示","view-database-detail": "データベースの詳細を表示する","view-detail": "詳細を見る","view-issue": "View Issue","view-schema-text": "テキストの表示 スキーマ",+ "visualize-explain": "視覚化の説明","web-socket": {"errors": {"description": "Auto Completion might be limited or disabled.",diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex 20cd529fb9..abac5978a8 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -336,6 +336,7 @@"previous": "Previous","project": "Dự án","projects": "Dự án",+ "query": "Truy vấn","read-only": "Chỉ đọc","reason": "Lý do","refresh": "Làm mới",@@ -393,6 +394,7 @@"succeed": "Thành công","system": "Hệ thống","table": "Bảng",+ "text-wrap": "Ngắt dòng văn bản","title": "Tiêu đề","to": "Đến","total": "Total",@@ -781,6 +783,7 @@"selected-n-databases": "Đã chọn {{n}} cơ sở dữ liệu","successfully-transferred-databases": "Chuyển cơ sở dữ liệu thành công","sync-complete-for-instance": "Đồng bộ hoàn tất cho instance '{{0}}'",+ "sync-database": "Đồng bộ cơ sở dữ liệu","sync-schema": {"copy-schema": "Copy schema","description": "Bytebase supports synchronizing a schema to one or multiple target databases. (MySQL, PostgreSQL, Oracle, MSSQL, TiDB only)",@@ -850,6 +853,7 @@"extensions": "Tiện ích mở rộng","external-tables": "Bảng ngoài","failed-to-sync-schema": "Đồng bộ hóa lược đồ thất bại",+ "failed-to-sync-schema-for-database-database-value-name": "Đồng bộ schema thất bại cho cơ sở dữ liệu \"{{name}}\".","functions": "Hàm","n-databases-had-sync-errors": "{{0}} cơ sở dữ liệu gặp lỗi đồng bộ","packages": "Gói",@@ -872,6 +876,7 @@"start-to-sync-schema": "Bắt đầu đồng bộ hóa lược đồ","streams": "Luồng","successfully-synced-schema": "Đồng bộ hóa lược đồ thành công",+ "successfully-synced-schema-for-database-database-value-name": "Đồng bộ schema thành công cho cơ sở dữ liệu \"{{name}}\".","syncing-databases-for-instance": "Đang đồng bộ hóa cơ sở dữ liệu cho {{0}}...","tables": "Bảng","tasks": "Tác vụ",@@ -2028,6 +2033,9 @@"select": "Chọn phân loại"}},+ "sensitive-data": {+ "self": "Dữ liệu nhạy cảm"+ },"setting": {"label": {"key-placeholder": "Khóa nhãn...",@@ -2620,14 +2628,19 @@},"show-or-hide-empty-query-results": "Hiển thị / ẩn kết quả truy vấn trống"},+ "binary-format": "Định dạng nhị phân",+ "boolean-format": "Định dạng boolean",+ "cancel-selection": "Hủy chọn","choose-folder": "Chọn hoặc tạo thư mục","choose-folder-tips": "Bạn có thể tạo một thư mục mới bằng cách nhập một đường dẫn không tồn tại. Các thư mục phải được nối bằng dấu \"/\".","click-to-sync-now": "Nhấp để đồng bộ ngay","close-sheet": "Đóng trang tính",+ "column-display-format": "Định dạng hiển thị cột","connect-in-admin-mode": "Kết nối ở chế độ quản trị","connect-to-a-database": "Kết nối cơ sở dữ liệu","copy-all-column-names": "Sao chép tất cả tên cột","copy-name": "Sao chép tên",+ "copy-selected-results": "Sao chép dữ liệu đã chọn bằng <action></action> hoặc <button></button>","copy-url": "Sao chép URL","ddl-dml-requires-data-change-plan": "Để thực thi câu lệnh DDL/DML trong <environment></environment>, vui lòng gửi Kế hoạch Thay đổi Dữ liệu để được phê duyệt.","download-as-file": "Tải xuống dưới dạng {{file}}",@@ -2638,9 +2651,11 @@"expire-in": "Expire in {{time}}","expired": "Expired","format": "Định dạng",+ "format-default": "Mặc định","format-sql": "Format SQL","generate-sql": "Tạo SQL","grant-type-unmask": "Unmask",+ "hex-format": "Định dạng thập lục phân","hint-tips": {"confirm-to-close-unsaved-sheet": {"content": "Đóng trang tính và mất bất kỳ dữ liệu chưa lưu nào?",@@ -2650,9 +2665,12 @@"jit": "Just-In-Time Access","last-synced": "Đã đồng bộ lần cuối: <time></time>","link-access": "Truy cập liên kết",+ "loading-data": "Đang tải Dữ liệu...","loading-databases": "Đang tải Cơ sở dữ liệu...","manage-connections": "Quản lý kết nối",+ "next-row": "Dòng tiếp theo","no-access-requests": "No access requests",+ "no-data-available": "Không có dữ liệu","no-database-selected": "Chưa chọn cơ sở dữ liệu","no-history-found": "Không tìm thấy lịch sử","no-project": {@@ -2664,6 +2682,7 @@"only-select-allowed": "Chỉ cho phép thực thi câu lệnh chỉ đọc.","open-in-new-tab": "Mở trong tab mới","preview-table-data": "Xem trước dữ liệu bảng",+ "previous-row": "Dòng trước","private": "Riêng tư","private-desc": "Chỉ bạn mới có thể truy cập trang tính này","project-read": "Đọc dự án",@@ -2673,6 +2692,7 @@"query-context": {"admin-data-source-is-disallowed-to-query": "Nguồn dữ liệu quản trị không được phép truy vấn."},+ "query-time": "Thời gian truy vấn","re-request": "Yêu cầu lại","redis-command": {"all-nodes": "Tất cả các nút",@@ -2689,13 +2709,24 @@},"revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?",+ "rows": {+ "self": "dòng"+ },+ "rows-affected": "dòng bị ảnh hưởng",+ "rows-upper-limit": "đã đạt đến giới hạn kết quả truy vấn","save-sheet": "Lưu trang tính","save-sheet-input-placeholder": "Vui lòng nhập tên trang tính",+ "scroll-to-bottom": "Cuộn xuống cuối",+ "scroll-to-top": "Cuộn lên đầu","search-history-by-statement": "Tìm kiếm theo câu lệnh",+ "search-scope-column-description": "Cột kiểu {{type}}. Nhập giá trị và nhấn Enter để chuyển đến dòng khớp.",+ "search-scope-row-number-description": "Nhập số dòng để chuyển đến dòng đó.",+ "search-scope-row-number-title": "Số dòng","select-a-database-to-start": "Chọn một cơ sở dữ liệu để bắt đầu","select-encoding": "Chọn mã hóa","self": "Trình soạn thảo SQL","show-databases-without-query-permission": "Hiển thị cơ sở dữ liệu không có quyền truy vấn",+ "show-in-editor": "Hiển thị trong editor","sync-in-progress": "Đang đồng bộ","tab": {"context-menu": {@@ -2712,13 +2743,18 @@}}},+ "table-empty-placeholder": "Nhấp vào Chạy để thực hiện truy vấn.",+ "table-view": "Chế độ xem bảng",+ "text-format": "Định dạng văn bản","unmask-warning": "The query result may include unmasked sensitive data.","upload-file": "Tải lên tệp","url-copied-to-clipboard": "URL đã được sao chép vào bảng nhớ tạm của bạn",+ "vertical-display": "Hiển thị dọc","view-database-detail": "Xem chi tiết cơ sở dữ liệu","view-detail": "Xem chi tiết","view-issue": "View Issue","view-schema-text": "Xem văn bản lược đồ",+ "visualize-explain": "Trực quan hóa Giải thích","web-socket": {"errors": {"description": "Auto Completion might be limited or disabled.",diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex d39b4c9499..da67664304 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -336,6 +336,7 @@"previous": "上一步","project": "项目","projects": "项目",+ "query": "查询","read-only": "只读","reason": "理由","refresh": "刷新",@@ -393,6 +394,7 @@"succeed": "成功","system": "系统","table": "表",+ "text-wrap": "文本折行","title": "标题","to": "到","total": "Total",@@ -781,6 +783,7 @@"selected-n-databases": "已选择 {{n}} 个数据库","successfully-transferred-databases": "成功转移数据库","sync-complete-for-instance": "实例 '{{0}}' 同步完成",+ "sync-database": "同步数据库","sync-schema": {"copy-schema": "粘贴 Schema 文本","description": "Bytebase 支持将一个指定的 Schema 同步到一个或多个目标数据库。(支持 MySQL, PostgreSQL, Oracle, MSSQL 以及 TiDB)",@@ -850,6 +853,7 @@"extensions": "扩展","external-tables": "外部表","failed-to-sync-schema": "同步 schema 失败",+ "failed-to-sync-schema-for-database-database-value-name": "同步数据库 \"{{name}}\" 的 schema 失败。","functions": "函数","n-databases-had-sync-errors": "{{0}} 个数据库同步出错","packages": "包",@@ -872,6 +876,7 @@"start-to-sync-schema": "开始同步 schema","streams": "流","successfully-synced-schema": "成功同步 schema",+ "successfully-synced-schema-for-database-database-value-name": "成功同步数据库 \"{{name}}\" 的 schema。","syncing-databases-for-instance": "正在同步 {{0}} 的数据库...","tables": "表","tasks": "任务",@@ -2028,6 +2033,9 @@"select": "选择分类"}},+ "sensitive-data": {+ "self": "敏感数据"+ },"setting": {"label": {"key-placeholder": "标签 key...",@@ -2620,14 +2628,19 @@},"show-or-hide-empty-query-results": "显示/隐藏空查询结果"},+ "binary-format": "二进制格式",+ "boolean-format": "布尔格式",+ "cancel-selection": "取消选择","choose-folder": "选择或创建文件夹","choose-folder-tips": "您可以通过输入不存在的路径来创建新文件夹。文件夹之间应以\"/\"连接。","click-to-sync-now": "点击立即同步","close-sheet": "关闭工作表",+ "column-display-format": "列显示格式","connect-in-admin-mode": "以管理员模式连接","connect-to-a-database": "连接数据库","copy-all-column-names": "复制所有列名","copy-name": "复制名称",+ "copy-selected-results": "通过 <action></action> 或 <button></button> 来快速复制选定的数据","copy-url": "复制 URL","ddl-dml-requires-data-change-plan": "如需在 <environment></environment> 中执行 DDL/DML 语句,请创建变更计划以获得审批。","download-as-file": "下载为 {{file}} 格式",@@ -2638,9 +2651,11 @@"expire-in": "{{time}} 后过期","expired": "已过期","format": "格式化",+ "format-default": "默认","format-sql": "格式化 SQL","generate-sql": "生成 SQL","grant-type-unmask": "脱敏豁免",+ "hex-format": "十六进制格式","hint-tips": {"confirm-to-close-unsaved-sheet": {"content": "关闭当前工作表会丢失所有未保存的数据?",@@ -2650,9 +2665,12 @@"jit": "即时访问","last-synced": "上次同步时间:<time></time>","link-access": "链接访问权限",+ "loading-data": "加载数据中...","loading-databases": "加载数据库信息...","manage-connections": "管理连接",+ "next-row": "下一行","no-access-requests": "暂无访问请求",+ "no-data-available": "暂无数据","no-database-selected": "未选择数据库","no-history-found": "暂无历史记录","no-project": {@@ -2664,6 +2682,7 @@"only-select-allowed": "只允许执行只读语句","open-in-new-tab": "在新选项卡中打开","preview-table-data": "预览表数据",+ "previous-row": "上一行","private": "私有","private-desc": "只有您自己可以访问此工作表","project-read": "项目内可读",@@ -2673,6 +2692,7 @@"query-context": {"admin-data-source-is-disallowed-to-query": "禁止查询主数据源。"},+ "query-time": "查询时间","re-request": "重新申请","redis-command": {"all-nodes": "所有节点",@@ -2689,13 +2709,24 @@},"revoke-access": "撤销","revoke-confirm": "确定要撤销此访问授权吗?",+ "rows": {+ "self": "行"+ },+ "rows-affected": "行受影响",+ "rows-upper-limit": "到达查询结果条数上限","save-sheet": "保存工作表","save-sheet-input-placeholder": "请输入工作表名称",+ "scroll-to-bottom": "滚动到底部",+ "scroll-to-top": "滚动到顶部","search-history-by-statement": "搜索 SQL 语句",+ "search-scope-column-description": "{{type}} 类型的列。输入值并按回车跳转到匹配行。",+ "search-scope-row-number-description": "输入行号跳转到指定行。",+ "search-scope-row-number-title": "行号","select-a-database-to-start": "选择数据库以开始","select-encoding": "选择编码","self": "SQL 编辑器","show-databases-without-query-permission": "显示没有查询权限的数据库",+ "show-in-editor": "在编辑器中显示","sync-in-progress": "正在同步","tab": {"context-menu": {@@ -2712,13 +2743,18 @@}}},+ "table-empty-placeholder": "点击 \"运行\" 执行查询",+ "table-view": "表格视图",+ "text-format": "文本格式","unmask-warning": "The query result may include unmasked sensitive data.","upload-file": "上传文件","url-copied-to-clipboard": "URL 已复制到剪贴板",+ "vertical-display": "竖向展示","view-database-detail": "查看数据库详情","view-detail": "查看详情","view-issue": "查看工单","view-schema-text": "查看文本 Schema",+ "visualize-explain": "可视化 Explain","web-socket": {"errors": {"description": "Auto Completion might be limited or disabled.",diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vuedeleted file mode 100644index 051cb4bde6..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/TableCell.vue+++ /dev/null@@ -1,233 +0,0 @@-<!-- eslint-disable vue/no-v-html -->-<template>- <div- class="px-2 py-1 flex items-center"- :class="classes"- @click="handleClick"- @dblclick="showDetail"- ref="cellRef"- >- <div- ref="wrapperRef"- class="font-mono text-start wrap-break-word line-clamp-3"- v-html="html"- ></div>- <div- class="absolute right-1 top-1/2 translate-y-[-45%] flex items-center gap-1"- >- <!-- Format button for binary data -->- <BinaryFormatButton- v-if="hasByteData"- :format="binaryFormat"- @update:format="- (format: BinaryFormat) =>- setBinaryFormat({- colIndex,- rowIndex,- format,- })- "- @click.stop- />-- <!-- Expand button for long content -->- <NButton- v-if="clickable"- size="tiny"- circle- class="shadow bg-white! dark:bg-dark-bg!"- :class="{- 'opacity-90': clickable,- 'hover:opacity-100': clickable,- }"- @click.stop="showDetail"- >- <template #icon>- <ExpandIcon class="w-3 h-3" />- </template>- </NButton>- </div>- </div>-</template>--<script setup lang="ts">-import { useResizeObserver } from "@vueuse/core";-import { ExpandIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { twMerge } from "tailwind-merge";-import { computed, ref } from "vue";-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 {- getHighlightHTMLByRegExp,- getInstanceResource,- type SearchScope,-} from "@/utils";-import { useSQLResultViewContext } from "../context";-import BinaryFormatButton from "./common/BinaryFormatButton.vue";-import {- type BinaryFormat,- useBinaryFormatContext,-} from "./common/binary-format-store";-import { useSelectionContext } from "./common/selection-logic";-import { getPlainValue } from "./common/utils";--const props = defineProps<{- value: RowValue;- rowIndex: number;- colIndex: number;- allowSelect?: boolean;- columnType: string; // Column type from QueryResult- database: Database;- scope?: SearchScope;- keyword: string;-}>();--const { detail } = useSQLResultViewContext();-const { getBinaryFormat, setBinaryFormat } = useBinaryFormatContext();--const {- state: selectionState,- disabled: selectionDisabled,- toggleSelectCell,- toggleSelectRow,-} = useSelectionContext();-const wrapperRef = ref<HTMLDivElement>();-const cellRef = ref<HTMLDivElement>();-const truncated = ref(false);--const allowSelect = computed(() => {- return props.allowSelect && !selectionDisabled.value;-});--// Check if the value is binary data (proto-es oneof pattern)-const hasByteData = computed(() => {- return props.value.kind?.case === "bytesValue";-});--const binaryFormat = computed(() => {- return getBinaryFormat({- rowIndex: props.rowIndex,- colIndex: props.colIndex,- });-});--useResizeObserver(cellRef, () => {- const cell = cellRef.value;- const wrapper = wrapperRef.value;- if (!cell || !wrapper) return;-- // Check if content is truncated vertically (due to line-clamp)- const contentHeight = wrapper.scrollHeight;- const visibleHeight = wrapper.offsetHeight;- const verticalTruncated = contentHeight > visibleHeight + 2; // +2 for minor pixel differences-- // Check if content is truncated horizontally- const contentWidth = wrapper.scrollWidth;- const visibleWidth = cell.offsetWidth;- const horizontalTruncated = contentWidth > visibleWidth + 2;-- truncated.value = verticalTruncated || horizontalTruncated;-});--const clickable = computed(() => {- if (truncated.value) return true;- const eng = getInstanceResource(props.database).engine;- if (eng === Engine.MONGODB || eng === Engine.ELASTICSEARCH) {- // A cheap way to check JSON string without paying the parsing cost.- const maybeJSON = String(props.value).trim();- return (- (maybeJSON.startsWith("{") && maybeJSON.endsWith("}")) ||- (maybeJSON.startsWith("[") && maybeJSON.endsWith("]"))- );- }- return false;-});--const selected = computed(() => {- if (!allowSelect.value) {- return false;- }- if (- selectionState.value.columns.length === 1 &&- selectionState.value.rows.length === 1- ) {- if (- selectionState.value.columns[0] === props.colIndex &&- selectionState.value.rows[0] === props.rowIndex- ) {- return true;- }- } else if (- selectionState.value.columns.includes(props.colIndex) ||- selectionState.value.rows.includes(props.rowIndex)- ) {- return true;- }- return false;-});--const classes = computed(() => {- const classes: string[] = [];- if (allowSelect.value) {- classes.push("cursor-pointer");- classes.push("hover:bg-accent/10 dark:hover:bg-accent/20");- if (selected.value) {- classes.push("bg-accent/20! dark:bg-accent/40!");- }- } else {- classes.push("select-none");- }- return twMerge(classes);-});--const plainValue = computed(() => {- return getPlainValue(props.value, props.columnType, binaryFormat.value);-});--const html = computed(() => {- // Extract the display value- const value = plainValue.value;-- if (value === undefined) {- return `<span class="text-gray-400 italic">UNSET</span>`;- }- if (value === null) {- return `<span class="text-gray-400 italic">NULL</span>`;- }- if (value.length === 0) {- return `<br style="min-width: 1rem; display: inline-flex;" />`;- }-- let kw = props.scope?.value.trim();- if (!kw) {- kw = props.keyword.trim();- }- return getHighlightHTMLByRegExp(value, kw, false /* !caseSensitive */);-});--const handleClick = (e: MouseEvent) => {- if (!allowSelect.value) {- return;- }- const selectedString = window.getSelection()?.toString();- if (selectedString) {- return;- }- // If the user is holding the ctrl/cmd key, select the row.- if (e.ctrlKey || e.metaKey) {- toggleSelectRow(props.rowIndex);- } else {- toggleSelectCell(props.rowIndex, props.colIndex);- }- e.stopPropagation();-};--const showDetail = () => {- detail.value = {- row: props.rowIndex,- col: props.colIndex,- };-};-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/VirtualDataTable.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/VirtualDataTable.vuedeleted file mode 100644index d9af3482ff..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/VirtualDataTable.vue+++ /dev/null@@ -1,458 +0,0 @@-<template>- <div- ref="containerRef"- class="relative w-full flex-1 overflow-auto flex flex-col rounded-sm border dark:border-zinc-500"- >- <div class="inline-block shrink-0">- <table- ref="tableRef"- class="relative border-collapse -mx-px"- v-bind="tableResize.getTableProps()"- >- <thead- class="bg-gray-50 dark:bg-gray-700 sticky top-0 z-1 drop-shadow-xs"- >- <tr>- <!-- header for the index -->- <th- :key="`0-index`"- class="group relative py-2 shrink-0 tracking-wider border-x border-block-border dark:border-zinc-500 w-px whitespace-nowrap"- v-bind="tableResize.getColumnProps(0)"- >- <!-- Use the max index to calculate the cell width -->- <div- :class="[- 'textinfolabel pr-1 opacity-0',- selectionDisabled- ? 'pl-1'- : 'pl-4',- ]"- >{{ rows.length }}</div>- <div- class="absolute w-2 right-0 top-0 bottom-0 cursor-col-resize"- @pointerdown="tableResize.startResizing(0)"- @click.stop.prevent- />- </th>- <!-- header for columns -->- <th- v-for="(header, columnIndex) of columns"- :key="`${columnIndex + 1}-${header.id}`"- class="group relative px-3 py-2 min-w-8 text-left text-xs font-medium text-gray-500 dark:text-gray-300 tracking-wider border-block-border dark:border-zinc-500"- :class="{- 'border-r': columnIndex < (columns.length - 1),- 'cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800':- !selectionDisabled,- 'bg-accent/10! dark:bg-accent/40!':- selectionState.rows.length === 0 &&- selectionState.columns.includes(columnIndex),- }"- v-bind="tableResize.getColumnProps(columnIndex + 1)"- @click="e => handleSelectColumn(e, columnIndex)"- >- <div class="flex items-center overflow-hidden gap-x-1">- <span class="flex flex-row items-center select-none">- <template- v-if="String(header.name).length > 0"- >- {{ header.name }}- </template>- <br v-else class="min-h-4 inline-flex" />- </span>-- <ReactPageMount- v-if="getMaskingReason && getMaskingReason(columnIndex)"- page="MaskingReasonPopover"- :reason="getMaskingReason(columnIndex)!"- :statement="statement"- :database="database.name"- class="shrink-0"- />-- <ColumnSortedIcon- :is-sorted="getColumnSortDirection(columnIndex)"- @click.stop.prevent="handleHeaderClick(columnIndex)"- />-- <!-- Add binary format button if this column has binary data -->- <BinaryFormatButton- v-if="existBinaryValue(columnIndex)"- :format="- getBinaryFormat({- colIndex: columnIndex,- })- "- @update:format="- (format: BinaryFormat) =>- setBinaryFormat({- colIndex: columnIndex,- format,- })- "- @click.stop- />- </div>-- <!-- The drag-to-resize handler -->- <div- class="absolute w-2 right-0 top-0 bottom-0 cursor-col-resize"- @pointerdown="tableResize.startResizing(columnIndex + 1)"- @click.stop.prevent- />- </th>- </tr>- </thead>- </table>- </div>- <NVirtualList- ref="virtualListRef"- :items="rows"- :item-size="ROW_HEIGHT"- :style="{- minWidth: `${tableResize.effectiveWidth.value}px`,- }"- >- <template #default="{ item: row, index: rowIndex }: { item: { key: number; item: QueryRow; }; index: number; }">- <div- :key="rowIndex"- class="flex group"- :data-row-index="rowIndex"- :style="{- height: `${ROW_HEIGHT}px`,- minWidth: `${tableResize.effectiveWidth.value}px`,- }"- >- <!-- the index cell -->- <div- :key="`${rowIndex}-0`"- class="relative flex items-center shrink-0 text-sm dark:text-gray-100 leading-5 whitespace-nowrap break-all border-block-border dark:border-zinc-500 group-even:bg-gray-100/50 dark:group-even:bg-gray-700/50"- :class="{- 'border-r': true,- 'border-b': true,- 'bg-accent/10! dark:bg-accent/40!': activeRowIndex === rowIndex,- 'bg-accent/20! dark:bg-accent/40!': selectionState.columns.length === 0 && selectionState.rows.includes(rowIndex)- }"- :data-col-index="0"- :style="{- height: `${ROW_HEIGHT}px`,- width: `${tableResize.getColumnWidth(0)}px`,- }"- >- <NPerformantEllipsis- :class="[- 'textinfolabel pr-1',- selectionDisabled- ? 'pl-1'- : 'pl-4',- ]"- >- {{ rowIndex + 1 }}- </NPerformantEllipsis>-- <div- v-if="!selectionDisabled"- class="absolute inset-y-0 left-0 w-3 cursor-pointer bg-accent/5 dark:bg-white/10 hover:bg-accent/10 dark:hover:bg-accent/40"- :class="{- 'bg-accent/20! dark:bg-accent/40!':- selectionState.columns.length === 0 &&- selectionState.rows.includes(- rowIndex- ),- }"- @click="e => handleSelectRow(e, rowIndex)"- ></div>- </div>-- <!-- other cells -->- <div- v-for="(cell, columnIndex) of row.item.values"- :key="`${rowIndex}-${columnIndex + 1}`"- class="relative shrink-0 text-sm dark:text-gray-100 leading-5 whitespace-nowrap break-all border-block-border dark:border-zinc-500 group-even:bg-gray-100/50 dark:group-even:bg-gray-700/50"- :class="{- 'border-r': columnIndex < (row.item.values.length - 1),- 'border-b': true,- }"- :data-col-index="columnIndex + 1"- :style="{- height: `${ROW_HEIGHT}px`,- width: `${tableResize.getColumnWidth(columnIndex + 1)}px`,- }"- >- <div- class="h-full flex items-center overflow-hidden"- >- <TableCell- :value="cell"- :keyword="search.query"- :scope="search.scopes.find(scope => scope.id === columns[columnIndex]?.id)"- :row-index="rowIndex"- :col-index="columnIndex"- :allow-select="true"- :column-type="getColumnTypeByIndex(columnIndex)"- :database="database"- :class="{- 'h-full w-full truncate': true,- 'bg-accent/10! dark:bg-accent/40!': activeRowIndex === rowIndex- }"- />- </div>- </div>- </div>- </template>- </NVirtualList>- </div>-</template>--<script lang="ts" setup>-import { useWindowSize, watchDebounced } from "@vueuse/core";-import { head, last } from "lodash-es";-import { NPerformantEllipsis, NVirtualList } from "naive-ui";-import { computed, nextTick, onMounted, onUnmounted, ref } from "vue";-import ReactPageMount from "@/react/ReactPageMount.vue";-import { DEBOUNCE_SEARCH_DELAY } from "@/types";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import type { MaskingReason } from "@/types/proto-es/v1/sql_service_pb";-import { type QueryRow } from "@/types/proto-es/v1/sql_service_pb";-import { type SearchParams } from "@/utils";-import BinaryFormatButton from "./common/BinaryFormatButton.vue";-import {- type BinaryFormat,- getBinaryFormatByColumnType,- useBinaryFormatContext,-} from "./common/binary-format-store";-import ColumnSortedIcon from "./common/ColumnSortedIcon.vue";-import { useSelectionContext } from "./common/selection-logic";-import type {- ResultTableColumn,- ResultTableRow,- SortDirection,- SortState,-} from "./common/types";-import { getPlainValue } from "./common/utils";-import TableCell from "./TableCell.vue";-import useTableColumnWidthLogic from "./useTableResize";--const props = defineProps<{- rows: ResultTableRow[];- columns: ResultTableColumn[];- activeRowIndex: number;- isSensitiveColumn: (index: number) => boolean;- getMaskingReason?: (index: number) => MaskingReason | undefined;- database: Database;- statement?: string;- sortState?: SortState;- search: SearchParams;-}>();--const emit = defineEmits<{- (event: "toggle-sort", columnIndex: number): void;-}>();--const ROW_HEIGHT = 35; // 35px height for every row-const { width: windowWidth } = useWindowSize();--const getColumnSortDirection = (columnIndex: number): SortDirection => {- if (!props.sortState || props.sortState.columnIndex !== columnIndex) {- return false;- }- return props.sortState.direction;-};--const handleHeaderClick = (columnIndex: number) => {- emit("toggle-sort", columnIndex);-};--const {- state: selectionState,- disabled: selectionDisabled,- toggleSelectColumn,- toggleSelectRow,- deselect,-} = useSelectionContext();-const containerRef = ref<HTMLDivElement>();-const tableRef = ref<HTMLTableElement>();-const virtualListRef = ref<InstanceType<typeof NVirtualList>>();--// Get row cell content for column width calculation-const getRowCellContent = (columnIndex: number): string | undefined => {- // check at most 3 rows- for (let i = 0; i < Math.min(3, props.rows.length); i++) {- const firstRow = props.rows[i];- if (!firstRow) {- continue;- }- const cell = firstRow.item.values[columnIndex];- if (!cell) {- continue;- }- const columnType = props.columns[columnIndex]?.columnType ?? "";- const plainValue = getPlainValue(cell, columnType, "DEFAULT");- if (plainValue) {- return plainValue;- }- }- return undefined;-};--const hasRowSelect = computed(() => {- return (- selectionState.value.columns.length === 0 &&- selectionState.value.rows.length > 0- );-});--const handleSelectRow = (e: MouseEvent, index: number) => {- e.stopPropagation();-- if ((e.metaKey || e.ctrlKey) && hasRowSelect.value) {- const firstRowIndex = head(selectionState.value.rows);- const lastRowIndex = last(selectionState.value.rows);- if (lastRowIndex !== undefined && index > lastRowIndex) {- for (let i = lastRowIndex + 1; i <= index; i++) {- toggleSelectRow(i);- }- } else if (firstRowIndex !== undefined && index < firstRowIndex) {- deselect();- for (let i = index; i <= firstRowIndex; i++) {- toggleSelectRow(i);- }- }- return;- }-- toggleSelectRow(index);-};--const hasColumnSelect = computed(() => {- return (- selectionState.value.columns.length > 0 &&- selectionState.value.rows.length === 0- );-});--const handleSelectColumn = (e: MouseEvent, index: number) => {- e.stopPropagation();-- if ((e.metaKey || e.ctrlKey) && hasColumnSelect.value) {- const firstColumnIndex = head(selectionState.value.columns);- const lastColumnIndex = last(selectionState.value.columns);- if (lastColumnIndex !== undefined && index > lastColumnIndex) {- for (let i = lastColumnIndex + 1; i <= index; i++) {- toggleSelectColumn(i);- }- } else if (firstColumnIndex !== undefined && index < firstColumnIndex) {- deselect();- for (let i = index; i <= firstColumnIndex; i++) {- toggleSelectColumn(i);- }- }- return;- }-- toggleSelectColumn(index);-};--const tableResize = useTableColumnWidthLogic({- tableRef,- containerRef,- minWidth: 64, // 4rem- maxWidth: 640, // 40rem- getRowCellContent,-});--const { getBinaryFormat, setBinaryFormat } = useBinaryFormatContext();--const getColumnTypeByIndex = (columnIndex: number) => {- return props.columns[columnIndex].columnType;-};--const existBinaryValue = (columnIndex: number) => {- if (!getBinaryFormatByColumnType(getColumnTypeByIndex(columnIndex))) {- return false;- }-- // Check each row in the column for binary data (proto-es oneof pattern)- for (const row of props.rows) {- const cell = row.item.values[columnIndex];- if (!cell) continue;-- if (cell.kind?.case === "bytesValue") {- return true;- }- }-- return false;-};--// Re-initialize column widths when data changes-watchDebounced(- () => props.columns,- () => {- nextTick(() => {- tableResize.reset();- });- },- { immediate: true, deep: true, debounce: DEBOUNCE_SEARCH_DELAY }-);--watchDebounced(- () => windowWidth.value,- () => {- nextTick(() => {- tableResize.reset();- });- },- { debounce: DEBOUNCE_SEARCH_DELAY }-);--// Handle horizontal scrolling for both:-// 1. Shift+wheel for mouse users-// 2. Native horizontal swipe (deltaX) for trackpad users-// Use capture phase to intercept before NVirtualList handles it-const handleWheel = (event: WheelEvent) => {- const container = containerRef.value;- if (!container) return;-- const hasHorizontalOverflow = container.scrollWidth > container.clientWidth;- if (!hasHorizontalOverflow) return;-- // Handle shift+wheel (mouse with vertical scroll wheel)- if (event.shiftKey) {- event.preventDefault();- event.stopPropagation();- container.scrollLeft += event.deltaY || event.deltaX;- return;- }-- // Handle trackpad horizontal swipe (deltaX is dominant)- // When |deltaX| > |deltaY|, it's a horizontal swipe gesture- if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) {- event.preventDefault();- event.stopPropagation();- container.scrollLeft += event.deltaX;- }-};--onMounted(() => {- // Use capture phase to intercept before NVirtualList- containerRef.value?.addEventListener("wheel", handleWheel, {- passive: false,- capture: true,- });-});--onUnmounted(() => {- containerRef.value?.removeEventListener("wheel", handleWheel, {- capture: true,- });-});--defineExpose({- scrollTo: (index: number) =>- virtualListRef.value?.scrollTo({- top: Math.max(0, (index - 1) * ROW_HEIGHT),- debounce: true,- behavior: "smooth",- }),-});-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/BinaryFormatButton.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/BinaryFormatButton.vuedeleted file mode 100644index a0a11b10e7..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/BinaryFormatButton.vue+++ /dev/null@@ -1,72 +0,0 @@-<!-- Button to change binary data format for an entire column -->-<template>- <div>- <NPopover trigger="click" placement="bottom">- <template #trigger>- <NButton- size="tiny"- circle- class="ml-1 dark:bg-dark-bg!"- @click.stop- :type="hasColumnOverride ? 'primary' : 'default'"- :secondary="hasColumnOverride"- >- <template #icon>- <CodeIcon class="w-3 h-3" />- </template>- </NButton>- </template>- <template #default>- <div class="p-2 w-52">- <div class="text-xs font-semibold mb-2">- {{ $t("sql-editor.column-display-format") }}- </div>- <NRadioGroup- :value="currentColumnFormat"- class="flex flex-col gap-2"- @update:value="emit('update:format', $event as BinaryFormat)"- >- <NRadio value="DEFAULT">- {{ $t("sql-editor.format-default") }}- </NRadio>- <NRadio value="BINARY">- {{ $t("sql-editor.binary-format") }}- </NRadio>- <NRadio value="HEX">- {{ $t("sql-editor.hex-format") }}- </NRadio>- <NRadio value="TEXT">- {{ $t("sql-editor.text-format") }}- </NRadio>- <NRadio value="BOOLEAN">- {{ $t("sql-editor.boolean-format") }}- </NRadio>- </NRadioGroup>- </div>- </template>- </NPopover>- </div>-</template>--<script setup lang="ts">-import { CodeIcon } from "lucide-vue-next";-import { NButton, NPopover, NRadio, NRadioGroup } from "naive-ui";-import { computed } from "vue";-import { type BinaryFormat } from "../common/binary-format-store";--const emit = defineEmits<{- (e: "update:format", format: BinaryFormat): void;-}>();--const props = defineProps<{- format: BinaryFormat | undefined;-}>();--const currentColumnFormat = computed(() => {- return props.format || "DEFAULT";-});--const hasColumnOverride = computed(() => {- return currentColumnFormat.value !== "DEFAULT";-});-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/ColumnSortedIcon.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/ColumnSortedIcon.vuedeleted file mode 100644index e504d59c20..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/ColumnSortedIcon.vue+++ /dev/null@@ -1,19 +0,0 @@-<template>- <span class="w-4 h-auto opacity-80 shrink-0">- <ArrowDownWideNarrow- v-if="!isSorted || isSorted === 'desc'"- class="w-full h-auto"- :class="[isSorted ? 'text-accent' : 'text-gray-300']"- />- <ArrowUpWideNarrow v-else class="w-full h-auto text-accent" />- </span>-</template>--<script lang="ts" setup>-import { ArrowDownWideNarrow, ArrowUpWideNarrow } from "lucide-vue-next";-import type { SortDirection } from "../common/types";--defineProps<{- isSorted: SortDirection;-}>();-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/SensitiveDataIcon.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/SensitiveDataIcon.vuedeleted file mode 100644index 96cee766bc..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/SensitiveDataIcon.vue+++ /dev/null@@ -1,41 +0,0 @@-<template>- <NTooltip :animated="false" :delay="250">- <template #trigger>- <EyeOffIcon- class="w-3 h-3 -mb-0.5"- :class="[clickable && 'cursor-pointer']"- v-bind="$attrs"- @click="handleClick"- />- </template>-- <span class="whitespace-nowrap">- {{ $t("sensitive-data.self") }}- </span>- </NTooltip>-</template>--<script lang="ts" setup>-import { EyeOffIcon } from "lucide-vue-next";-import { NTooltip } from "naive-ui";-import { computed } from "vue";-import { useRouter } from "vue-router";-import { WORKSPACE_ROUTE_GLOBAL_MASKING } from "@/router/dashboard/workspaceRoutes";-import { hasWorkspacePermissionV2 } from "@/utils";--const router = useRouter();--const clickable = computed(() => {- return hasWorkspacePermissionV2("bb.policies.update");-});--const handleClick = () => {- if (!clickable.value) {- return;- }- const url = router.resolve({- name: WORKSPACE_ROUTE_GLOBAL_MASKING,- });- window.open(url.href, "_BLANK");-};-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/binary-format-store.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/binary-format-store.tsdeleted file mode 100644index 40c18296c3..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/binary-format-store.ts+++ /dev/null@@ -1,240 +0,0 @@-import type { InjectionKey } from "vue";-import { inject, provide, ref } from "vue";--export type BinaryFormat = "DEFAULT" | "BINARY" | "HEX" | "TEXT" | "BOOLEAN";--interface ColumnKeyParams {- colIndex: number;-}--interface CellKeyParams extends ColumnKeyParams {- rowIndex: number;-}--// Get a unique key for a cell's row/column position-const getCellKey = (params: CellKeyParams): string => {- const { rowIndex } = params;- return `row_${rowIndex}:${getColumnKey(params)}`;-};--// Get a key for a column-const getColumnKey = (params: ColumnKeyParams): string => {- const { colIndex } = params;- return `col_${colIndex}`;-};--interface GetBinaryFormatParams {- rowIndex?: number;- colIndex: number;-}--// Parameter interfaces for the public API functions-interface BinaryFormatParams extends GetBinaryFormatParams {- format: BinaryFormat;-}--export type BinaryFormatContext = {- getBinaryFormat: (params: GetBinaryFormatParams) => BinaryFormat | undefined;- setBinaryFormat: (params: BinaryFormatParams) => void;-};--const KEY = Symbol(- "bb.sql-editor.result-view.binary-format"-) as InjectionKey<BinaryFormatContext>;--export const provideBinaryFormatContext = () => {- const formattedBinaryValues = ref<Map<string, BinaryFormat>>(new Map());-- const getBinaryFormat = (- params: GetBinaryFormatParams- ): BinaryFormat | undefined => {- const { rowIndex, colIndex } = params;- if (rowIndex !== undefined) {- // find format for a specific cell.- const key = getCellKey({- rowIndex,- colIndex,- });- if (formattedBinaryValues.value.has(key)) {- return formattedBinaryValues.value.get(key);- }- }- // fallback to column format.- const key = getColumnKey({- colIndex,- });- return formattedBinaryValues.value.get(key);- };-- const setBinaryFormat = (params: BinaryFormatParams): void => {- const { rowIndex, colIndex, format } = params;- const key =- rowIndex !== undefined- ? getCellKey({- rowIndex,- colIndex,- })- : getColumnKey({- colIndex,- });-- // If setting to DEFAULT, delete the key so it falls through to column/auto-detect- if (format === "DEFAULT") {- formattedBinaryValues.value.delete(key);- } else {- formattedBinaryValues.value.set(key, format);- }- };-- const context: BinaryFormatContext = {- getBinaryFormat,- setBinaryFormat,- };-- provide(KEY, context);- return context;-};--export const useBinaryFormatContext = () => {- return inject(KEY)!;-};--// Detect the best format for binary data based on content-export const detectBinaryFormat = (params: {- bytesValue: Uint8Array | undefined;- columnType: string;-}): BinaryFormat => {- const { bytesValue, columnType = "" } = params;- if (!bytesValue || bytesValue.length === 0 || columnType === "") {- return "DEFAULT";- }-- const byteArray = Array.from(bytesValue);-- // For single bit values (could be boolean)- if (byteArray.length === 1 && (byteArray[0] === 0 || byteArray[0] === 1)) {- return "BOOLEAN";- }-- // Check if it's readable text- const isReadableText = byteArray.every((byte) => byte >= 32 && byte <= 126);- if (isReadableText) {- return "TEXT";- }-- // Default format based on column type- return getBinaryFormatByColumnType(columnType) ?? "DEFAULT";-};--export const formatBinaryValue = ({- bytesValue,- format,-}: {- bytesValue: Uint8Array | undefined;- format: BinaryFormat;-}): string => {- if (!bytesValue || bytesValue.length === 0) {- return "";- }-- const byteArray = Array.from(bytesValue);- const binaryValue = byteArray- .map((byte) => byte.toString(2).padStart(8, "0"))- .join("");-- switch (format) {- case "BINARY":- return binaryValue;- case "TEXT":- try {- return new TextDecoder().decode(new Uint8Array(byteArray));- } catch {- // Fallback to BINARY if text decoding fails- return binaryValue;- }- case "HEX":- return (- "0x" +- byteArray- .map((byte) => byte.toString(16).toUpperCase().padStart(2, "0"))- .join("")- );- case "BOOLEAN":- if (- byteArray.length === 1 &&- (byteArray[0] === 0 || byteArray[0] === 1)- ) {- return byteArray[0] === 1 ? "true" : "false";- }- // Fall through to DEFAULT- default:- return binaryValue;- }-};--// Determine the suitable format for a column based on column type and content-export const getBinaryFormatByColumnType = (- rawType: string | undefined-): BinaryFormat | undefined => {- if (!rawType) {- return;- }- // Get column type name from direct columnTypeNames prop- const columnType = rawType.toLowerCase();- if (!columnType) {- return;- }-- // Detect BIT column types (bit, varbit, bit varying) - for binary format display- const isBitColumn =- // Generic bit types- columnType === "bit" ||- columnType.startsWith("bit(") ||- (columnType.includes("bit") && !columnType.includes("binary")) ||- // PostgreSQL bit types- columnType === "varbit" ||- columnType === "bit varying";-- // BIT columns default to binary format- if (isBitColumn) {- return "BINARY";- }-- // Detect BINARY column types (binary, varbinary, bytea, blob, etc) - for hex format display- const isBinaryColumn =- // Generic binary types- columnType === "binary" ||- columnType.includes("binary") ||- // MySQL/MariaDB binary types- columnType.startsWith("binary(") ||- columnType.startsWith("varbinary") ||- columnType.includes("blob") ||- columnType === "longblob" ||- columnType === "mediumblob" ||- columnType === "tinyblob" ||- // PostgreSQL binary type- columnType === "bytea" ||- // SQL Server binary types- columnType === "image" ||- columnType === "varbinary(max)" ||- // Oracle binary types- columnType === "raw" ||- columnType === "long raw" ||- // Spatial types (SQL Server, PostgreSQL/PostGIS, MySQL)- columnType === "geometry" ||- columnType === "geography" ||- columnType === "point" ||- columnType === "linestring" ||- columnType === "polygon" ||- columnType === "multipoint" ||- columnType === "multilinestring" ||- columnType === "multipolygon" ||- columnType === "geometrycollection";-- // BINARY/VARBINARY/BLOB columns default to HEX format- if (isBinaryColumn) {- return "HEX";- }-- return undefined;-};diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/selection-logic.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/selection-logic.tsdeleted file mode 100644index 1ff28bce4e..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/selection-logic.ts+++ /dev/null@@ -1,350 +0,0 @@-import { useClipboard, useEventListener } from "@vueuse/core";-import { sortBy } from "lodash-es";-import {- type ComputedRef,- computed,- type InjectionKey,- inject,- nextTick,- provide,- type Ref,- ref,-} from "vue";-import { useI18n } from "vue-i18n";-import { pushNotification } from "@/store";-import type { RowValue } from "@/types/proto-es/v1/sql_service_pb";-import { extractSQLRowValuePlain, isDescendantOf } from "@/utils";-import {- type BinaryFormatContext,- detectBinaryFormat,- formatBinaryValue,-} from "./binary-format-store";-import type { ResultTableColumn, ResultTableRow } from "./types";--export type SelectionState = {- rows: number[];- columns: number[];-};--export type SelectionContext = {- state: Ref<SelectionState>;- disabled: Ref<boolean>;- toggleSelectRow: (row: number) => void;- toggleSelectColumn: (column: number) => void;- toggleSelectCell: (row: number, column: number) => void;- deselect: () => void;- copySelected: () => void;- copyAll: () => void;-};--export const KEY = Symbol(- "bb.sql-editor.result-view.selection"-) as InjectionKey<SelectionContext>;--export const provideSelectionContext = ({- rows,- columns,- binaryFormatContext,- disallowCopyingData,-}: {- rows: ComputedRef<ResultTableRow[]>;- columns: ComputedRef<ResultTableColumn[]>;- binaryFormatContext: BinaryFormatContext;- disallowCopyingData: ComputedRef<boolean>;-}) => {- const { t } = useI18n();- const { getBinaryFormat } = binaryFormatContext;-- const { copy: copyTextToClipboard, isSupported } = useClipboard({- legacy: true,- });-- const copying = ref(false);- const state = ref<SelectionState>({- rows: [],- columns: [],- });- const disabled = computed(() => {- return disallowCopyingData.value;- });- const checkIsSingleCellSelected = (state: SelectionState) => {- return state.rows.length === 1 && state.columns.length === 1;- };- const isCellSelected = computed(() => checkIsSingleCellSelected(state.value));-- const deselect = () => {- state.value = {- rows: [],- columns: [],- };- };-- const toggleSelectRow = (row: number) => {- if (disabled.value) return;- if (isCellSelected.value) {- deselect();- }- state.value = {- rows: sortBy(- state.value.rows.includes(row)- ? state.value.rows.filter((r) => r !== row)- : [...state.value.rows, row]- ),- columns: [],- };- };-- const toggleSelectColumn = (column: number) => {- if (disabled.value) return;- if (isCellSelected.value) {- deselect();- }- state.value = {- rows: [],- columns: sortBy(- state.value.columns.includes(column)- ? state.value.columns.filter((c) => c !== column)- : [...state.value.columns, column]- ),- };- };-- const toggleSelectCell = (row: number, column: number) => {- if (disabled.value) return;- if (- state.value.rows.includes(row) &&- state.value.columns.includes(column)- ) {- deselect();- return;- }- state.value = {- rows: [row],- columns: [column],- };- };-- // Escape values that contain TSV delimiters (\t, \n) or double quotes- // by wrapping in double quotes (standard TSV/CSV quoting convention).- const escapeTSVValue = (val: string): string => {- if (val.includes("\t") || val.includes("\n") || val.includes('"')) {- return `"${val.replaceAll('"', '""')}"`;- }- return val;- };-- const getFormattedValue = ({- value,- colIndex,- rowIndex,- }: {- value: RowValue;- colIndex: number;- rowIndex: number;- }) => {- // Special handling for binary data (proto-es oneof pattern)- if (value && value.kind?.case === "bytesValue") {- // First check if there's a column format override- const binaryFormat = getBinaryFormat({- colIndex,- rowIndex,- });- if (binaryFormat) {- // Column format overrides take precedence- return formatBinaryValue({- bytesValue: value.kind.value,- format: binaryFormat,- });- }-- const detectedFormat = detectBinaryFormat({- bytesValue: value.kind.value,- columnType: columns.value[colIndex].columnType,- });- return formatBinaryValue({- bytesValue: value.kind.value,- format: detectedFormat,- });- }-- // Fall back to default formatting- return String(extractSQLRowValuePlain(value));- };-- const getValues = (state: SelectionState) => {- if (checkIsSingleCellSelected(state)) {- // single cell selected- const row = rows.value[state.rows[0]];- if (!row) {- return "";- }- const cell = row.item.values[state.columns[0]];- if (!cell) {- return "";- }-- // Get the cell value- return getFormattedValue({- value: cell,- colIndex: state.columns[0],- rowIndex: state.rows[0],- });- }-- if (state.rows.length > 0) {- const columnNames = ["index", ...columns.value.map((c) => c.name)];- // multi-rows selected- const data: string[] = [];- for (const rowIndex of state.rows) {- const queryRow = rows.value[rowIndex].item;- if (!queryRow) {- continue;- }-- const rowStr = queryRow.values- .map((cell, colIdx) => {- return escapeTSVValue(- getFormattedValue({- value: cell,- colIndex: colIdx,- rowIndex,- })- );- })- .join("\t");-- data.push(`${rowIndex}\t${rowStr}`);- }- if (data.length === 0) {- return "";- }- return `${columnNames.join("\t")}\n${data.join("\n")}`;- }-- if (state.columns.length > 0) {- const columnNames = state.columns.map(- (columnIndex) => columns.value[columnIndex]?.name ?? ""- );- // multi-columns selected- const values: RowValue[][] = [];- for (const row of rows.value) {- const cells: RowValue[] = [];- for (const column of state.columns) {- const cell = row.item.values[column];- if (!cell) continue;- cells.push(cell);- }- values.push(cells);- }- if (values.length === 0) {- return "";- }- const value = values- .map((cells, rowIdx) =>- cells- .map((cell, colIdx) => {- return escapeTSVValue(- getFormattedValue({- value: cell,- rowIndex: rowIdx,- colIndex: state.columns[colIdx],- })- );- })- .join("\t")- )- .join("\n");-- return `${columnNames.join("\t")}\n${value}`;- }-- return "";- };-- const copy = (state: SelectionState) => {- if (disabled.value || !isSupported.value || copying.value) {- return;- }- const values = getValues(state);- if (!values) {- return;- }- copying.value = true;- copyTextToClipboard(values)- .then(() => {- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.copied"),- });- })- .catch((err: unknown) => {- const errors = [t("common.failed")];- if (err instanceof Error) {- errors.push(err.message);- }- pushNotification({- module: "bytebase",- style: "WARN",- title: errors.join(": "),- });- })- .finally(() => {- nextTick(() => {- copying.value = false;- });- });- };-- const copyAll = () => {- copy({- rows: rows.value.map((_, i) => i),- columns: [],- });- };-- const copySelected = () => {- copy(state.value);- };-- useEventListener("click", (e) => {- if (copying.value) return;- if (isDescendantOf(e.target as Element, ".result-scroll-buttons")) {- return;- }- deselect();- });-- useEventListener("keydown", (e) => {- if (disabled.value) return;- if (state.value.columns.length === 0 && state.value.rows.length === 0)- return;- // Deselect all when escape is pressed.- if (e.key === "Escape") {- deselect();- }- // Copy when Cmd/Ctrl + C is pressed.- if ((e.key === "c" || e.key === "C") && (e.metaKey || e.ctrlKey)) {- e.preventDefault();- e.stopImmediatePropagation();- copySelected();- }- });-- const context: SelectionContext = {- state,- disabled,- toggleSelectRow,- toggleSelectColumn,- toggleSelectCell,- deselect,- copySelected,- copyAll,- };- provide(KEY, context);- return context;-};--export const useSelectionContext = () => {- return inject(KEY)!;-};diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/utils.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/utils.tsdeleted file mode 100644index 694184bd43..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/common/utils.ts+++ /dev/null@@ -1,60 +0,0 @@-import type { RowValue } from "@/types/proto-es/v1/sql_service_pb";-import { extractSQLRowValuePlain } from "@/utils";-import {- type BinaryFormat,- detectBinaryFormat,- formatBinaryValue,-} from "./binary-format-store";--const getFormattedValue = (- rowValue: RowValue,- columnType: string,- binaryFormat: BinaryFormat | undefined-) => {- const bytesValue =- rowValue.kind?.case === "bytesValue" ? rowValue.kind.value : undefined;- if (!bytesValue) {- return rowValue;- }-- // Determine the format to use - column override, cell override, or auto-detected format- let actualFormat = binaryFormat ?? "DEFAULT";-- // If format is DEFAULT or undefined, auto-detect based on column type and content- if (actualFormat === "DEFAULT") {- actualFormat = detectBinaryFormat({- bytesValue,- columnType: columnType,- });- }-- const stringValue = formatBinaryValue({- bytesValue,- format: actualFormat,- });-- // Return proto-es oneof structure with stringValue- return {- ...rowValue,- kind: {- case: "stringValue" as const,- value: stringValue,- },- };-};--export const getPlainValue = (- rowValue: RowValue | undefined,- columnType: string,- binaryFormat: BinaryFormat | undefined-) => {- if (!rowValue) {- return undefined;- }- const formattedValue = getFormattedValue(rowValue, columnType, binaryFormat);- const value = extractSQLRowValuePlain(formattedValue);- if (value === undefined || value === null) {- return value;- }- return String(value);-};diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/index.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/index.tsdeleted file mode 100644index ca1fe87a6a..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import VirtualDataTable from "./VirtualDataTable.vue";--export default VirtualDataTable;diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/useTableResize.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/useTableResize.tsdeleted file mode 100644index 5069dcb094..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DataTable/useTableResize.ts+++ /dev/null@@ -1,313 +0,0 @@-import { useEventListener, usePointer } from "@vueuse/core";-import { sumBy } from "lodash-es";-import type { Ref } from "vue";-import { computed, nextTick, onBeforeUnmount, reactive, watch } from "vue";--export type TableResizeOptions = {- tableRef: Ref<HTMLTableElement | undefined>;- containerRef: Ref<HTMLElement | null | undefined>;- minWidth: number;- maxWidth: number;- // Optional: provide row cell content for minimum width calculation- // Returns the display text for a given column index (0-based, excluding the index column)- getRowCellContent?: (columnIndex: number) => string | undefined;-};--type ColumnProps = {- width: number;-};--type DragState = {- start: number;- index: number;- initialWidth: number;-};--type LocalState = {- columns: ColumnProps[];- drag?: DragState;- isAutoAdjusting: boolean;-};--const useTableResize = (options: TableResizeOptions) => {- const state = reactive<LocalState>({- columns: [],- drag: undefined,- isAutoAdjusting: false,- });- const pointer = usePointer();-- const table = computed(() => options.tableRef.value);-- const containerWidth = computed(() => {- return options.containerRef?.value?.scrollWidth || 0;- });-- const normalizeWidth = (width: number) => {- if (state.columns.length === 1) {- // When there is only one column, display it with full width.- // minus 1px to avoid unexpected horizontal scrollbar.- return containerWidth.value - 1;- }- const { maxWidth, minWidth } = options;- if (width > maxWidth) return maxWidth;- if (width < minWidth) return minWidth;- return width;- };-- const reset = () => {- if (!table.value) return;-- state.drag = undefined;- // Use auto layout to calculate the width of each column.- state.isAutoAdjusting = true;-- nextTick(() => {- if (!table.value) return;-- const thList = Array.from(table.value.querySelectorAll("th"));-- // Font settings for measuring cell text width- // Cell font: text-sm (14px) monospace as defined in TableCell.vue- const cellFont = "14px ui-monospace, monospace";- // Cell padding: px-1 = 0.25rem * 2 = 8px- const cellPadding = 8;-- const baseWidths = thList.map((th, index) => {- // Get header content width from the first child element (the content div)- // This includes text + icons and avoids inflation from auto-layout- const content = th.firstElementChild as HTMLElement | null;- const thStyle = getComputedStyle(th);- const paddingLeft = parseFloat(thStyle.paddingLeft) || 0;- const paddingRight = parseFloat(thStyle.paddingRight) || 0;- const borderLeft = parseFloat(thStyle.borderLeftWidth) || 0;- const borderRight = parseFloat(thStyle.borderRightWidth) || 0;-- // For the first column (index column), use scrollWidth to get exact content width- if (index === 0) {- if (content) {- const contentStyle = getComputedStyle(content);- const marginLeft = parseFloat(contentStyle.marginLeft) || 0;- const marginRight = parseFloat(contentStyle.marginRight) || 0;- return (- content.scrollWidth +- borderLeft +- borderRight +- marginLeft +- marginRight- );- }- }-- // For data columns, measure header content scrollWidth (includes text + icons)- let headerWidth = options.minWidth;- if (content) {- headerWidth =- content.scrollWidth +- paddingLeft +- paddingRight +- borderLeft +- borderRight;- }-- // Also consider first row content width if available- // index-1 because the first column (index 0) is the row index column- if (options.getRowCellContent && index > 0) {- const cellContent = options.getRowCellContent(index - 1);- // Only use cell content if it's non-empty- if (- cellContent !== undefined &&- cellContent !== null &&- cellContent.length > 0- ) {- const textWidth = measureTextWidth(String(cellContent), cellFont);- const cellWidth = textWidth + cellPadding;- // Use the larger of header width and cell content width- headerWidth = Math.max(headerWidth, cellWidth);- }- }-- // Apply min/max constraints- return Math.min(- options.maxWidth,- Math.max(options.minWidth, headerWidth)- );- });-- state.columns = baseWidths.map((width) => ({ width }));- // After calculating the width, use fixed layout to keep the width stable.- state.isAutoAdjusting = false;- });- };-- // Record the initial state of dragging.- const startResizing = (index: number) => {- // Use actual DOM width as the initial width to ensure accuracy- const th = table.value?.querySelectorAll("th")[index];- const actualWidth =- th?.getBoundingClientRect().width ?? state.columns[index].width;-- state.drag = {- start: pointer.x.value,- index,- initialWidth: actualWidth,- };- // Sync state with actual DOM width, but for the last column,- // exclude the extra space that was added to fill the container- const isLastColumn = index === state.columns.length - 1;- if (isLastColumn) {- const containerW = options.containerRef?.value?.clientWidth || 0;- const total = sumBy(state.columns, (col) => col.width);- const extraWidth = Math.max(0, containerW - total);- // Store actual width minus extra space- state.columns[index].width = actualWidth - extraWidth;- } else {- state.columns[index].width = actualWidth;- }- toggleDragStyle(table, true);- };-- // Watch the drag moving.- watch(pointer.x, () => {- const { drag } = state;- if (!drag) return;- const { start, index, initialWidth } = drag;-- // Calculate the expectedWidth according to the pointer's position.- const offset = pointer.x.value - start;- const expectedWidth = initialWidth + offset;- state.columns[index].width = normalizeWidth(expectedWidth);-- if (index === state.columns.length - 1) {- // When resizing the last column, Keep the horizontal scroll at the end of the container.- scrollMaxX(options.containerRef.value);- }- });-- // Reset dragging state when mouse button released.- useEventListener("pointerup", () => {- if (state.drag) {- state.drag = undefined;- toggleDragStyle(table, false);- }- });-- const getColumnProps = (index: number) => {- const column = state.columns[index];- if (!column) return {};- // For the first column (index column), use "1px" during auto-adjusting to shrink to content- const autoWidth = index === 0 ? "1px" : "auto";-- // Calculate actual width including extra space for the last column- let actualWidth = column.width;- if (!state.isAutoAdjusting) {- const containerW = options.containerRef?.value?.clientWidth || 0;- const total = sumBy(state.columns, (col) => col.width);- const extraWidth = Math.max(0, containerW - total);- if (extraWidth > 0 && index === state.columns.length - 1) {- actualWidth = column.width + extraWidth;- }- }-- const widthValue = state.isAutoAdjusting ? autoWidth : `${actualWidth}px`;- return {- style: {- width: widthValue,- minWidth: widthValue,- maxWidth: widthValue,- boxSizing: "border-box" as const,- },- class: state.isAutoAdjusting ? "" : "truncate",- "data-index": index,- };- };-- const getColumnWidth = (index: number): number => {- const column = state.columns[index];- if (!column) return 0;-- // When effectiveWidth > totalWidth, add extra space to the last column- const containerW = options.containerRef?.value?.clientWidth || 0;- const total = sumBy(state.columns, (col) => col.width);- const extraWidth = Math.max(0, containerW - total);-- // Add extra width to the last column- if (extraWidth > 0 && index === state.columns.length - 1) {- return column.width + extraWidth;- }-- return column.width;- };-- const totalWidth = computed(() => {- return sumBy(state.columns, (col) => col.width);- });-- // Effective width is the max of totalWidth and container width- const effectiveWidth = computed(() => {- const containerW = options.containerRef?.value?.clientWidth || 0;- return Math.max(totalWidth.value, containerW);- });-- const getTableProps = () => {- const widthValue = state.isAutoAdjusting- ? "auto"- : `${effectiveWidth.value}px`;- const tableLayout: "auto" | "fixed" = state.isAutoAdjusting- ? "auto"- : "fixed";- return {- style: {- width: widthValue,- tableLayout,- },- };- };-- onBeforeUnmount(() => {- toggleDragStyle(table, false);- });-- return {- reset,- getColumnProps,- getColumnWidth,- getTableProps,- totalWidth,- effectiveWidth,- startResizing,- };-};--export default useTableResize;--const scrollMaxX = (elem: HTMLElement | null | undefined) => {- if (!elem) return;- const max = elem.scrollWidth;- elem.scrollTo(max, elem.scrollTop);-};--const toggleDragStyle = (- table: Ref<HTMLTableElement | undefined>,- on: boolean-) => {- if (on) {- // Prevent text selection while dragging.- table.value?.classList.add("select-none");- // Set the cursor style.- document.body.classList.add("cursor-col-resize");- } else {- table.value?.classList.remove("select-none");- document.body.classList.remove("cursor-col-resize");- }-};--// Measure text width using canvas for accurate calculation-// let measureCanvas: HTMLCanvasElement | null = null;-const measureTextWidth = (text: string, font: string): number => {- const measureCanvas = document.createElement("canvas");- const context = measureCanvas.getContext("2d");- if (!context) return 0;- context.font = font;- return context.measureText(text).width;-};diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/DetailPanel.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/DetailPanel.vuedeleted file mode 100644index 1f240c97cf..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/DetailPanel.vue+++ /dev/null@@ -1,303 +0,0 @@-<template>- <DrawerContent- v-if="detail"- :title="$t('common.detail')"- class="w-[100vw-4rem] min-w-[24rem] max-w-[100vw-4rem] md:w-[33vw]"- >- <div- class="h-full flex flex-col gap-y-2"- :class="dark ? 'text-white' : 'text-main'"- >- <div class="flex items-center justify-between gap-x-4">- <div class="flex items-center gap-x-2">- <NTooltip :delay="500">- <template #trigger>- <NButton- size="tiny"- tag="div"- :disabled="detail.row === 0"- @click="move(-1)"- >- <template #icon>- <ChevronUpIcon class="w-4 h-4" />- </template>- </NButton>- </template>- <template #default>- <div class="whitespace-nowrap">- {{ $t("sql-editor.previous-row") }}- </div>- </template>- </NTooltip>- <NTooltip :delay="500">- <template #trigger>- <NButton- size="tiny"- tag="div"- :disabled="detail.row === totalCount - 1"- @click="move(1)"- >- <template #icon>- <ChevronDownIcon class="w-4 h-4" />- </template>- </NButton>- </template>- <template #default>- <div class="whitespace-nowrap">- {{ $t("sql-editor.next-row") }}- </div>- </template>- </NTooltip>- <div class="text-xs text-control-light flex items-center gap-x-1">- <span>{{ detail.row + 1 }}</span>- <span>/</span>- <span>{{ totalCount }}</span>- <span>{{ $t("sql-editor.rows", totalCount) }}</span>- </div>- </div>-- <div class="flex items-center gap-1">- <NPopover v-if="guessedIsJSON">- <template #trigger>- <NButton- size="small"- style="--n-padding: 0 5px"- :type="format ? 'primary' : 'default'"- :secondary="format"- @click="format = !format"- >- <template #icon>- <BracesIcon class="w-4 h-4" />- </template>- </NButton>- </template>- <template #default>- {{ $t("sql-editor.format") }}- </template>- </NPopover>-- <!-- Binary data format selector -->- <BinaryFormatButton- v-if="isBinaryData"- :format="binaryFormat"- @update:format="- (format: BinaryFormat) =>- setBinaryFormat({- colIndex: detail!.col,- rowIndex: detail!.row,- format,- })- "- @click.stop- />-- <CopyButton- v-if="!disallowCopyingData"- quaternary- size="small"- :text="false"- :content="copyContent"- />- </div>- </div>- <NScrollbar- class="flex-1 overflow-hidden text-sm font-mono border p-2 relative"- :content-class="contentClass"- :x-scrollable="true"- trigger="none"- >- <template v-if="guessedIsJSON && format">- <div- class="absolute right-2 top-2 flex justify-end items-center gap-1"- >- <NPopover>- <template #trigger>- <NButton- size="tiny"- style="--n-padding: 0 4px"- :type="wrap ? 'primary' : 'default'"- :secondary="wrap"- @click="wrap = !wrap"- >- <template #icon>- <WrapTextIcon class="w-3 h-3" />- </template>- </NButton>- </template>- <template #default>- {{ $t("common.text-wrap") }}- </template>- </NPopover>- </div>- <PrettyJSON :content="content ?? ''" />- </template>- <template v-else>- <template v-if="content && content.length > 0">- {{ content }}- </template>- <br v-else style="min-width: 1rem; display: inline-flex" />- </template>- </NScrollbar>- </div>- </DrawerContent>-</template>--<script setup lang="ts">-import { onKeyStroke, useLocalStorage } from "@vueuse/core";-import {- parse as losslessParse,- stringify as losslessStringify,-} from "lossless-json";-import {- BracesIcon,- ChevronDownIcon,- ChevronUpIcon,- WrapTextIcon,-} from "lucide-vue-next";-import { NButton, NPopover, NScrollbar, NTooltip } from "naive-ui";-import { computed } from "vue";-import { CopyButton, DrawerContent } from "@/components/v2";-import {- STORAGE_KEY_SQL_EDITOR_DETAIL_FORMAT,- STORAGE_KEY_SQL_EDITOR_DETAIL_LINE_WRAP,-} from "@/utils";-import { useSQLResultViewContext } from "../context";-import BinaryFormatButton from "../DataTable/common/BinaryFormatButton.vue";-import {- type BinaryFormat,- useBinaryFormatContext,-} from "../DataTable/common/binary-format-store";-import type {- ResultTableColumn,- ResultTableRow,-} from "../DataTable/common/types";-import { getPlainValue } from "../DataTable/common/utils";-import PrettyJSON from "./PrettyJSON.vue";--const props = defineProps<{- rows: ResultTableRow[];- columns: ResultTableColumn[];-}>();--const { dark, detail, disallowCopyingData } = useSQLResultViewContext();-const { getBinaryFormat, setBinaryFormat } = useBinaryFormatContext();--const format = useLocalStorage<boolean>(- STORAGE_KEY_SQL_EDITOR_DETAIL_FORMAT,- false-);-const wrap = useLocalStorage<boolean>(- STORAGE_KEY_SQL_EDITOR_DETAIL_LINE_WRAP,- true-);--// Get the current value being displayed first-const rawValue = computed(() => {- if (!detail.value) {- return;- }-- const { row, col } = detail.value;- return props.rows[row].item.values[col];-});--const columnType = computed(() => {- if (!detail.value) {- return "";- }- return props.columns[detail.value.col].columnType;-});--const binaryFormat = computed(() => {- if (!detail.value) {- return;- }- return getBinaryFormat({- rowIndex: detail.value.row,- colIndex: detail.value.col,- });-});--// Check if the current value is binary data (using bytesValue)-const isBinaryData = computed(() => {- if (!rawValue.value) return false;- return rawValue.value.kind?.case === "bytesValue";-});--const content = computed(() => {- return getPlainValue(rawValue.value, columnType.value, binaryFormat.value);-});--const guessedIsJSON = computed(() => {- if (!content.value || content.value.length === 0) return false;- const maybeJSON = content.value.trim();- return (- (maybeJSON.startsWith("{") && maybeJSON.endsWith("}")) ||- (maybeJSON.startsWith("[") && maybeJSON.endsWith("]"))- );-});--const totalCount = computed(() => {- return props.rows.length;-});--const contentClass = computed(() => {- const classes: string[] = [];-- if (disallowCopyingData.value) {- classes.push("select-none");- }- if (guessedIsJSON.value && format.value && !wrap.value) {- classes.push("whitespace-pre");- } else {- classes.push("whitespace-pre-wrap");- }- return classes.join(" ");-});--const copyContent = computed(() => {- const raw = content.value ?? "";-- // For JSON content, use lossless-json to preserve precision for large integers (> 2^53-1)- // No reviver needed: losslessStringify correctly outputs LosslessNumber as numeric literals- if (guessedIsJSON.value && format.value) {- try {- const obj = losslessParse(raw);- return losslessStringify(obj, null, " ") ?? raw;- } catch {- console.warn(- "[DetailPanel]",- "failed to parse and format (maybe) JSON value"- );- return raw;- }- }-- // For binary data, copy according to the selected format- if (isBinaryData.value) {- return raw;- }-- return raw;-});--const move = (offset: number) => {- if (!detail.value) {- return;- }- const target = detail.value.row + offset;- if (target < 0 || target >= totalCount.value) return;- detail.value.row = target;-};--onKeyStroke("ArrowUp", (e) => {- e.preventDefault();- e.stopPropagation();- move(-1);-});-onKeyStroke("ArrowDown", (e) => {- e.preventDefault();- e.stopPropagation();- move(1);-});-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/PrettyJSON.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/PrettyJSON.vuedeleted file mode 100644index ab41049688..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/PrettyJSON.vue+++ /dev/null@@ -1,56 +0,0 @@-<template>- <!-- eslint-disable-next-line vue/no-v-html -->- <div v-html="state.html" />-</template>--<script setup lang="ts">-import { escape } from "lodash-es";-import { shallowReactive, watch } from "vue";--const props = defineProps<{- content: string;-}>();--const state = shallowReactive({- html: "",- controller: new AbortController(),-});--watch(- () => props.content,- async (content) => {- if (state.controller) {- state.controller.abort();- state.controller = new AbortController();- }- const controller = state.controller;- const finish = (html: string) => {- if (controller.signal.aborted) {- return;- }- state.html = html;- };-- try {- const { prettyPrintJson } = await import("pretty-print-json");- const { parse } = await import("lossless-json");- const { losslessReviver } = await import("@/composables/utils");- await import("./pretty-print-json.css");- // Use lossless-json to preserve precision for large integers (> 2^53-1)- const obj = parse(content, null, losslessReviver);- const html = prettyPrintJson.toHtml(obj, {- quoteKeys: true,- trailingCommas: false,- });- finish(html);- } catch (err) {- console.warn("[PrettyJSON]", err);-- finish(escape(props.content));- }- },- {- immediate: true,- }-);-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/index.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/index.tsdeleted file mode 100644index 4740165dc9..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import DetailPanel from "./DetailPanel.vue";--export default DetailPanel;diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/EmptyView.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/EmptyView.vuedeleted file mode 100644index ff9f796bd7..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/EmptyView.vue+++ /dev/null@@ -1,14 +0,0 @@-<template>- <div- class="text-md font-normal"- :class="[dark ? 'text-matrix-green-hover' : 'text-control-light']"- >- {{ $t("sql-editor.no-data-available") }}- </div>-</template>--<script lang="ts" setup>-defineProps<{- dark: boolean;-}>();-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/ErrorView.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/ErrorView.vuedeleted file mode 100644index f4bbc318f6..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/ErrorView.vue+++ /dev/null@@ -1,146 +0,0 @@-<template>- <div- class="w-full text-md font-normal flex flex-col gap-2 text-sm"- :class="[dark ? 'text-matrix-green-hover' : 'text-control-light']"- >- <BBAttention class="w-full" type="error">- <div class="flex items-center gap-2">- <span class="flex-1">{{ error }}</span>- <NButton- v-if="canShowInEditor"- size="tiny"- quaternary- type="primary"- @click="showInEditor"- >- {{ positionLabel }}- </NButton>- </div>- </BBAttention>- <div v-if="$slots.suffix">- <slot name="suffix" />- </div>- <PostgresError v-if="resultSet" :result-set="resultSet" />- </div>-</template>--<script lang="ts" setup>-import type { IRange } from "monaco-editor";-import { Selection } from "monaco-editor";-import { NButton } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import { BBAttention } from "@/bbkit";-import { positionWithOffset } from "@/components/MonacoEditor/utils";-import type { SQLEditorQueryParams, SQLResultSetV1 } from "@/types";-import { useSQLEditorContext } from "@/views/sql-editor/context";-import { activeSQLEditorRef } from "@/views/sql-editor/EditorPanel/StandardPanel/state";-import PostgresError from "./PostgresError.vue";--const props = defineProps<{- dark: boolean;- error: string | undefined;- executeParams?: SQLEditorQueryParams;- resultSet?: SQLResultSetV1;-}>();--const { t } = useI18n();-const { events: editorEvents } = useSQLEditorContext();--// Get the failing statement from the result-const failingStatement = computed(() => {- const results = props.resultSet?.results ?? [];- const failedResult = results.find((r) => r.error);- return failedResult?.statement?.trim();-});--const canShowInEditor = computed(() => {- return hasErrorPosition.value || !!failingStatement.value;-});--const hasErrorPosition = computed(() => {- const result = props.resultSet?.results?.[0];- if (!result) return false;-- if (result.detailedError.case === "syntaxError") {- const pos = result.detailedError.value.startPosition;- return (pos?.line ?? 0) > 0;- }- return false;-});--const errorPosition = computed(() => {- const result = props.resultSet?.results?.[0];- if (result?.detailedError.case === "syntaxError") {- return result.detailedError.value.startPosition;- }- return undefined;-});--// Find the failing statement in the editor and return its range-const findStatementRange = (): IRange | undefined => {- let statement = failingStatement.value;- if (!statement) return undefined;-- const editor = activeSQLEditorRef.value;- const model = editor?.getModel();- if (!model) return undefined;-- // Backend may add "LIMIT N" to the statement - strip it for matching- statement = statement.replace(/\s+LIMIT\s+\d+\s*;?\s*$/i, "").trim();-- // Try exact match first- let matches = model.findMatches(statement, false, false, false, null, false);- if (matches.length > 0) {- return matches[0].range;- }-- // Try with semicolon if not found- matches = model.findMatches(- statement + ";",- false,- false,- false,- null,- false- );- if (matches.length > 0) {- return matches[0].range;- }-- return undefined;-};--const highlightRange = computed((): IRange | undefined => {- // Priority 1: Exact error position from syntax error- if (hasErrorPosition.value && errorPosition.value) {- const [line, col] = positionWithOffset(- errorPosition.value.line,- errorPosition.value.column,- props.executeParams?.selection- );- return new Selection(line, col, line, col);- }-- // Priority 2: Find the specific failing statement in editor- return findStatementRange();-});--const positionLabel = computed(() => {- if (hasErrorPosition.value && errorPosition.value) {- const [line, col] = positionWithOffset(- errorPosition.value.line,- errorPosition.value.column,- props.executeParams?.selection- );- return `L${line}:C${col}`;- }- return t("sql-editor.show-in-editor");-});--const showInEditor = () => {- if (highlightRange.value) {- editorEvents.emit("set-editor-selection", highlightRange.value as IRange);- }-};-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/PostgresError.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/PostgresError.vuedeleted file mode 100644index a0c06f80d1..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/PostgresError.vue+++ /dev/null@@ -1,41 +0,0 @@-<template>- <div- v-for="(error, i) in postgresErrors"- :key="i"- class="text-sm grid gap-1 pl-8"- style="grid-template-columns: auto 1fr"- >- <template v-if="error.detail">- <div>DETAIL:</div>- <div>{{ error.detail }}</div>- </template>- <template v-if="error.hint">- <div>HINT:</div>- <div>{{ error.hint }}</div>- </template>- <template v-if="error.where">- <div>WHERE:</div>- <div>{{ error.where }}</div>- </template>- </div>-</template>--<script setup lang="ts">-import { computed } from "vue";-import type { SQLResultSetV1 } from "@/types";-import type { QueryResult_PostgresError } from "@/types/proto-es/v1/sql_service_pb";--const props = defineProps<{- resultSet: SQLResultSetV1;-}>();--const postgresErrors = computed(() => {- const errors: QueryResult_PostgresError[] = [];- props.resultSet.results.forEach((result) => {- if (result.detailedError?.case === "postgresError") {- errors.push(result.detailedError.value);- }- });- return errors;-});-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/index.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/index.tsdeleted file mode 100644index 56cde5ad7e..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ErrorView/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import ErrorView from "./ErrorView.vue";--export default ErrorView;diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vuedeleted file mode 100644index fc637f7bdb..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/ResultViewV1.vue+++ /dev/null@@ -1,359 +0,0 @@-<template>- <NConfigProvider- v-bind="naiveUIConfig"- class="relative flex flex-col justify-start items-start pb-1 overflow-y-auto"- :class="dark && 'dark bg-dark-bg'"- >- <template v-if="executeParams && resultSet && !showPlaceholder">- <template v-if="viewMode === 'SINGLE-RESULT'">- <ErrorView- v-if="resultSet.results[0]?.error"- :dark="dark"- :error="resultSet.results[0]?.error"- :execute-params="executeParams"- :result-set="resultSet"- @execute="$emit('execute', $event)"- >- <template #suffix>- <ReactPageMount- v-if="!!permissionDeniedError"- page="RequestQueryButton"- :text="false"- :statement="executeParams.statement"- :permissionDeniedDetail="permissionDeniedError"- />- </template>- </ErrorView>- <SingleResultViewV1- v-else- :dark="dark"- :disallow-copying-data="disallowCopyingData"- :params="executeParams"- :database="database"- :result="resultSet.results[0]"- :show-export="!queryDataPolicy.disableExport"- :maximum-export-count="queryDataPolicy.maximumResultRows"- @export="handleExportBtnClick"- />- </template>- <template v-else-if="viewMode === 'MULTI-RESULT'">- <NTabs- type="line"- size="small"- class="flex-1 flex flex-col overflow-hidden"- style="--n-tab-padding: 4px 12px"- >- <NTabPane- v-for="(result, i) in filteredResults"- :key="i"- :name="tabName(i)"- class="flex-1 flex flex-col overflow-hidden"- >- <template #tab>- <NTooltip>- <template #trigger>- <div class="flex items-center gap-x-2 mb-1">- <span>{{ tabName(i) }}</span>- <Info- v-if="result.error"- class="text-yellow-600 w-4 h-auto"- />- </div>- </template>- {{ result.statement }}- </NTooltip>- </template>- <ErrorView- v-if="result.error"- :dark="dark"- :error="result.error"- :execute-params="executeParams"- :result-set="resultSet"- @execute="$emit('execute', $event)"- >- <template #suffix>- <ReactPageMount- v-if="!!permissionDeniedError"- page="RequestQueryButton"- :text="false"- :statement="result.statement"- :permissionDeniedDetail="permissionDeniedError"- />- </template>- </ErrorView>- <SingleResultViewV1- v-else- :dark="dark"- :disallow-copying-data="disallowCopyingData"- :params="executeParams"- :database="database"- :result="result"- :show-export="false"- :maximum-export-count="queryDataPolicy.maximumResultRows"- @export="handleExportBtnClick"- />- </NTabPane>- <template v-if="!queryDataPolicy.disableExport" #suffix>- <div class="mb-1">- <DataExportButton- size="small"- :disabled="false"- :support-formats="[- ExportFormat.CSV,- ExportFormat.JSON,- ExportFormat.SQL,- ExportFormat.XLSX,- ]"- :view-mode="'DRAWER'"- :support-password="true"- :maximum-export-count="queryDataPolicy.maximumResultRows"- @export="- ($event) =>- handleExportBtnClick({- ...$event,- statement: executeParams.statement,- })- "- >- <template #form>- <NFormItem :label="$t('common.database')">- <DatabaseInfo :database="database" />- </NFormItem>- </template>- </DataExportButton>- </div>- </template>- </NTabs>- </template>- <template v-else-if="viewMode === 'EMPTY'">- <EmptyView :dark="dark" />- </template>- <template v-else-if="viewMode === 'ERROR'">- <ErrorView- :dark="dark"- :error="resultSet.error"- :execute-params="executeParams"- :result-set="resultSet"- @execute="$emit('execute', $event)"- >- <template #suffix>- <ReactPageMount- v-if="!!permissionDeniedError"- page="RequestQueryButton"- :text="false"- :statement="resultSet.results[0]?.statement"- :permissionDeniedDetail="permissionDeniedError"- />- <SyncDatabaseButton- v-else-if="resultSet.error.includes('resource not found')"- :type="'primary'"- :text="true"- :database="database"- />- </template>- </ErrorView>- </template>- </template>-- <div- v-if="showPlaceholder"- class="absolute inset-0 flex flex-col justify-center items-center z-10"- :class="loading && 'bg-white/80 dark:bg-black/80'"- >- <template v-if="loading">- <BBSpin />- {{ $t("sql-editor.loading-data") }}- </template>- <template v-else-if="!resultSet">- {{ $t("sql-editor.table-empty-placeholder") }}- </template>- </div>- </NConfigProvider>-</template>--<script lang="ts" setup>-import { create } from "@bufbuild/protobuf";-import dayjs from "dayjs";-import { Info } from "lucide-vue-next";-import {- darkTheme,- NConfigProvider,- NFormItem,- NTabPane,- NTabs,- NTooltip,-} from "naive-ui";-import { storeToRefs } from "pinia";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import { darkThemeOverrides } from "@/../naive-ui.config";-import { BBSpin } from "@/bbkit";-import SyncDatabaseButton from "@/components/DatabaseDetail/SyncDatabaseButton.vue";-import DatabaseInfo from "@/components/DatabaseInfo.vue";-import type {- DownloadContent,- ExportOption,-} from "@/components/DataExportButton.vue";-import DataExportButton from "@/components/DataExportButton.vue";-import { isDisallowChangeDatabaseError } from "@/composables/useExecuteSQL";-import ReactPageMount from "@/react/ReactPageMount.vue";-import { useSQLEditorStore, useSQLEditorTabStore, useSQLStore } from "@/store";-import { usePolicyV1Store } from "@/store/modules/v1/policy";-import type { SQLEditorQueryParams, SQLResultSetV1 } from "@/types";-import {- ExportFormat,- type PermissionDeniedDetail,-} from "@/types/proto-es/v1/common_pb";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import { ExportRequestSchema } from "@/types/proto-es/v1/sql_service_pb";-import { extractDatabaseResourceName } from "@/utils";-import EmptyView from "./EmptyView.vue";-import ErrorView from "./ErrorView";-import SingleResultViewV1 from "./SingleResultViewV1.vue";--type ViewMode = "SINGLE-RESULT" | "MULTI-RESULT" | "EMPTY" | "ERROR";--const props = withDefaults(- defineProps<{- executeParams: SQLEditorQueryParams;- database: Database;- resultSet?: SQLResultSetV1;- loading?: boolean;- dark?: boolean;- }>(),- {- executeParams: undefined,- resultSet: undefined,- loading: false,- dark: false,- }-);--defineEmits<{- (event: "execute", params: SQLEditorQueryParams): void;-}>();--const { t } = useI18n();-const policyStore = usePolicyV1Store();-const tabStore = useSQLEditorTabStore();-const { queryDataPolicy } = storeToRefs(useSQLEditorStore());--const permissionDeniedError = computed(- (): PermissionDeniedDetail | undefined => {- if (!props.resultSet || isDisallowChangeDatabaseError(props.resultSet)) {- return undefined;- }- for (const result of props.resultSet.results) {- if (result.detailedError.case === "permissionDenied") {- return result.detailedError.value;- }- }- return undefined;- }-);--const viewMode = computed((): ViewMode => {- const { resultSet } = props;- if (!resultSet) {- return "EMPTY";- }- const { results = [], error } = resultSet;- if (error) {- return "ERROR";- }- if (results.length === 0) {- return "EMPTY";- }- if (results.length === 1) {- return "SINGLE-RESULT";- }- return "MULTI-RESULT";-});--const naiveUIConfig = computed(() => {- if (props.dark) {- return { theme: darkTheme, themeOverrides: darkThemeOverrides.value };- }- return {};-});--const showPlaceholder = computed(() => {- if (viewMode.value === "ERROR") return false;- if (!props.resultSet) return true;- if (props.loading) return true;- return false;-});--const tabName = (index: number) => {- return `${t("common.query")} #${index + 1}`;-};--const disallowCopyingData = computed(() => {- if (queryDataPolicy.value.disableCopyData) {- return true;- }- // If the database is provided, use its effective environment.- const environment = props.database.effectiveEnvironment;-- // Check if the environment has a policy that disables copying data.- if (environment) {- if (policyStore.getQueryDataPolicyByParent(environment).disableCopyData) {- return true;- }- }- return false;-});--const filteredResults = computed(() => {- if (!props.resultSet) {- return []; // If resultSet is undefined, return an empty array- }-- // Skip SET commands when displaying results- return props.resultSet.results.filter((result) => {- return !result.statement.trim().toUpperCase().startsWith("SET");- });-});--const handleExportBtnClick = async ({- options,- resolve,- reject,- statement,-}: {- statement: string;- options: ExportOption;- reject: (reason?: unknown) => void;- resolve: (content: DownloadContent[]) => void;-}) => {- const admin = tabStore.currentTab?.mode === "ADMIN";- const limit = options.limit;-- try {- const content = await useSQLStore().exportData(- create(ExportRequestSchema, {- name: props.database.name,- ...(props.executeParams.connection.dataSourceId- ? { dataSourceId: props.executeParams.connection.dataSourceId }- : {}),- format: options.format,- statement,- limit,- admin,- password: options.password,- schema: props.executeParams.connection.schema,- })- );-- resolve([- {- content,- // the download file is always zip file.- filename: `${extractDatabaseResourceName(props.database.name).databaseName}.${dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss")}.zip`,- },- ]);- } catch (e) {- reject(e);- }-};-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/SelectionCopyTooltips.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SelectionCopyTooltips.vuedeleted file mode 100644index 600b784ccf..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/SelectionCopyTooltips.vue+++ /dev/null@@ -1,59 +0,0 @@-<template>- <div- v-if="shouldShow"- class="w-full absolute h-full bg-white dark:bg-dark-bg flex flex-row justify-start items-center text-control dark:text-control-light"- @click.prevent.stop- >- <InfoIcon :size="16" class="mr-2 text-control" />- <i18n-t- keypath="sql-editor.copy-selected-results"- tag="p"- class="text-sm flex flex-row justify-start items-center gap-1"- >- <template #action>- <NButton size="tiny" type="primary" secondary>- <template #icon>- <span v-if="isMac" class="text-base leading-none">⌘</span>- <span- v-else- class="tracking-tighter text-xs transform scale-x-90 leading-none"- >- Ctrl- </span>- </template>- C- </NButton>- </template>- <template #button>- <NButton size="tiny" @click="copySelected" type="primary" secondary>- <template #icon>- <CopyIcon />- </template>- {{ $t("common.copy") }}- </NButton>- </template>- </i18n-t>- <div class="ml-1">- <NButton size="tiny" quaternary @click="deselect">- {{ $t("sql-editor.cancel-selection") }}- </NButton>- </div>- </div>-</template>--<script lang="ts" setup>-import { CopyIcon, InfoIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { computed } from "vue";-import { useSelectionContext } from "./DataTable/common/selection-logic";--const { state: selectionState, copySelected, deselect } = useSelectionContext();--const shouldShow = computed(- () =>- selectionState.value.rows.length > 0 ||- selectionState.value.columns.length > 0-);--const isMac = navigator.platform.match(/mac/i);-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vuedeleted file mode 100644index 1f55b2a2ac..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/SingleResultViewV1.vue+++ /dev/null@@ -1,833 +0,0 @@-<template>- <template v-if="result.messages.length > 0">- <div- v-for="(message, i) in result.messages"- :key="`message-${i}`"- :class="'text-control-light'"- >- <div>{{ `[${message.level}] ${message.content}` }}</div>- </div>- </template>- <template v-if="viewMode === 'RESULT'">- <BBAttention v-if="result.error" class="w-full mb-2" :type="'error'">- <ErrorView :dark="dark" :error="result.error" />- </BBAttention>- <div- class="result-toolbar relative w-full shrink-0 flex flex-row gap-x-4 justify-between items-center mb-2 hide-scrollbar"- >- <div class="flex flex-row justify-start items-center gap-x-2 mr-2 flex-1">- <AdvancedSearch- v-model:params="state.searchParams"- placeholder=""- :scope-options="searchScopeOptions"- :cache-query="false"- @keyup:enter="scrollToNextCandidate"- />- <NTooltip :disabled="!reachQueryLimit">- <template #trigger>- <div class="flex items-center gap-x-1 whitespace-nowrap text-sm text-gray-500">- <InfoIcon v-if="reachQueryLimit" class="w-4 text-yellow-500" />- {{ resultRowsText }}- </div>- </template>- {{ $t("sql-editor.rows-upper-limit") }}- </NTooltip>- </div>- <div class="flex justify-between items-center shrink-0 gap-x-2">- <div v-if="supportsTableViewToggle" class="flex items-center">- <NSwitch v-model:value="noSQLTableView" size="small" />- <span class="ml-1 whitespace-nowrap text-sm text-gray-500">- {{ $t("sql-editor.table-view") }}- </span>- </div>- <div class="flex items-center">- <NSwitch v-model:value="state.vertical" size="small" />- <span class="ml-1 whitespace-nowrap text-sm text-gray-500">- {{ $t("sql-editor.vertical-display") }}- </span>- </div>- <NTooltip v-if="DISMISS_PLACEHOLDER">- <template #trigger>- <NButton- size="small"- style="--n-padding: 0 8px"- @click="DISMISS_PLACEHOLDER = false"- >- <template #icon>- <GraduationCap class="w-4 h-4" />- </template>- </NButton>- </template>- <template #default>- {{ $t("plugin.ai.text2sql") }}- </template>- </NTooltip>- <NButton- v-if="!disallowCopyingData && rows.length > 0"- size="small"- style="--n-padding: 0 8px"- @click="copyAll"- >- <template #icon>- <CopyIcon class="w-4 h-4" />- </template>- {{ $t("common.copy") }}- </NButton>- <template v-if="showExport">- <DataExportButton- size="small"- :disabled="props.result === null || isEmpty(props.result)"- :support-formats="[- ExportFormat.CSV,- ExportFormat.JSON,- ExportFormat.SQL,- ExportFormat.XLSX,- ]"- :view-mode="'DRAWER'"- :support-password="true"- :maximum-export-count="maximumExportCount"- @export="- ($event) =>- $emit('export', {- ...$event,- statement: params.statement,- })- "- >- <template #form>- <NFormItem :label="$t('common.database')">- <DatabaseInfo :database="database" />- </NFormItem>- </template>- </DataExportButton>- </template>- </div>- <SelectionCopyTooltips />- </div>-- <div- class="w-full flex flex-col relative"- :class="dark ? 'h-80 overflow-hidden' : 'flex-1 overflow-y-auto'"- >- <VirtualDataBlock- v-if="state.vertical"- ref="dataTableRef"- :rows="rows"- :columns="columns"- :is-sensitive-column="isSensitiveColumn"- :get-masking-reason="getMaskingReason"- :database="database"- :statement="params.statement"- :active-row-index="activeRowIndex"- :search="state.searchParams"- />- <VirtualDataTable- v-else- ref="dataTableRef"- :rows="rows"- :columns="columns"- :is-sensitive-column="isSensitiveColumn"- :get-masking-reason="getMaskingReason"- :database="database"- :statement="params.statement"- :sort-state="state.sortState"- :active-row-index="activeRowIndex"- :search="state.searchParams"- @toggle-sort="toggleSort"- />-- <div class="absolute bottom-2 right-4 flex items-end gap-x-2">- <div v-if="state.searchCandidateRowIndexs.length > 0" class="flex flex-row gap-x-2 border shadow rounded bg-white dark:bg-gray-800 dark:border-gray-600 py-1 px-2">- <NButton- quaternary- size="small"- :disabled="state.searchCandidateActiveIndex <= 0"- @click="scrollToPreviousCandidate"- >- <template #icon>- <ArrowUpIcon class="x-4" />- </template>- {{ $t("sql-editor.previous-row") }}- </NButton>- <NButton- quaternary- size="small"- :disabled="state.searchCandidateActiveIndex >= (state.searchCandidateRowIndexs.length - 1)"- @click="scrollToNextCandidate"- >- <template #icon>- <ArrowDownIcon class="x-4" />- </template>- {{ $t("sql-editor.next-row") }}- </NButton>- <NButton quaternary size="small" style="--n-padding: 2px" @click="clearSearchCandidate">- <template #icon>- <XIcon class="x-4" />- </template>- </NButton>- </div>-- <div class="flex flex-col gap-y-2 result-scroll-buttons">- <NTooltip>- <template #trigger>- <div class="rounded-full shadow bg-white dark:bg-gray-800">- <NButton- circle- size="medium"- quaternary- @click="() => scrollToRow(0)"- >- <template #icon>- <ArrowUpIcon class="x-4" />- </template>- </NButton>- </div>- </template>- {{ $t("sql-editor.scroll-to-top") }}- </NTooltip>- <NTooltip>- <template #trigger>- <div class="rounded-full shadow bg-white dark:bg-gray-800">- <NButton- circle- size="medium"- quaternary- @click="() => scrollToRow(rows.length - 1)"- >- <template #icon>- <ArrowDownIcon class="x-4" />- </template>- </NButton>- </div>- </template>- {{ $t("sql-editor.scroll-to-bottom") }}- </NTooltip>- </div>- </div>- </div>-- <div- class="w-full flex items-center justify-between text-xs mt-1 gap-x-4 text-control-light"- >- <div class="flex items-center gap-x-2">- <RichDatabaseName :database="database" />- <div class="flex items-center gap-x-1">- <EllipsisText- :line-clamp="1"- >- {{ result.statement }}- </EllipsisText>- <CopyButton :size="'tiny'" :content="result.statement" />- </div>- </div>- <div class="flex shrink-0 items-center gap-x-2">- <NButton- v-if="showVisualizeButton"- text- type="primary"- @click="visualizeExplain"- size="tiny"- >- {{ $t("sql-editor.visualize-explain") }}- </NButton>- <span>{{ $t("sql-editor.query-time") }}: {{ queryTime }}</span>- </div>- </div>- </template>- <template v-else-if="viewMode === 'AFFECTED-ROWS'">- <div- class="text-md font-normal flex items-center gap-x-1"- :class="[dark ? 'text-matrix-green-hover' : 'text-control-light']"- >- <span>{{ extractSQLRowValuePlain(result.rows[0].values[0]) }}</span>- <span>rows affected</span>- </div>- </template>- <template v-else-if="viewMode === 'EMPTY'">- <EmptyView :dark="dark" />- </template>-- <Drawer- v-if="detail"- :show="!!detail"- @close="detail = undefined"- >- <DetailPanel- :columns="columns"- :rows="rows"- />- </Drawer>-</template>--<script lang="ts" setup>-import { create } from "@bufbuild/protobuf";-import { useLocalStorage } from "@vueuse/core";-import { isEmpty } from "lodash-es";-import {- ArrowDownIcon,- ArrowUpIcon,- CopyIcon,- GraduationCap,- InfoIcon,- XIcon,-} from "lucide-vue-next";-import { NButton, NFormItem, NSwitch, NTooltip } from "naive-ui";-import { v4 as uuidv4 } from "uuid";-import { computed, nextTick, reactive, ref, toRef, watch } from "vue";-import { useI18n } from "vue-i18n";-import { BBAttention } from "@/bbkit";-import AdvancedSearch from "@/components/AdvancedSearch";-import type { ScopeOption } from "@/components/AdvancedSearch/types";-import DatabaseInfo from "@/components/DatabaseInfo.vue";-import type {- DownloadContent,- ExportOption,-} from "@/components/DataExportButton.vue";-import DataExportButton from "@/components/DataExportButton.vue";-import EllipsisText from "@/components/EllipsisText.vue";-import { CopyButton, Drawer, RichDatabaseName } from "@/components/v2";-import { useExecuteSQL } from "@/composables/useExecuteSQL";-import {- flattenElasticsearchSearchResult,- flattenNoSQLQueryResult,-} from "@/composables/utils";-import { DISMISS_PLACEHOLDER } from "@/plugins/ai/components/state";-import { useSQLEditorStore, useSQLEditorTabStore } from "@/store";-import type {- SQLEditorDatabaseQueryContext,- SQLEditorQueryParams,-} from "@/types";-import { Engine, ExportFormat } from "@/types/proto-es/v1/common_pb";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import {- QueryOption_MSSQLExplainFormat,- QueryOptionSchema,- type QueryResult,- type RowValue,-} from "@/types/proto-es/v1/sql_service_pb";-import {- compareQueryRowValues,- createExplainToken,- extractSQLRowValuePlain,- getInstanceResource,- isNullOrUndefined,- type SearchParams,-} from "@/utils";-import { STORAGE_KEY_SQL_EDITOR_NOSQL_TABLE_VIEW } from "@/utils/storage-keys";-import {- provideSQLResultViewContext,- type SQLResultViewContext,-} from "./context";-import { provideBinaryFormatContext } from "./DataTable/common/binary-format-store";-import { provideSelectionContext } from "./DataTable/common/selection-logic";-import type {- ResultTableColumn,- ResultTableRow,- SortState,-} from "./DataTable/common/types";-import VirtualDataTable from "./DataTable/VirtualDataTable.vue";-import DetailPanel from "./DetailPanel";-import EmptyView from "./EmptyView.vue";-import ErrorView from "./ErrorView";-import SelectionCopyTooltips from "./SelectionCopyTooltips.vue";-import VirtualDataBlock from "./VirtualDataBlock.vue";--type LocalState = {- vertical: boolean;- sortState: SortState | undefined;- searchParams: SearchParams;- searchCandidateActiveIndex: number;- searchCandidateRowIndexs: number[];-};--type ViewMode = "RESULT" | "EMPTY" | "AFFECTED-ROWS" | "ERROR";--const props = defineProps<{- dark: boolean;- disallowCopyingData: boolean;- params: SQLEditorQueryParams;- database: Database;- result: QueryResult;- showExport: boolean;- maximumExportCount?: number;-}>();--defineEmits<{- (- event: "export",- option: {- resolve: (content: DownloadContent[]) => void;- reject: (reason?: unknown) => void;- options: ExportOption;- statement: string;- }- ): Promise<void>;-}>();--const state = reactive<LocalState>({- vertical: false,- sortState: undefined,- searchParams: {- query: "",- scopes: [],- },- searchCandidateActiveIndex: -1,- searchCandidateRowIndexs: [],-});--const dataTableRef =- ref<InstanceType<typeof VirtualDataTable | typeof VirtualDataBlock>>();--const binaryFormatContext = provideBinaryFormatContext();--const detail: SQLResultViewContext["detail"] = ref(undefined);-provideSQLResultViewContext({- dark: toRef(props, "dark"),- disallowCopyingData: toRef(props, "disallowCopyingData"),- detail,-});--const { t } = useI18n();-const tabStore = useSQLEditorTabStore();-const editorStore = useSQLEditorStore();-const currentTab = computed(() => tabStore.currentTab);-const { runQuery } = useExecuteSQL();--const viewMode = computed((): ViewMode => {- const { result } = props;- if (result.error && rows.value.length === 0) {- return "ERROR";- }- const columnNames = result.columnNames;- if (columnNames?.length === 0) {- return "EMPTY";- }- if (columnNames?.length === 1 && columnNames[0] === "Affected Rows") {- return "AFFECTED-ROWS";- }- return "RESULT";-});--const engine = computed(() => getInstanceResource(props.database).engine);--const noSQLTableView = useLocalStorage(- STORAGE_KEY_SQL_EDITOR_NOSQL_TABLE_VIEW,- true-);--const flattenedESResult = computed(() => {- if (engine.value !== Engine.ELASTICSEARCH) return undefined;- return flattenElasticsearchSearchResult(props.result);-});--const flattenedMongoResult = computed(() => {- if (engine.value !== Engine.MONGODB) return undefined;- return flattenNoSQLQueryResult(props.result);-});--const flattenedNoSQLResult = computed(() => {- if (engine.value === Engine.ELASTICSEARCH) {- return flattenedESResult.value;- }- if (engine.value === Engine.MONGODB) {- return flattenedMongoResult.value;- }- return undefined;-});--const supportsTableViewToggle = computed(- () => flattenedNoSQLResult.value !== undefined-);--const activeResult = computed(() => {- if (supportsTableViewToggle.value && noSQLTableView.value) {- return flattenedNoSQLResult.value!;- }- return props.result;-});--watch(noSQLTableView, () => {- state.sortState = undefined;- state.searchParams = { query: "", scopes: [] };- state.searchCandidateActiveIndex = -1;- state.searchCandidateRowIndexs = [];-});--const columns = computed((): ResultTableColumn[] => {- return activeResult.value.columnNames.map<ResultTableColumn>(- (columnName, index) => {- const columnType = activeResult.value.columnTypeNames[index];- return {- id: columnName,- name: columnName,- columnType,- };- }- );-});--const searchScopeOptions = computed((): ScopeOption[] => {- const options: ScopeOption[] = [- {- id: "row-number",- title: t("sql-editor.search-scope-row-number-title"),- description: t("sql-editor.search-scope-row-number-description"),- },- ];-- for (const column of columns.value) {- options.push({- id: column.id,- title: column.name,- description: t("sql-editor.search-scope-column-description", {- type: column.columnType,- }),- });- }- return options;-});--const activeRowIndex = computed(() => {- return state.searchCandidateRowIndexs[state.searchCandidateActiveIndex] ?? -1;-});--watch(- () => state.searchParams,- (params) => {- const next = getNextCandidateRowIndex(0, params);- const indexs = [];- if (next >= 0) {- indexs.push(next);- const another = getNextCandidateRowIndex(next + 1, params);- if (another >= 0) {- indexs.push(another);- }- }- state.searchCandidateRowIndexs = indexs;- state.searchCandidateActiveIndex = 0;- },- { deep: true }-);--watch(- () => activeRowIndex.value,- () => {- scrollToCurrentCandidate();- }-);--watch(- () => state.vertical,- () => {- scrollToCurrentCandidate();- }-);--const scrollToNextCandidate = () => {- if (- state.searchCandidateActiveIndex >=- state.searchCandidateRowIndexs.length - 1- ) {- return;- }- state.searchCandidateActiveIndex++;- // Append next candidate if reaches the last- if (- state.searchCandidateActiveIndex ===- state.searchCandidateRowIndexs.length - 1- ) {- const currentRowIndex =- state.searchCandidateRowIndexs[state.searchCandidateActiveIndex];- const next = getNextCandidateRowIndex(- currentRowIndex + 1,- state.searchParams- );- if (next >= 0) {- state.searchCandidateRowIndexs.push(next);- }- }-};--const scrollToPreviousCandidate = () => {- if (state.searchCandidateActiveIndex <= 0) {- return;- }- state.searchCandidateActiveIndex--;-};--const scrollToCurrentCandidate = () => {- scrollToRow(activeRowIndex.value);-};--const scrollToRow = (index: number | undefined) => {- if (index === undefined || index < 0) {- return;- }- nextTick(() => {- if (index >= 0) {- dataTableRef.value?.scrollTo(index);- }- });-};--const clearSearchCandidate = () => {- state.searchParams = {- query: "",- scopes: [],- };-};--const cellValueMatches = (cell: RowValue, query: string) => {- const value = extractSQLRowValuePlain(cell);- if (isNullOrUndefined(value)) {- return false;- }- return String(value).toLowerCase().includes(query.toLowerCase());-};--const getNextCandidateRowIndex = (from: number, params: SearchParams) => {- if (params.scopes.length === 0 && !params.query) {- return -1;- }-- for (let i = from; i < rows.value.length; i++) {- const row = rows.value[i];-- let checked = params.scopes.every((scope) => {- if (!scope.value) {- return false;- }- if (scope.id === "row-number") {- return i + 1 === Number.parseInt(scope.value, 10);- }- const columnIndex = columns.value.findIndex(- (column) => column.name === scope.id- );- if (columnIndex < 0) {- return false;- }- const cell = row.item.values[columnIndex];- return cellValueMatches(cell, scope.value);- });- if (!checked) {- continue;- }-- if (params.query) {- checked = row.item.values.some((cell) => {- return cellValueMatches(cell, params.query);- });- }- if (checked) {- return i;- }- }-- return -1;-};--const toggleSort = (columnIndex: number) => {- const currentSort = state.sortState;-- if (!currentSort || currentSort.columnIndex !== columnIndex) {- // New column or no current sort - start with descending- state.sortState = { columnIndex, direction: "desc" };- } else if (currentSort.direction === "desc") {- // Currently descending - switch to ascending- state.sortState = { columnIndex, direction: "asc" };- } else {- // Currently ascending - clear sort- state.sortState = undefined;- }-};--// Apply sorting to filtered rows-const rows = computed((): ResultTableRow[] => {- const sortState = state.sortState;-- if (!sortState || !sortState.direction) {- return activeResult.value.rows.map((item, index) => ({- key: index,- item,- }));- }-- const { columnIndex, direction } = sortState;- const columnType = columns.value[columnIndex]?.columnType ?? "";-- return activeResult.value.rows- .map((item, index) => ({- key: index,- item,- }))- .sort((a, b) => {- const result = compareQueryRowValues(- columnType,- a.item.values[columnIndex],- b.item.values[columnIndex]- );- return direction === "asc" ? result : -result;- });-});--const reachQueryLimit = computed(() => {- return (- currentTab.value?.mode !== "ADMIN" &&- (rows.value.length === editorStore.resultRowsLimit ||- rows.value.length === editorStore.queryDataPolicy.maximumResultRows)- );-});--// Computed property for result rows text to avoid accessing data.length twice-const resultRowsText = computed(() => {- const length = rows.value.length;- return `${length} ${t("sql-editor.rows", length)}`;-});--const isSensitiveColumn = (columnIndex: number): boolean => {- // Column indices don't match when showing flattened NoSQL table view.- if (supportsTableViewToggle.value && noSQLTableView.value) return false;- const maskingReason = props.result.masked?.[columnIndex];- // Check if maskingReason exists and has actual content (not empty object)- return (- maskingReason !== null &&- maskingReason !== undefined &&- maskingReason.semanticTypeId !== undefined &&- maskingReason.semanticTypeId !== ""- );-};--const getMaskingReason = (columnIndex: number) => {- // Column indices don't match when showing flattened NoSQL table view.- if (supportsTableViewToggle.value && noSQLTableView.value) return undefined;- if (!props.result.masked || columnIndex >= props.result.masked.length) {- return undefined;- }- const reason = props.result.masked[columnIndex];- // Return undefined for empty masking reasons- if (!reason || !reason.semanticTypeId) {- return undefined;- }- return reason;-};--const { copyAll } = provideSelectionContext({- columns,- rows,- binaryFormatContext,- disallowCopyingData: computed(() => props.disallowCopyingData),-});--const showVisualizeButton = computed((): boolean => {- return (- (engine.value === Engine.POSTGRES ||- engine.value === Engine.MSSQL ||- engine.value === Engine.SPANNER) &&- props.params.explain- );-});--const visualizeExplain = async () => {- let token: string | undefined;- try {- if (engine.value === Engine.POSTGRES || engine.value === Engine.SPANNER) {- token = getExplainToken(props.result);- } else if (engine.value === Engine.MSSQL) {- token = await getExplainTokenForMSSQL();- }- if (!token) return;-- window.open(`/explain-visualizer.html?token=${token}`, "_blank");- } catch {- // nothing- }-};--const getExplainToken = (result: QueryResult) => {- const { statement } = result;- if (!statement) return;-- const lines = result.rows.map((row) =>- row.values.map((value) => String(extractSQLRowValuePlain(value)))- );- const explain = lines.map((line) => line[0]).join("\n");- if (!explain) return;-- return createExplainToken({- statement,- explain,- engine: engine.value,- });-};--const getExplainTokenForMSSQL = async () => {- const context: SQLEditorDatabaseQueryContext = {- id: uuidv4(),- params: {- ...props.params,- queryOption: create(QueryOptionSchema, {- mssqlExplainFormat:- QueryOption_MSSQLExplainFormat.MSSQL_EXPLAIN_FORMAT_XML,- }),- },- status: "PENDING",- };- await runQuery(props.database, context);-- const result = context.resultSet?.results[0];- if (!result) {- return;- }- return getExplainToken(result);-};--const queryTime = computed(() => {- const { latency } = props.result;- if (!latency) return "-";-- const { seconds, nanos } = latency;- const totalSeconds = Number(seconds) + nanos / 1e9;- if (totalSeconds < 1) {- const totalMS = Math.round(totalSeconds * 1000);- return `${totalMS} ms`;- }- return `${totalSeconds.toFixed(2)} s`;-});-</script>--<style scoped lang="postcss">-.pagination :deep(.n-input) {- --n-padding-left: 6px !important;- --n-padding-right: 6px !important;-}-.pagination :deep(.n-input__input-el) {- text-align: right;-}--.pagesize-select :deep(.n-base-selection) {- --n-padding-single-left: 8px !important;- --n-padding-single-right: 8px !important;-}--.result-toolbar {- scrollbar-width: thin;- scrollbar-color: rgba(0, 0, 0, 0.2) transparent;-}--.result-toolbar::-webkit-scrollbar {- width: 6px;-}--.result-toolbar::-webkit-scrollbar-track {- background: transparent;-}--.result-toolbar::-webkit-scrollbar-thumb {- background-color: rgba(0, 0, 0, 0.2);- border-radius: 3px;-}--.result-toolbar::-webkit-scrollbar-thumb:hover {- background-color: rgba(0, 0, 0, 0.3);-}-</style>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/VirtualDataBlock.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/VirtualDataBlock.vuedeleted file mode 100644index 442b210242..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/VirtualDataBlock.vue+++ /dev/null@@ -1,144 +0,0 @@-<template>- <NVirtualList- ref="virtualListRef"- item-resizable- :items="rows"- :item-size="estimateRowHeight"- >- <template #default="{ item: row, index: rowIndex }: { item: { key: number; item: QueryRow; }; index: number; }">- <div- :key="`row-${rowIndex}`"- class="font-mono mb-2 mx-2"- :style="{- height: `${estimateRowHeight}px`,- }"- >- <p- class="font-bold text-gray-500 dark:text-gray-300 overflow-hidden whitespace-nowrap mb-1"- >- ********************************- {{ rowIndex + 1 }}. row- ********************************- </p>- <div- class="py-2 px-3 bg-gray-50 dark:bg-gray-700 rounded relative"- :class="{- 'border-2 border-accent/20 bg-accent/10!': activeRowIndex === rowIndex- }"- >- <div- class="absolute right-2 top-2 z-50 opacity-70 hover:opacity-100"- >- <CopyButton size="small" :content="() => getContent(rowIndex)" />- </div>- <div- v-for="(column, columnIndex) in columns"- :key="column.id"- class="flex items-start text-gray-500 dark:text-gray-300 text-sm"- >- <div class="min-w-28 text-left flex items-center font-medium pt-1">- <div class="flex items-center gap-x-1">- {{ column.name }}- <ReactPageMount- v-if="getMaskingReason && getMaskingReason(columnIndex)"- page="MaskingReasonPopover"- :reason="getMaskingReason(columnIndex)!"- :statement="statement"- :database="database.name"- class="shrink-0"- />- </div>- :- </div>- <div class="flex-1">- <TableCell- :value="row.item.values[columnIndex]"- :keyword="search.query"- :scope="search.scopes.find(scope => scope.id === columns[columnIndex]?.id)"- :row-index="rowIndex"- :col-index="columnIndex"- :column-type="column.columnType"- :allow-select="true"- :database="database"- />- </div>- </div>- </div>- </div>- </template>- </NVirtualList>-</template>--<script setup lang="ts">-import { NVirtualList } from "naive-ui";-import { computed, ref } from "vue";-import { CopyButton } from "@/components/v2";-import ReactPageMount from "@/react/ReactPageMount.vue";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import type {- MaskingReason,- QueryRow,-} from "@/types/proto-es/v1/sql_service_pb";-import { type SearchParams } from "@/utils";-import { useBinaryFormatContext } from "./DataTable/common/binary-format-store";-import type {- ResultTableColumn,- ResultTableRow,-} from "./DataTable/common/types";-import { getPlainValue } from "./DataTable/common/utils";-import TableCell from "./DataTable/TableCell.vue";--const props = defineProps<{- rows: ResultTableRow[];- columns: ResultTableColumn[];- activeRowIndex: number;- isSensitiveColumn: (index: number) => boolean;- getMaskingReason?: (index: number) => MaskingReason | undefined;- database: Database;- statement?: string;- search: SearchParams;-}>();--const { getBinaryFormat } = useBinaryFormatContext();-const virtualListRef = ref<InstanceType<typeof NVirtualList>>();--// Calculate the height of each row block-const estimateRowHeight = computed(() => {- // Estimate based on number of columns- // Each column is roughly 28px, plus padding and header- const columnCount = props.columns.length;- return 60 + columnCount * 28; // Header + columns-});--const getContent = (rowIndex: number): string => {- const object = props.columns.reduce(- (obj, column, columnIndex) => {- if (!column.name) {- return obj;- }- const binaryFormat = getBinaryFormat({- rowIndex: rowIndex,- colIndex: columnIndex,- });- obj[`${column.name}`] = getPlainValue(- props.rows[rowIndex].item.values[columnIndex],- column.columnType,- binaryFormat- );- return obj;- },- {} as Record<string, unknown>- );-- return JSON.stringify(object, null, 4);-};--defineExpose({- scrollTo: (index: number) =>- virtualListRef.value?.scrollTo({- top: index * estimateRowHeight.value,- debounce: true,- behavior: "smooth",- }),-});-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/context.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/context.tsdeleted file mode 100644index 9f5e860395..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/context.ts+++ /dev/null@@ -1,26 +0,0 @@-import { type InjectionKey, inject, provide, type Ref } from "vue";--export type SQLResultViewContext = {- dark: Ref<boolean>;- disallowCopyingData: Ref<boolean>;- detail: Ref<- | {- row: number; // The row index of selected record.- col: number; // The column index of selected cell.- }- | undefined- >;-};--export const KEY = Symbol(- "bb.sql-editor.result-view"-) as InjectionKey<SQLResultViewContext>;--export const provideSQLResultViewContext = (context: SQLResultViewContext) => {- provide(KEY, context);- return context;-};--export const useSQLResultViewContext = () => {- return inject(KEY)!;-};diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/index.ts b/frontend/src/views/sql-editor/EditorCommon/ResultView/index.tsdeleted file mode 100644index 2a2a3030ba..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import ResultViewV1 from "./ResultViewV1.vue";--export { ResultViewV1 };diff --git a/frontend/src/views/sql-editor/EditorCommon/index.ts b/frontend/src/views/sql-editor/EditorCommon/index.tsindex c139c9bb8e..265d314969 100644--- a/frontend/src/views/sql-editor/EditorCommon/index.ts+++ b/frontend/src/views/sql-editor/EditorCommon/index.ts@@ -1,4 +1,2 @@-export { ResultViewV1 } from "./ResultView";-export * from "./hover-state";export * from "./utils";diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/DatabaseQueryContext.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/DatabaseQueryContext.vueindex b8d3dcc03a..35d6657327 100644--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/DatabaseQueryContext.vue+++ b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/DatabaseQueryContext.vue@@ -26,13 +26,15 @@</NButton></div></template>- <ResultViewV1+ <ReactPageMountv-else- class="w-full h-auto grow"- :execute-params="context.params"- :database="database"- :result-set="context.resultSet"- @execute="execQuery"+ page="ResultViewPage"+ container-class="w-full flex-1 min-h-0"+ :page-props="{+ executeParams: context.params,+ database,+ resultSet: context.resultSet,+ }"/></template>@@ -42,13 +44,13 @@ import { computed, watch } from "vue";import { BBSpin } from "@/bbkit";import { useCurrentTimestamp } from "@/composables/useCurrentTimestamp";import { useExecuteSQL } from "@/composables/useExecuteSQL";+import ReactPageMount from "@/react/ReactPageMount.vue";import { useSQLEditorTabStore } from "@/store";import type {SQLEditorDatabaseQueryContext,SQLEditorQueryParams,} from "@/types";import type { Database } from "@/types/proto-es/v1/database_service_pb";-import { ResultViewV1 } from "../../EditorCommon/";const props = defineProps<{database: Database;diff --git a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vueindex 0359dac794..af5a28f916 100644--- a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue+++ b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue@@ -30,16 +30,19 @@onClearScreen: handleClearScreen,}"/>- <ResultViewV1+ <ReactPageMountv-if="query.params && query.resultSet"- class="p-2"- :execute-params="query.params"- :result-set="query.resultSet"- :database="- databaseStore.getDatabaseByName(query.params.connection.database)- "- :loading="query.status === 'RUNNING'"- :dark="true"+ page="ResultViewPage"+ container-class="p-2 w-full flex-1 min-h-0"+ :page-props="{+ executeParams: query.params,+ resultSet: query.resultSet,+ database: databaseStore.getDatabaseByName(+ query.params.connection.database+ ),+ loading: query.status === 'RUNNING',+ dark: true,+ }"/><div@@ -83,7 +86,6 @@ import {useWebTerminalStore,} from "@/store";import type { SQLEditorQueryParams, WebTerminalQueryItemV1 } from "@/types";-import { ResultViewV1 } from "../../EditorCommon";import { useHistory } from "./useHistory";const tabStore = useSQLEditorTabStore();diff --git a/frontend/tsconfig.app.json b/frontend/tsconfig.app.jsonindex 96dd60e136..a3e267ef2a 100644--- a/frontend/tsconfig.app.json+++ b/frontend/tsconfig.app.json@@ -9,6 +9,8 @@],"exclude": ["src/**/__tests__/*",+ "src/**/*.test.ts",+ "src/**/*.test.tsx","src/react/**/*.tsx","src/react/components/MarkdownEditor/index.ts","src/react/components/task-run-log/index.ts",@@ -26,7 +28,8 @@"src/react/components/SchemaEditorLite/Panels/TableColumnEditor/index.ts","src/react/components/SchemaEditorLite/Panels/IndexesEditor/index.ts","src/react/components/SchemaEditorLite/Panels/PartitionsEditor/index.ts",- "src/react/components/SchemaEditorLite/Panels/TableList/index.ts"+ "src/react/components/SchemaEditorLite/Panels/TableList/index.ts",+ "src/react/components/sql-editor/ResultView/index.ts"],"compilerOptions": {"composite": true,diff --git a/frontend/tsconfig.vitest.json b/frontend/tsconfig.vitest.jsonindex cd3a92306e..ff689d6bb9 100644--- a/frontend/tsconfig.vitest.json+++ b/frontend/tsconfig.vitest.json@@ -25,7 +25,8 @@"src/react/components/SchemaEditorLite/Panels/TableColumnEditor/index.ts","src/react/components/SchemaEditorLite/Panels/IndexesEditor/index.ts","src/react/components/SchemaEditorLite/Panels/PartitionsEditor/index.ts",- "src/react/components/SchemaEditorLite/Panels/TableList/index.ts"+ "src/react/components/SchemaEditorLite/Panels/TableList/index.ts",+ "src/react/components/sql-editor/ResultView/index.ts"],"compilerOptions": {"composite": true,