Skip to content

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

refactor(react): migrate SQL Editor schema panel (#20124)

ecmadaoaacfad418d91
diff --git a/docs/superpowers/specs/2026-04-26-sql-editor-react-migration-stage-15-design.md b/docs/superpowers/specs/2026-04-26-sql-editor-react-migration-stage-15-design.md
new file mode 100644
index 0000000000..88feab37d5
--- /dev/null
+++ b/docs/superpowers/specs/2026-04-26-sql-editor-react-migration-stage-15-design.md
@@ -0,0 +1,265 @@
+# SQL Editor React Migration — Stage 15 Design
+
+**Date:** 2026-04-26
+**Author:** [email protected]
+**Status:** Draft
+
+## 1. Goal & non-goals
+
+**Goal:** Port the entire `SchemaPane/` subtree (the schema browser shown when `asidePanelTab === "SCHEMA"`) to React. After this stage, all four AsidePanel tabs (Worksheet, **Schema**, History, Access) are React; the only Vue surface left in the SQL Editor sidebar is `AsidePanel.vue` itself, which simply mounts the four React children.
+
+**Non-goals:**
+- Migrating `AsidePanel.vue` — host shell, still Vue; mounts the React panes.
+- Migrating `EditorPanel/*`, `ResultView/*`, or `SQLEditorHomePage.vue` — separate stages.
+- Refactoring `useDBSchemaV1Store`, `useSQLEditorTabStore`, `useSQLEditorContext`, or `useCurrentTabViewStateContext` — read/written via `useVueState` and direct method calls.
+- Visual or behavioral changes — parity only.
+- Changing the `NodeType` / `NodeTarget` discriminated unions or the wire shape of `tab.treeState.keys` (expanded/selected key persistence). The React port must produce **byte-identical** key strings so users' persisted tree state survives the swap.
+- Porting the schema viewer modal body (the surface that opens from `actions.tsx` "View schema") — only the trigger is in scope.
+
+## 2. Inventory
+
+### 2.1 SchemaPane root + utilities (7 files, ~2,369 LOC)
+
+| File | LOC | Notes |
+|---|---|---|
+| `SchemaPane.vue` | 546 | Root orchestrator: search input, NTree ↔ FlatTableList toggle, NDropdown context menu, hover-state provider, expand/select wiring. |
+| `FlatTableList.vue` | 198 | Alt-UI used when a database has more than ~1000 tables; NVirtualList of expandable rows. |
+| `SyncSchemaButton.vue` | 78 | Popover button calling `dbSchemaStore.syncDatabase`. |
+| `tree.ts` | 862 | Pure TS: `NodeType` (16 variants), `NodeTarget`, `TreeNode` types + `keyForNodeTarget` (large switch) + `buildDatabaseSchemaTree(metadata)` recursive builder. |
+| `actions.tsx` | 640 | Right-click menu: `useActions` (selectAll, viewDetail, openNewTab, copyName, …) + `useDropdown` (NDropdown imperative show/position). Heavy on Vue composables + JSX icon rendering for naive-ui DropdownOption. Despite the `.tsx` extension, this is a Vue module. |
+| `click.ts` | 42 | 250ms single/double-click discriminator built on Emittery. |
+| `index.ts` | 3 | Default-export re-export. |
+
+### 2.2 TreeNode/ (20 files, ~750 LOC)
+
+| File | LOC | Notes |
+|---|---|---|
+| `Label.vue` | 86 | Dispatcher — switches on `node.meta.type` to render the right `*Node`; passes through `HighlightLabelText` for search highlighting. |
+| `CommonNode.vue` | 41 | Shared template: icon slot + text + suffix slot. |
+| `ColumnNode.vue` | 96 | Reads `dbSchemaStore.getTableMetadata` for PK/index badges; renders `NTag` for the column type. |
+| `IndexNode.vue` | 44 | Unique / primary badge logic. |
+| `CheckNode.vue` | 59 | Reads metadata for the constraint expression. |
+| `TextNode.vue` | 40 | Expandable section headers ("Tables", "Views", …). |
+| `DummyNode.vue` | 34 | Error / empty placeholder. |
+| 13 thin variants | ~380 | `TableNode` 21, `ViewNode` 26, `SchemaNode` 24, `DatabaseNode` 39, `ProcedureNode` 39, `FunctionNode` 37, `SequenceNode` 26, `TriggerNode` 26, `PackageNode` 26, `ExternalTableNode` 23, `ForeignKeyNode` 28, `PartitionTableNode` 28, `DependencyColumnNode` 30 — each is essentially `<CommonNode icon={X} label={node.label} />`. |
+| `index.ts` | 3 | Re-exports. |
+
+### 2.3 HoverPanel/ (10 files, ~440 LOC)
+
+| File | LOC | Notes |
+|---|---|---|
+| `HoverPanel.vue` | 109 | Fixed-position popover; mouseenter/leave restart the timer; viewport-clamping math. |
+| `TableInfo.vue` | 78 | name / engine / row-count / size / collation / comment. |
+| `ColumnInfo.vue` | 85 | type / nullability / default / comment. |
+| `ViewInfo.vue` | 25 | name / engine / row-count / comment. |
+| `ExternalTableInfo.vue` | 35 | location / data format. |
+| `TablePartitionInfo.vue` | 48 | partition type / key / value. |
+| `InfoItem.vue` | 23 | Reusable `(label, value)` row. |
+| `CommonText.vue` | 11 | Text wrapper. |
+| `hover-state.ts` | 25 | Typed wrapper around the shared `EditorCommon/hover-state.ts` context (key = `"schema-pane"`). |
+| `index.ts` | 6 | Re-exports. |
+
+### 2.4 Caller integration
+
+`AsidePanel.vue:59` mounts `<SchemaPane v-if="asidePanelTab === 'SCHEMA'" />`. The other three tabs (`WorksheetPane`, `HistoryPane`, `AccessPane`) and the gutter (`GutterBar`) are already mounted via `<ReactPageMount …>`, so the harness is in place. SchemaPane is the last Vue child of `AsidePanel.vue`.
+
+### 2.5 Stores & context the subtree depends on
+
+| Source | What it provides |
+|---|---|
+| `useSQLEditorTabStore` | currentTab; `currentTab.treeState.keys` (persisted expand/select state); `openTabList`. |
+| `useDBSchemaV1Store` | `getOrFetchDatabaseMetadata`, `getTableMetadata`, `getSchemaMetadata`, `syncDatabase`. |
+| `useDatabaseV1Store` | engine detection, permissions. |
+| `useConnectionOfCurrentSQLEditorTab` | reactive `{ database, schema }` for the active tab. |
+| `useSQLEditorContext` (provide/inject) | `schemaViewer` ref, `events` (Emittery), `pendingInsertAtCaret`. |
+| `useCurrentTabViewStateContext` | `updateViewState`, `viewState` (used by actions to flip detail panes). |
+| `provideHoverStateContext("schema-pane")` | local provide/inject for `{ state, position, update }` consumed by HoverPanel. |
+
+## 3. External deps & primitives
+
+| Vue dep | React replacement | Status |
+|---|---|---|
+| `NTree` | `Tree` primitive (`src/react/components/ui/tree.tsx`) | ✓ from Stage 11; reused in Stage 14 ConnectionPane |
+| `NTree.renderLabel` (search highlight) | Render `<HighlightLabelText>` inside our `Tree` row renderer | New small component if not already in tree (verify reuse from Stage 14) |
+| `NDropdown` (imperative) | `ContextMenu` primitive (`src/react/components/ui/context-menu.tsx`) | ✓ added Stage 14b |
+| `NPopover` | `Popover` primitive | ✓ |
+| `NVirtualList` (FlatTableList) | `react-window` (already a dep) — decide between `FixedSizeList` and `VariableSizeList` in Phase 4d | Decision in 4d |
+| `NEmpty` | Inline `<div>` with i18n empty text | n/a |
+| `NTag` (column-type badge) | `Badge` primitive | ✓ |
+| `NIcon` | Direct `lucide-react` icon | ✓ |
+| `useDelayedValue` (`src/composables/useDelayedValue.ts`, 47 LOC) | New `useDelayedValue` React hook (`src/react/hooks/useDelayedValue.ts`); ref-stored timer; identical `update(value, "before"\|"after", overrideDelay?)` signature | New util |
+| `provide/inject` HoverStateContext | React `HoverStateProvider` + `useHoverState` (scoped to `SchemaPane.tsx`; not a global context) | New |
+| `@vueuse/core useElementSize` | `useResizeObserver` hook (already inline-used in Stage 14) | Reuse |
+| `@vueuse/core useEventListener` | `useEffect + addEventListener` | Inline |
+| `@vueuse/core useMounted` | `useState(false) + useEffect(()=>setTrue,[])` | Inline |
+| `@vueuse/core computedAsync` | `useEffect + useState` async pattern; cancel via AbortController where appropriate | Inline |
+| `@vueuse/core refDebounced` | Tiny `useDebouncedValue(value, ms)` hook (or reuse if Stage 14 landed one) | Reuse / inline |
+| `@vueuse/core useClipboard` | `navigator.clipboard.writeText` (already used in Stage 14b actions) | Inline |
+| `Emittery` (click.ts) | Keep — framework-agnostic | ✓ |
+| `protobuf-es` metadata types | Same imports | ✓ |
+| `lodash-es` | Same imports | ✓ |
+| `RichDatabaseName` (Vue) | Inline minimal display, or reuse the React helper if Stage 14 landed one (`src/react/components/RichDatabaseName.tsx`) | Reuse if present |
+
+## 4. Architecture & phases
+
+Five phases. Each commit-able independently, each green on `pnpm fix / type-check / test / check`.
+
+### Phase 1 — Pure utilities + leaf TreeNodes
+
+**Files ported:** `tree.ts` (copy as-is into `src/react/components/sql-editor/SchemaPane/schemaTree.ts` — already pure TS, no Vue deps), `click.ts` (likewise), and the React equivalents of `useDelayedValue` + `EditorCommon/hover-state.ts` (`useDelayedValue.ts` + `HoverStateProvider`/`useHoverState` exported from `src/react/components/sql-editor/SchemaPane/hover-state.tsx`). Plus the 16 thin leaf TreeNodes that just compose `CommonNode` + an icon + label, plus `CommonNode.tsx`, `DummyNode.tsx`, `TextNode.tsx`.
+
+Add or reuse `HighlightLabelText.tsx`. (Search Stage 14 output first — ConnectionPane likely already has one. If yes, lift to a shared location; if no, write a small new one and use it from both surfaces in a follow-up.)
+
+**Rename note:** The new tree builder is renamed `schemaTree.ts` (not `tree.ts`) to avoid colliding with `src/react/components/sql-editor/ConnectionPane/tree.ts` from Stage 14.
+
+**Approach:** No UI rewiring yet — these compile but aren't called. `schemaTree.ts` gets a unit test (`schemaTree.test.ts`) that asserts `buildDatabaseSchemaTree(fixtureMetadata)` produces the expected key paths for representative MySQL + Postgres + Oracle metadata fixtures. **This test is the regression net for the rest of the migration** — every subsequent phase keeps it green.
+
+**Deliverables:** ~16 `.tsx` + 3 `.ts/.tsx` (utils) + 1 test.
+
+### Phase 2 — Heavy TreeNodes + Label dispatcher
+
+**Files ported:** `ColumnNode.tsx` (reads `dbSchemaStore.getTableMetadata` via `useVueState`), `IndexNode.tsx`, `CheckNode.tsx`, and `Label.tsx` (the dispatcher that switches on `NodeType`).
+
+**Approach:** Each node is a presentational component with a stable signature `{ node: TreeNode; keyword: string }`. `Label.tsx` is a `switch (node.meta.type)` returning the right child. Verify rendered output against Vue side-by-side for the same `NodeTarget` fixtures.
+
+**Deliverables:** 4 `.tsx` + 1 `Label.test.tsx` covering all 16 dispatch branches via fixtures.
+
+### Phase 3 — HoverPanel
+
+**Files ported:** `HoverPanel.tsx`, `TableInfo.tsx`, `ColumnInfo.tsx`, `ViewInfo.tsx`, `ExternalTableInfo.tsx`, `TablePartitionInfo.tsx`, `InfoItem.tsx`, `CommonText.tsx`.
+
+**Approach:** Use the `Popover` primitive in **controlled** mode — the consumer (`SchemaPane.tsx`) drives `open`, `anchor`, and `state` via the React `useHoverState()` context from Phase 1. Viewport clamping uses `useResizeObserver` + bounds math (matches Vue's clamp at `HoverPanel.vue:90–100`). Render whichever `*Info` matches `state.column ?? state.partition ?? state.table ?? state.externalTable ?? state.view`. Mount via `getLayerRoot("overlay")` — non-modal hover surface goes into the standard overlay family.
+
+**Deliverables:** 8 `.tsx` + `HoverPanel.test.tsx` (mock dbSchema metadata, verify the right pane renders for each state shape, verify clamp math).
+
+### Phase 4 — actions + ContextMenu wiring + SyncSchemaButton + FlatTableList (sliced)
+
+The largest phase. Slice into 4a–4d so each can land cleanly.
+
+#### 4a — `useSchemaPaneActions` (logic only, no UI)
+Rewrite Vue `actions.tsx` as a React module. Two exports:
+- `useSchemaPaneActions()` returns invokable handlers: `selectAllFromTableOrView`, `viewDetail`, `openNewTab`, `copyName`, `insertColumnAtCaret`, etc. These call into `useSQLEditorTabStore`, `useSQLEditorContext().events`, `useCurrentTabViewStateContext().updateViewState`.
+- `useSchemaPaneContextMenu(target)` returns the `ContextMenuItem[]` array keyed by the `NodeTarget` discriminator. Mirror Vue branching exactly — **do not reorder items**; the order is the user-visible menu.
+
+Snapshot test: feed an exhaustive set of `NodeTarget` fixtures and assert the menu shape. This is the easiest place to introduce subtle regressions.
+
+#### 4b — `SchemaContextMenu`
+Imperative-handle wrapper around the `ContextMenu` primitive (matches `ConnectionContextMenu.tsx` from Stage 14b). Exposes `open(event, target)`. Internally renders items from `useSchemaPaneContextMenu(target)`.
+
+#### 4c — `SyncSchemaButton`
+Popover (last-sync timestamp + tooltip) + Button (RefreshCcw icon). On click, calls `dbSchemaStore.syncDatabase` then `dbSchemaStore.getOrFetchDatabaseMetadata`. State machine: idle → syncing → idle, with disabled button while syncing.
+
+#### 4d — `FlatTableList`
+Virtual list (`react-window` `VariableSizeList` if rows can expand inline, else `FixedSizeList`). Receives the same `tables[]` shape Vue uses. Emits `select`, `selectAll`, `contextmenu` callbacks. Verify smoothness with a synthetic 5k-row fixture before merging.
+
+**Deliverables:** ~5 `.tsx` + 4 tests.
+
+### Phase 5 — SchemaPane shell + caller swap + cleanup
+
+**Files ported:** `SchemaPane.tsx` (the orchestrator).
+
+**Approach:**
+- Internal state: `searchPattern` (debounced 200ms via local hook), `expandedKeys`/`selectedKeys` (synced **bidirectionally** with `tabStore.currentTab.treeState.keys` via `useVueState({deep:true})` — same pattern as TabList from Stage 14), `flatMode` (computed: `tableCount > 1000`).
+- Compose: `<HoverStateProvider>` → mount `<SchemaContextMenu ref={menuRef}>` → conditional `<Tree>` or `<FlatTableList>` → `<HoverPanel>` (anchored via context).
+- Subscribe to `dbSchemaStore.getOrFetchDatabaseMetadata(currentDatabase)` via `useEffect`; rebuild via `buildDatabaseSchemaTree` when metadata version bumps.
+- Caller swap: `AsidePanel.vue:59` from `<SchemaPane v-if="..." />` to `<ReactPageMount page="SchemaPane" v-if="..." container-class="h-full" />`.
+- Register `SchemaPane` in `src/react/mount.ts` page registry.
+- Delete the entire Vue `SchemaPane/` directory once `grep` confirms zero callers.
+- Verify `EditorCommon/hover-state.ts` is still used by other Vue surfaces; delete if not.
+
+**Deliverables:** 1 `.tsx` + `SchemaPane.test.tsx` + caller swap + Vue tree deletion + i18n key audit (no new keys expected — schema-pane keys are display-only and ported as-is).
+
+## 5. Per-phase checklist
+
+### Phase 1 — Utilities + leaf TreeNodes
+- [ ] `schemaTree.ts` ported (`src/react/components/sql-editor/SchemaPane/schemaTree.ts`)
+- [ ] `schemaTree.test.ts` covering each `NodeType` branch
+- [ ] `click.ts` ported (or imported from existing location if framework-agnostic)
+- [ ] `useDelayedValue.ts` React hook + test
+- [ ] `HoverStateProvider` / `useHoverState` context + types
+- [ ] 16 leaf `TreeNode/*.tsx` files + shared `CommonNode.tsx`, `TextNode.tsx`, `DummyNode.tsx`
+- [ ] `HighlightLabelText.tsx` (or reuse if Stage 14 landed one)
+- [ ] Gates green
+
+### Phase 2 — Heavy nodes + Label dispatcher
+- [ ] `ColumnNode.tsx`, `IndexNode.tsx`, `CheckNode.tsx`
+- [ ] `Label.tsx` dispatcher
+- [ ] `Label.test.tsx` (16 branches)
+- [ ] Gates green
+
+### Phase 3 — HoverPanel
+- [ ] `HoverPanel.tsx` + 6 `*Info.tsx` + `InfoItem.tsx` + `CommonText.tsx`
+- [ ] `HoverPanel.test.tsx`
+- [ ] Viewport clamp math verified
+- [ ] Gates green
+
+### Phase 4a — Actions logic
+- [ ] `useSchemaPaneActions.ts` + test
+- [ ] `useSchemaPaneContextMenu(target)` snapshot test across all NodeTarget shapes
+- [ ] Gates green
+
+### Phase 4b — Context menu
+- [ ] `SchemaContextMenu.tsx` + imperative ref handle + test
+- [ ] Gates green
+
+### Phase 4c — Sync button
+- [ ] `SyncSchemaButton.tsx` + test
+- [ ] Gates green
+
+### Phase 4d — Flat table list
+- [ ] `FlatTableList.tsx` + virtualization decision documented inline
+- [ ] Test (synthetic 5k-row fixture for scroll smoothness)
+- [ ] Gates green
+
+### Phase 5 — Shell + caller swap + cleanup
+- [ ] `SchemaPane.tsx` + test
+- [ ] `mount.ts` registers page
+- [ ] `AsidePanel.vue` swapped to `<ReactPageMount page="SchemaPane" />`
+- [ ] `grep` confirms zero live Vue callers of `SchemaPane.vue` and the TreeNode/HoverPanel files
+- [ ] Delete entire Vue `SchemaPane/` directory
+- [ ] Verify `EditorCommon/hover-state.ts` is still used; delete if not
+- [ ] Gates green
+
+## 6. Manual UX verification (after all phases)
+
+1. Open SQL Editor → connect to a MySQL database with ~10 tables → schema tree renders, expanded to schema level.
+2. Click a table → row highlights; tree state persists across tab switches and survives page reload.
+3. Type `users` in the search box → matches highlight; non-matching subtrees collapse; clear search → tree restores prior expand state.
+4. Hover a column for ~1s → HoverPanel appears with type / nullability / default; move mouse off → panel hides after 350ms; quick re-hover → panel re-appears immediately within the after-window.
+5. Right-click a table → context menu shows Copy / Select * / View schema / Open in new tab; click Select * → SQL is inserted at editor caret.
+6. Right-click a column → menu shows column-specific actions (Insert at caret, Copy name).
+7. Click Sync icon → spinner; metadata refetches; tree re-renders without losing expand/select state.
+8. Connect to a database with >1000 tables → SchemaPane renders FlatTableList instead of NTree → scroll smoothly, expand a row → columns appear inline.
+9. Repeat 1–6 across MySQL, Postgres (schemas), and Oracle (packages) to cover engine-specific node types.
+10. Switch the AsidePanel tab Worksheet → Schema → History → Schema → tree re-renders without losing expand/select state.
+11. Disconnect (clear connection) → AsidePanel hides SchemaPane (`v-if`); reconnect → fresh fetch.
+
+## 7. Out of scope (deferred)
+
+- `AsidePanel.vue` migration (host shell — Vue-only after this stage; mounts the four React panes via `ReactPageMount`).
+- `EditorPanel.vue`, `Panels/*` (TablesPanel / ViewsPanel / IndexesPanel / etc.) — separate stage.
+- `ResultView/VirtualDataTable/*` — separate stage; needs perf spike first.
+- `SQLEditorHomePage.vue` — root container; depends on EditorPanel.
+- Schema viewer modal body (the modal that opens from `actions.tsx` "View schema" — only the trigger is ported; modal body remains Vue).
+
+## 8. Risks & open questions
+
+- **`buildDatabaseSchemaTree` regression risk.** 862 LOC of recursive metadata→tree code with 16 type branches. Tree-key paths must match exactly so `tabStore.currentTab.treeState.keys` (persisted expand/select state) keeps working across the Vue→React swap. **Mitigation:** Phase 1 lands a unit test fixture per engine before any orchestrator changes.
+
+- **`Tree` primitive at 10k+ rows.** Stage 14 risks list flagged this for ConnectionPane (≤10k databases). SchemaPane can hit 10k+ columns when a single big table is fully expanded. **Mitigation:** FlatTableList already handles >1000-table DBs; for column-explosion within a single table, apply the same threshold — fall back to a virtualized leaf list. Benchmark in Phase 5.
+
+- **Hover-state timing.** 1000ms-before / 350ms-after is fragile in React because effect cleanup races setTimeout callbacks. **Mitigation:** ref-stored timer (not state); cancel + reschedule unconditionally in the same effect; test with rapid mouseenter/leave bursts. Mirror `useDelayedValue.ts` line-for-line so the semantics are identical.
+
+- **Search-highlight + virtual scroll.** Vue uses NTree's `renderLabel` callback so the highlight DOM is rebuilt only for visible rows. Naive React port could re-render all rows on every keystroke. **Mitigation:** memoize the row renderer; key the highlight `useMemo` on `(keyword, node.id)`. Benchmark with a 5k-column fixture.
+
+- **`useSQLEditorContext` provide/inject.** Many `actions.tsx` paths call `context.events.emit(...)` to drive caret-insert and pendingInsert state. The React port reads state via `useVueState` and calls methods directly for emits. Need to verify `events` (Emittery) is reachable as a stable reference from a Pinia setup store. It should be — typically held in a `ref(emittery)` — but confirm in Phase 4a.
+
+- **`provideHoverStateContext` is per-key.** Other surfaces may use the shared `EditorCommon/hover-state.ts` with a different key. Phase 5 cleanup must check before deleting the shared module. If still in use, leave it; the React port has its own scoped provider.
+
+- **`actions.tsx` has 640 LOC of branchy menu logic.** The easiest place to introduce subtle 1:1 regressions. **Mitigation:** snapshot test in 4a covering every `NodeTarget` discriminator. Sit Vue and React versions side-by-side during 4b smoke testing.
+
+- **Naming collision: `tree.ts`.** A file at `src/react/components/sql-editor/SchemaPane/tree.ts` would shadow `…/ConnectionPane/tree.ts` in fuzzy searches. Renamed to `schemaTree.ts` for clarity.
+
+- **`FlatTableList` virtualization library choice.** `react-window` is already a dep used by the worksheet table; prefer it over introducing `react-virtualized` or `@tanstack/virtual`. Confirm `react-window`'s expandable-row support meets parity with `NVirtualList`'s; if not, fall back to a non-virtualized list with a 1k-row hard cap matching Vue's existing threshold.
+
+- **HighlightLabelText source of truth.** If Stage 14 landed a React equivalent for ConnectionPane search, lift it to a shared location (`src/react/components/sql-editor/HighlightLabelText.tsx`) before Stage 15 imports it; otherwise we'll end up with two near-identical copies.
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index ac8550d517..9cf97b3b8d 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2532,7 +2532,6 @@
},
"invalid-database": "Invalid database {database}",
"jit": "Just-In-Time Access",
- "last-synced": "Last synced: {time}",
"link-access": "Link access",
"loading-data": "Loading Data...",
"loading-databases": "Loading Databases...",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index a7b88a23ce..163d90d893 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2532,7 +2532,6 @@
},
"invalid-database": "Base de datos no válida {database}",
"jit": "Just-In-Time Access",
- "last-synced": "Última sincronización: {hora}",
"link-access": "Acceso al enlace",
"loading-data": "Cargando datos...",
"loading-databases": "Cargando bases de datos...",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 9fe40ffbc2..0a45d3f20e 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -2532,7 +2532,6 @@
},
"invalid-database": "無効なデータベース {database}",
"jit": "Just-In-Time Access",
- "last-synced": "最終同期時間: {time}",
"link-access": "リンクアクセス",
"loading-data": "データのロード...",
"loading-databases": "データベース情報をロードしています...",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 5bb8cb61e5..4dc6eca746 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -2532,7 +2532,6 @@
},
"invalid-database": "Cơ sở dữ liệu không hợp lệ {database}",
"jit": "Just-In-Time Access",
- "last-synced": "Đã đồng bộ lần cuối: {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...",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index e5ce81a742..f722242da8 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2532,7 +2532,6 @@
},
"invalid-database": "数据库 {database} 无效",
"jit": "即时访问",
- "last-synced": "上次同步时间:{time}",
"link-access": "链接访问权限",
"loading-data": "加载数据中...",
"loading-databases": "加载数据库信息...",
diff --git a/frontend/src/react/components/ProjectSelect.tsx b/frontend/src/react/components/ProjectSelect.tsx
index e4aa88b94a..1fc64fdf1d 100644
--- a/frontend/src/react/components/ProjectSelect.tsx
+++ b/frontend/src/react/components/ProjectSelect.tsx
@@ -1,3 +1,4 @@
+import type { ReactNode } from "react";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Combobox } from "@/react/components/ui/combobox";
@@ -13,6 +14,11 @@ export interface ProjectSelectProps {
className?: string;
/** When true, the workspace's default project is excluded. Defaults to true. */
excludeDefault?: boolean;
+ /** Optional rich empty-state node — used by surfaces that need to
+ * surface workspace-level guidance (e.g. AsidePanel's "not a member
+ * of any projects" + "go to create" prompt). Falls back to the
+ * generic "no data" string when omitted. */
+ emptyContent?: ReactNode;
}
export function ProjectSelect({
@@ -22,6 +28,7 @@ export function ProjectSelect({
disabled,
className,
excludeDefault = true,
+ emptyContent,
}: ProjectSelectProps) {
const { t } = useTranslation();
const projectStore = useProjectV1Store();
@@ -57,6 +64,7 @@ export function ProjectSelect({
onChange={handleChange}
placeholder={placeholder ?? t("common.project")}
noResultsText={t("common.no-data")}
+ noResultsContent={emptyContent}
onSearch={fetchProjects}
disabled={disabled}
className={className}
diff --git a/frontend/src/react/components/TableSchemaViewer.tsx b/frontend/src/react/components/TableSchemaViewer.tsx
new file mode 100644
index 0000000000..5faa1203a9
--- /dev/null
+++ b/frontend/src/react/components/TableSchemaViewer.tsx
@@ -0,0 +1,99 @@
+import { create } from "@bufbuild/protobuf";
+import { Copy } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { databaseServiceClientConnect } from "@/connect";
+import { ReadonlyMonaco } from "@/react/components/monaco/ReadonlyMonaco";
+import { Button } from "@/react/components/ui/button";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import {
+ type Database,
+ type GetSchemaStringRequest_ObjectType,
+ GetSchemaStringRequestSchema,
+} from "@/types/proto-es/v1/database_service_pb";
+import { getInstanceResource, hasSchemaProperty } from "@/utils";
+
+type Props = {
+ readonly database: Database;
+ readonly schema?: string;
+ readonly object?: string;
+ readonly type?: GetSchemaStringRequest_ObjectType;
+ readonly className?: string;
+};
+
+/**
+ * React port of `frontend/src/components/TableSchemaViewer.vue`.
+ *
+ * Fetches the SDL-style schema text for a database / schema / table /
+ * view via `databaseServiceClientConnect.getSchemaString` and displays
+ * it read-only. Header shows a `schema.object` (or `object` for
+ * engines without schemas) breadcrumb plus a Copy-to-clipboard button.
+ */
+export function TableSchemaViewer({
+ database,
+ schema,
+ object,
+ type,
+ className,
+}: Props) {
+ const { t } = useTranslation();
+ const [schemaString, setSchemaString] = useState<string>("");
+
+ const engine = getInstanceResource(database).engine;
+ const resourceName = object
+ ? hasSchemaProperty(engine)
+ ? `${schema}.${object}`
+ : object
+ : schema || database.name;
+
+ useEffect(() => {
+ let cancelled = false;
+ const request = create(GetSchemaStringRequestSchema, {
+ name: `${database.name}/schemaString`,
+ type,
+ schema,
+ object,
+ });
+ void databaseServiceClientConnect
+ .getSchemaString(request)
+ .then((response) => {
+ if (cancelled) return;
+ setSchemaString(response.schemaString.trim());
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [database.name, schema, object, type]);
+
+ const handleCopy = async () => {
+ if (typeof navigator === "undefined" || !navigator.clipboard) return;
+ await navigator.clipboard.writeText(schemaString);
+ };
+
+ return (
+ <div
+ className={`w-full h-auto flex flex-col justify-start items-center ${className ?? ""}`}
+ >
+ <div className="w-full flex flex-row justify-between items-center gap-x-2 mb-2">
+ <div className="text-sm text-control flex-1 truncate">
+ {resourceName}
+ </div>
+ <Tooltip content={t("common.copy")}>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={!schemaString}
+ onClick={handleCopy}
+ >
+ <Copy className="size-4" />
+ </Button>
+ </Tooltip>
+ </div>
+ <ReadonlyMonaco
+ content={schemaString}
+ className="border w-full h-auto grow"
+ />
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/AsidePanel.tsx b/frontend/src/react/components/sql-editor/AsidePanel.tsx
new file mode 100644
index 0000000000..425f505260
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/AsidePanel.tsx
@@ -0,0 +1,140 @@
+import { useCallback } from "react";
+import { useTranslation } from "react-i18next";
+import { ProjectSelect } from "@/react/components/ProjectSelect";
+import { useVueState } from "@/react/hooks/useVueState";
+import { router } from "@/router";
+import { PROJECT_V1_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";
+import {
+ useActuatorV1Store,
+ useSQLEditorStore,
+ useSQLEditorTabStore,
+ useSQLEditorUIStore,
+ useSQLEditorWorksheetStore,
+} from "@/store";
+import { defaultProject, isValidProjectName } from "@/types";
+import { hasProjectPermissionV2, hasWorkspacePermissionV2 } from "@/utils";
+import { AccessPane } from "./AccessPane";
+import { ActionBar } from "./AsidePanel/ActionBar";
+import { GutterBar } from "./GutterBar";
+import { HistoryPane } from "./HistoryPane";
+import { SchemaPane } from "./SchemaPane/SchemaPane";
+import { WorksheetPane } from "./WorksheetPane";
+
+/**
+ * Replaces `frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue`.
+ *
+ * Three-column shell:
+ * 1. GutterBar (vertical icon rail) — fixed.
+ * 2. ActionBar — only when `asidePanelTab === "SCHEMA"` and the tab is
+ * connected to a database. Vertical button column for view drill-downs.
+ * 3. Main column — project picker on top + active pane (Worksheet /
+ * Schema / History / Access) below.
+ *
+ * Schema-viewer modal stays in `SQLEditorHomePage.vue` (Vue parent) since
+ * the embedded `TableSchemaViewer` is Vue-only; the React side triggers
+ * it via the `show-schema-viewer` event on `sqlEditorEvents`.
+ */
+export function AsidePanel() {
+ const { t } = useTranslation();
+ const editorStore = useSQLEditorStore();
+ const actuatorStore = useActuatorV1Store();
+ const tabStore = useSQLEditorTabStore();
+ const uiStore = useSQLEditorUIStore();
+ const worksheetStore = useSQLEditorWorksheetStore();
+
+ const asidePanelTab = useVueState(() => uiStore.asidePanelTab);
+ const isDisconnected = useVueState(() => tabStore.isDisconnected);
+ const project = useVueState(() => editorStore.project);
+ const projectContextReady = useVueState(
+ () => editorStore.projectContextReady
+ );
+
+ const allowAccessDefaultProject = useVueState(() => {
+ const name = actuatorStore.serverInfo?.defaultProject ?? "";
+ return hasProjectPermissionV2(defaultProject(name), "bb.projects.get");
+ });
+ const allowCreateProject = useVueState(() =>
+ hasWorkspacePermissionV2("bb.projects.create")
+ );
+
+ const handleSwitchProject = useCallback(
+ (name: string) => {
+ if (!name || !isValidProjectName(name)) {
+ editorStore.setProject("");
+ } else {
+ void worksheetStore.maybeSwitchProject(name);
+ }
+ },
+ [editorStore, worksheetStore]
+ );
+
+ // Vue's `<template #empty>` — rich empty state when the user is not
+ // a member of any project. Shows a "go to create" link when the user
+ // has `bb.projects.create`, or an "ask the admin" hint otherwise.
+ // Vue Router resolves the dashboard route to its href; rendering a
+ // plain anchor lets the page navigate via the router's history side
+ // effects without dragging react-router-dom into the bundle.
+ const projectsHref = router.resolve({
+ name: PROJECT_V1_ROUTE_DASHBOARD,
+ hash: "#new",
+ }).href;
+ const emptyContent = (
+ <div className="text-sm text-control-placeholder flex flex-col gap-1">
+ <p>
+ {t("sql-editor.no-project.not-member-of-any-projects")}{" "}
+ {allowCreateProject ? (
+ <a
+ href={projectsHref}
+ className="text-accent hover:underline"
+ onClick={(e) => {
+ e.preventDefault();
+ router.push({
+ name: PROJECT_V1_ROUTE_DASHBOARD,
+ hash: "#new",
+ });
+ }}
+ >
+ {t("sql-editor.no-project.go-to-create")}
+ </a>
+ ) : null}
+ </p>
+ {!allowCreateProject ? (
+ <p>{t("sql-editor.no-project.contact-the-admin-to-grant-access")}</p>
+ ) : null}
+ </div>
+ );
+
+ return (
+ <div className="h-full flex flex-row overflow-hidden">
+ <div className="h-full border-r shrink-0">
+ <GutterBar />
+ </div>
+ {asidePanelTab === "SCHEMA" && !isDisconnected ? (
+ <div className="h-full border-r shrink-0">
+ <ActionBar />
+ </div>
+ ) : null}
+ <div className="h-full flex-1 flex flex-col overflow-hidden">
+ <div className="flex flex-row items-center gap-x-1 px-1 py-1 border-b">
+ <ProjectSelect
+ className="w-full project-select"
+ value={project ?? ""}
+ onChange={handleSwitchProject}
+ disabled={!projectContextReady}
+ excludeDefault={!allowAccessDefaultProject}
+ emptyContent={emptyContent}
+ />
+ </div>
+
+ <div className="flex-1 flex flex-row overflow-hidden">
+ <div className="h-full flex-1 flex flex-col pt-1 overflow-hidden">
+ {asidePanelTab === "WORKSHEET" ? <WorksheetPane /> : null}
+ {asidePanelTab === "SCHEMA" ? <SchemaPane /> : null}
+ {asidePanelTab === "HISTORY" ? <HistoryPane /> : null}
+ {asidePanelTab === "ACCESS" ? <AccessPane /> : null}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/AsidePanel/ActionBar.tsx b/frontend/src/react/components/sql-editor/AsidePanel/ActionBar.tsx
new file mode 100644
index 0000000000..78ff02f22b
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/AsidePanel/ActionBar.tsx
@@ -0,0 +1,24 @@
+import { useAvailableActions } from "../SchemaPane/availableActions";
+import { ActionBarTabItem } from "./ActionBarTabItem";
+
+/**
+ * Replaces `frontend/src/views/sql-editor/AsidePanel/ActionBar/ActionBar.vue`.
+ *
+ * Vertical column of one button per `viewState` action (Info / Tables /
+ * Views / Functions / Procedures / + engine-conditional Sequences /
+ * External Tables / Packages / Diagram). Rendered in the AsidePanel's
+ * Schema column when a connection is active.
+ */
+export function ActionBar() {
+ const actions = useAvailableActions();
+
+ return (
+ <div className="h-full flex flex-col items-stretch justify-between overflow-hidden text-sm p-1 shrink-0">
+ <div className="flex flex-col gap-y-1">
+ {actions.map((action) => (
+ <ActionBarTabItem key={action.view} action={action} />
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/AsidePanel/ActionBarTabItem.tsx b/frontend/src/react/components/sql-editor/AsidePanel/ActionBarTabItem.tsx
new file mode 100644
index 0000000000..f387c1bead
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/AsidePanel/ActionBarTabItem.tsx
@@ -0,0 +1,72 @@
+import { Button } from "@/react/components/ui/button";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { useVueState } from "@/react/hooks/useVueState";
+import { cn } from "@/react/lib/utils";
+import {
+ useConnectionOfCurrentSQLEditorTab,
+ useSQLEditorTabStore,
+} from "@/store";
+import { extractDatabaseResourceName } from "@/utils";
+import type { AvailableAction } from "../SchemaPane/actions";
+import { useSchemaPaneActions } from "../SchemaPane/actions";
+
+type Props = {
+ readonly action: AvailableAction;
+ readonly disabled?: boolean;
+};
+
+/**
+ * Replaces `frontend/src/views/sql-editor/AsidePanel/ActionBar/TabItem.vue`.
+ *
+ * One vertical-rail button per panel view. Active state lights up when
+ * the current tab's `viewState.view` equals the action's view. Click
+ * opens (or focuses) a tab for that view via
+ * `useSchemaPaneActions().openNewTab`.
+ *
+ * The label rides in a right-aligned tooltip — same UX as Vue's
+ * `<NTooltip placement="right">`.
+ */
+export function ActionBarTabItem({ action, disabled }: Props) {
+ const tabStore = useSQLEditorTabStore();
+ const { database: databaseRef } = useConnectionOfCurrentSQLEditorTab();
+ const { openNewTab } = useSchemaPaneActions();
+
+ const active = useVueState(
+ () => tabStore.currentTab?.viewState?.view === action.view
+ );
+ const database = useVueState(() => databaseRef.value);
+
+ const handleClick = () => {
+ openNewTab({
+ title: `[${
+ extractDatabaseResourceName(database.name).databaseName
+ }] ${action.title}`,
+ view: action.view,
+ });
+ };
+
+ return (
+ <Tooltip side="right" content={action.title} delayDuration={300}>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={disabled}
+ onClick={handleClick}
+ className={cn(
+ "h-8 w-9 px-1 flex items-center justify-center",
+ active && "bg-accent/10 text-accent hover:bg-accent/15"
+ )}
+ >
+ <span
+ className={cn(
+ "size-4 inline-flex items-center justify-center",
+ !active && "text-main"
+ )}
+ >
+ {action.icon}
+ </span>
+ </Button>
+ </Tooltip>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane.tsx b/frontend/src/react/components/sql-editor/SchemaPane.tsx
new file mode 100644
index 0000000000..5af30868d3
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane.tsx
@@ -0,0 +1,10 @@
+/**
+ * Top-level mount-shim for the SchemaPane subtree. The mount registry
+ * (`src/react/mount.ts`) discovers React pages via a non-recursive glob
+ * (`./components/sql-editor/*.tsx`); the subtree itself lives one level
+ * deeper at `./SchemaPane/SchemaPane.tsx` so its helpers (TreeNode/,
+ * HoverPanel/, schemaTree.ts, …) co-locate. Re-exporting here keeps the
+ * file structure clean and lets `<ReactPageMount page="SchemaPane" />`
+ * find the component.
+ */
+export { SchemaPane } from "./SchemaPane/SchemaPane";
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/FlatTableList.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/FlatTableList.test.tsx
new file mode 100644
index 0000000000..9976aae0c0
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/FlatTableList.test.tsx
@@ -0,0 +1,230 @@
+import { create } from "@bufbuild/protobuf";
+import { act, type ReactElement } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ ColumnMetadataSchema,
+ DatabaseMetadataSchema,
+ IndexMetadataSchema,
+ SchemaMetadataSchema,
+ TableMetadataSchema,
+} from "@/types/proto-es/v1/database_service_pb";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ hoverState: undefined as unknown,
+ hoverUpdate: vi.fn(),
+ hoverSetPosition: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (k: string) => k }),
+}));
+
+vi.mock("./hover-state", () => ({
+ useHoverState: () => ({
+ state: mocks.hoverState,
+ setPosition: mocks.hoverSetPosition,
+ update: mocks.hoverUpdate,
+ cancel: vi.fn(),
+ }),
+}));
+
+vi.mock("@/react/components/ui/button", () => ({
+ Button: ({
+ children,
+ onClick,
+ className,
+ }: {
+ children: React.ReactNode;
+ onClick?: (e: React.MouseEvent) => void;
+ className?: string;
+ }) => (
+ <button
+ type="button"
+ data-testid="btn"
+ data-class={className}
+ onClick={onClick}
+ >
+ {children}
+ </button>
+ ),
+}));
+
+vi.mock("@/utils/dom", () => ({
+ findAncestor: () => null,
+}));
+
+let FlatTableList: typeof import("./FlatTableList").FlatTableList;
+
+const renderInto = (element: ReactElement) => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ return {
+ container,
+ render: () => act(() => root.render(element)),
+ unmount: () => {
+ act(() => root.unmount());
+ container.remove();
+ },
+ };
+};
+
+const buildMetadata = (
+ schemas: {
+ name: string;
+ tables: { name: string; columns?: string[]; indexes?: string[] }[];
+ }[]
+) =>
+ create(DatabaseMetadataSchema, {
+ schemas: schemas.map((s) =>
+ create(SchemaMetadataSchema, {
+ name: s.name,
+ tables: s.tables.map((t) =>
+ create(TableMetadataSchema, {
+ name: t.name,
+ columns: (t.columns ?? []).map((c) =>
+ create(ColumnMetadataSchema, { name: c, type: "varchar" })
+ ),
+ indexes: (t.indexes ?? []).map((i) =>
+ create(IndexMetadataSchema, { name: i })
+ ),
+ })
+ ),
+ })
+ ),
+ });
+
+beforeEach(async () => {
+ mocks.hoverState = undefined;
+ mocks.hoverUpdate.mockReset();
+ mocks.hoverSetPosition.mockReset();
+ ({ FlatTableList } = await import("./FlatTableList"));
+});
+
+afterEach(() => {
+ document.body.innerHTML = "";
+});
+
+const noopProps = {
+ database: "instances/i/databases/db",
+ onSelect: vi.fn(),
+ onSelectAll: vi.fn(),
+ onContextMenu: vi.fn(),
+};
+
+describe("FlatTableList", () => {
+ test("renders one row per table across all schemas", () => {
+ const md = buildMetadata([
+ { name: "public", tables: [{ name: "users" }, { name: "orders" }] },
+ { name: "audit", tables: [{ name: "events" }] },
+ ]);
+ const { container, render, unmount } = renderInto(
+ <FlatTableList metadata={md} {...noopProps} />
+ );
+ render();
+ expect(container.querySelectorAll(".bb-flat-table-row").length).toBe(3);
+ unmount();
+ });
+
+ test("filters by search keyword (case-insensitive substring match on schema/table key)", () => {
+ const md = buildMetadata([
+ { name: "public", tables: [{ name: "users" }, { name: "orders" }] },
+ ]);
+ const { container, render, unmount } = renderInto(
+ <FlatTableList metadata={md} search="ORD" {...noopProps} />
+ );
+ render();
+ const rows = container.querySelectorAll(".bb-flat-table-row");
+ expect(rows.length).toBe(1);
+ expect(rows[0].textContent).toContain("orders");
+ unmount();
+ });
+
+ test("renders the empty placeholder when no tables match the search", () => {
+ const md = buildMetadata([{ name: "public", tables: [{ name: "users" }] }]);
+ const { container, render, unmount } = renderInto(
+ <FlatTableList metadata={md} search="missing" {...noopProps} />
+ );
+ render();
+ expect(container.textContent).toContain("No tables found");
+ unmount();
+ });
+
+ test("expand toggle reveals columns + indexes", () => {
+ const md = buildMetadata([
+ {
+ name: "public",
+ tables: [
+ { name: "users", columns: ["id", "email"], indexes: ["ix_email"] },
+ ],
+ },
+ ]);
+ const { container, render, unmount } = renderInto(
+ <FlatTableList metadata={md} {...noopProps} />
+ );
+ render();
+ const expandBtn = container.querySelectorAll("[data-testid='btn']")[0];
+ act(() => {
+ (expandBtn as HTMLButtonElement).dispatchEvent(
+ new MouseEvent("click", { bubbles: true })
+ );
+ });
+ expect(container.textContent).toContain("id");
+ expect(container.textContent).toContain("email");
+ expect(container.textContent).toContain("ix_email");
+ unmount();
+ });
+
+ test("clicking a row fires onSelect with the table item", () => {
+ const md = buildMetadata([{ name: "public", tables: [{ name: "users" }] }]);
+ const onSelect = vi.fn();
+ const { container, render, unmount } = renderInto(
+ <FlatTableList
+ metadata={md}
+ database="instances/i/databases/db"
+ onSelect={onSelect}
+ onSelectAll={vi.fn()}
+ onContextMenu={vi.fn()}
+ />
+ );
+ render();
+ const row = container.querySelector(".bb-flat-table-row") as HTMLElement;
+ act(() => {
+ row.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ expect(onSelect.mock.calls[0][0].metadata.name).toBe("users");
+ unmount();
+ });
+
+ test("right-click fires onContextMenu and defaults are prevented", () => {
+ const md = buildMetadata([{ name: "public", tables: [{ name: "users" }] }]);
+ const onContextMenu = vi.fn();
+ const { container, render, unmount } = renderInto(
+ <FlatTableList
+ metadata={md}
+ database="instances/i/databases/db"
+ onSelect={vi.fn()}
+ onSelectAll={vi.fn()}
+ onContextMenu={onContextMenu}
+ />
+ );
+ render();
+ const row = container.querySelector(".bb-flat-table-row") as HTMLElement;
+ const event = new MouseEvent("contextmenu", {
+ bubbles: true,
+ cancelable: true,
+ });
+ act(() => {
+ row.dispatchEvent(event);
+ });
+ expect(onContextMenu).toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ unmount();
+ });
+});
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/FlatTableList.tsx b/frontend/src/react/components/sql-editor/SchemaPane/FlatTableList.tsx
new file mode 100644
index 0000000000..7f64d649bb
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/FlatTableList.tsx
@@ -0,0 +1,268 @@
+import { ChevronDown, ChevronRight, Table as TableIcon } from "lucide-react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import { cn } from "@/react/lib/utils";
+import type {
+ DatabaseMetadata,
+ TableMetadata,
+} from "@/types/proto-es/v1/database_service_pb";
+import { findAncestor } from "@/utils/dom";
+import { useHoverState } from "./hover-state";
+import { ColumnIcon, IndexIcon } from "./TreeNode/icons";
+
+const PAGE_SIZE = 500;
+/**
+ * Hard cap matching Vue's PAGE_SIZE × default page count behavior. The
+ * design risk note flagged that `react-window` isn't a dep yet and the
+ * table-row count for FlatTableList mode is bounded — pure DOM rendering
+ * with a load-more cursor keeps this within ~500 rows (28px × 500 = ~14k
+ * px of DOM) per page, which modern browsers handle without
+ * virtualization. Revisit only if the cap becomes a real bottleneck.
+ */
+
+export interface FlatTableItem {
+ readonly key: string;
+ readonly schema: string;
+ readonly metadata: TableMetadata;
+}
+
+type Props = {
+ readonly metadata: DatabaseMetadata | undefined;
+ readonly database: string;
+ readonly search?: string;
+ readonly onSelect: (item: FlatTableItem) => void;
+ readonly onSelectAll: (item: FlatTableItem) => void;
+ readonly onContextMenu: (e: React.MouseEvent, item: FlatTableItem) => void;
+};
+
+/**
+ * Replaces `SchemaPane/FlatTableList.vue`. Flat list of tables with
+ * inline expand-to-show-columns/indexes for large databases (Vue
+ * threshold is >1000 tables). Search-filterable, paged at 500 rows
+ * with a load-more button at the bottom.
+ *
+ * Hover sets the SchemaPane's hover state so the shared HoverPanel can
+ * preview the table — same wiring as the Tree mode.
+ */
+export function FlatTableList({
+ metadata,
+ database,
+ search,
+ onSelect,
+ onSelectAll,
+ onContextMenu,
+}: Props) {
+ const { t } = useTranslation();
+ const hoverState = useHoverState();
+
+ const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
+ const [selectedKey, setSelectedKey] = useState<string | undefined>();
+ const [pageIndex, setPageIndex] = useState(0);
+
+ const filteredTables = useMemo<FlatTableItem[]>(() => {
+ const tables: FlatTableItem[] = [];
+ const pattern = search?.trim().toLowerCase();
+ if (!metadata?.schemas) return tables;
+ for (const schema of metadata.schemas) {
+ for (const table of schema.tables ?? []) {
+ const item: FlatTableItem = {
+ key: `${schema.name}/${table.name}`,
+ schema: schema.name,
+ metadata: table,
+ };
+ if (!pattern || item.key.toLowerCase().includes(pattern)) {
+ tables.push(item);
+ }
+ }
+ }
+ return tables;
+ }, [metadata, search]);
+
+ // Reset paging + expand state when the underlying list materially
+ // changes (e.g. user typed a new search, or switched databases).
+ useEffect(() => {
+ setPageIndex(0);
+ setExpanded(new Set());
+ }, [metadata, search]);
+
+ const pagedTables = useMemo(
+ () => filteredTables.slice(0, (pageIndex + 1) * PAGE_SIZE),
+ [filteredTables, pageIndex]
+ );
+
+ const hoverPositionRef = useRef(hoverState.setPosition);
+ hoverPositionRef.current = hoverState.setPosition;
+
+ const handleMouseEnter = (
+ e: React.MouseEvent<HTMLDivElement>,
+ item: FlatTableItem
+ ) => {
+ const target = {
+ database,
+ schema: item.schema,
+ table: item.metadata.name,
+ };
+ // 150ms when sliding between rows (state already populated) so the
+ // hover panel doesn't flicker; full open delay otherwise.
+ const delay = hoverState.state ? 150 : undefined;
+ hoverState.update(target, "before", delay);
+
+ // Microtask: position computed against the actual DOM bounding rect,
+ // matching Vue's `await nextTick()` before reading getBoundingClientRect.
+ const wrapper = findAncestor(e.target as HTMLElement, ".bb-flat-table-row");
+ if (!wrapper) {
+ hoverState.update(undefined, "after", 150);
+ return;
+ }
+ const bounding = wrapper.getBoundingClientRect();
+ hoverState.setPosition({ x: e.clientX, y: bounding.bottom });
+ };
+
+ const handleMouseLeave = () => {
+ hoverState.update(undefined, "after");
+ };
+
+ if (filteredTables.length === 0) {
+ // Vue's source uses hardcoded English here; preserve verbatim for
+ // 1:1 parity. If we ever i18n this, update the Vue side at the same
+ // time so the two surfaces don't drift.
+ return (
+ <div className="flex flex-col items-center justify-center mt-16 text-control-light text-sm">
+ {search ? "No tables found" : "No tables in this database"}
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col h-full overflow-y-auto py-1">
+ {pagedTables.map((item, index) => {
+ const isExpanded = expanded.has(item.key);
+ return (
+ <div key={item.key}>
+ <div
+ className={cn(
+ "bb-flat-table-row px-2 py-1 cursor-pointer flex items-center justify-between text-sm",
+ "transition-colors hover:bg-control-bg/70",
+ selectedKey === item.key && "bg-accent/10 font-medium"
+ )}
+ onClick={() => {
+ setSelectedKey(item.key);
+ onSelect(item);
+ }}
+ onDoubleClick={() => {
+ setSelectedKey(item.key);
+ onSelectAll(item);
+ }}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ setSelectedKey(item.key);
+ onContextMenu(e, item);
+ }}
+ onMouseEnter={(e) => handleMouseEnter(e, item)}
+ onMouseLeave={handleMouseLeave}
+ >
+ <div className="flex items-center gap-1 truncate flex-1 min-w-0">
+ <TableIcon className="size-3.5 shrink-0" />
+ <span className="truncate">
+ {item.schema ? (
+ <span className="text-gray-500">{item.schema}.</span>
+ ) : null}
+ <span>{item.metadata.name}</span>
+ </span>
+ </div>
+ <div className="flex items-center gap-2 text-xs text-gray-500 shrink-0 ml-2">
+ <span>{item.metadata.columns.length} cols</span>
+ {item.metadata.columns.length > 0 ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="size-5"
+ onClick={(e) => {
+ e.stopPropagation();
+ setExpanded((prev) => {
+ const next = new Set(prev);
+ if (next.has(item.key)) {
+ next.delete(item.key);
+ } else {
+ next.add(item.key);
+ }
+ return next;
+ });
+ }}
+ >
+ {isExpanded ? (
+ <ChevronDown className="size-3" />
+ ) : (
+ <ChevronRight className="size-3" />
+ )}
+ </Button>
+ ) : null}
+ </div>
+ </div>
+
+ {isExpanded ? (
+ <div className="pl-4 pr-2 bg-gray-50 border-l-2 border-gray-200">
+ {item.metadata.columns.length > 0 ? (
+ <div className="py-1">
+ <div className="text-xs font-medium text-gray-600 mb-1">
+ {t("database.columns")}
+ </div>
+ {item.metadata.columns.map((column) => (
+ <div
+ key={column.name}
+ className="flex flex-wrap items-center justify-between gap-1 py-0.5 text-xs pl-2"
+ >
+ <div className="flex items-center gap-1">
+ <ColumnIcon className="size-3 text-gray-400" />
+ <span>{column.name}</span>
+ </div>
+ <span className="text-gray-500">{column.type}</span>
+ </div>
+ ))}
+ </div>
+ ) : null}
+ {item.metadata.indexes && item.metadata.indexes.length > 0 ? (
+ <div className="py-1 border-t border-gray-200">
+ <div className="text-xs font-medium text-gray-600 mb-1">
+ {t("database.indexes")}
+ </div>
+ {item.metadata.indexes.map((index) => (
+ <div
+ key={index.name}
+ className="flex flex-wrap items-center justify-between gap-1 py-0.5 text-xs pl-2"
+ >
+ <div className="flex items-center gap-1">
+ <IndexIcon className="size-3 text-gray-400" />
+ <span>{index.name}</span>
+ </div>
+ <span className="text-gray-500">
+ {index.unique ? "UNIQUE" : ""}{" "}
+ {index.primary ? "PRIMARY" : ""}
+ </span>
+ </div>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+
+ {index === pagedTables.length - 1 &&
+ (pageIndex + 1) * PAGE_SIZE < filteredTables.length ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="w-full"
+ onClick={() => setPageIndex((p) => p + 1)}
+ >
+ {t("common.load-more")}
+ </Button>
+ ) : null}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ColumnInfo.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ColumnInfo.tsx
new file mode 100644
index 0000000000..c739cc76ca
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ColumnInfo.tsx
@@ -0,0 +1,80 @@
+import { create } from "@bufbuild/protobuf";
+import { Check, X } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { getColumnDefaultValuePlaceholder } from "@/components/SchemaEditorLite/utils/columnDefaultValue";
+import { useVueState } from "@/react/hooks/useVueState";
+import { useDatabaseV1Store, useDBSchemaV1Store } from "@/store";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import { ColumnMetadataSchema } from "@/types/proto-es/v1/database_service_pb";
+import { getInstanceResource } from "@/utils";
+import { InfoItem } from "./InfoItem";
+
+type Props = {
+ readonly database: string;
+ readonly schema?: string;
+ readonly table: string;
+ readonly column: string;
+};
+
+/**
+ * Replaces `HoverPanel/ColumnInfo.vue`. Character set is shown only for
+ * Postgres / ClickHouse / Snowflake; collation only for ClickHouse /
+ * Snowflake (other engines surface these at the table level).
+ */
+export function ColumnInfo({ database, schema, table, column }: Props) {
+ const { t } = useTranslation();
+ const dbSchema = useDBSchemaV1Store();
+ const databaseStore = useDatabaseV1Store();
+
+ const columnMetadata = useVueState(
+ () =>
+ dbSchema
+ .getTableMetadata({ database, schema, table })
+ .columns.find((col) => col.name === column) ??
+ create(ColumnMetadataSchema, {})
+ );
+ const instanceEngine = useVueState(
+ () => getInstanceResource(databaseStore.getDatabaseByName(database)).engine
+ );
+
+ const characterSet =
+ instanceEngine === Engine.POSTGRES ||
+ instanceEngine === Engine.CLICKHOUSE ||
+ instanceEngine === Engine.SNOWFLAKE
+ ? columnMetadata.characterSet
+ : "";
+ const collation =
+ instanceEngine === Engine.CLICKHOUSE || instanceEngine === Engine.SNOWFLAKE
+ ? columnMetadata.collation
+ : "";
+
+ return (
+ <div className="min-w-56 max-w-[18rem] gap-y-1">
+ <InfoItem title={t("common.name")}>{columnMetadata.name}</InfoItem>
+ <InfoItem title={t("common.type")}>{columnMetadata.type}</InfoItem>
+ <InfoItem title={t("common.Default")}>
+ {getColumnDefaultValuePlaceholder(columnMetadata)}
+ </InfoItem>
+ <InfoItem title={t("database.nullable")}>
+ <div className="inline-flex items-center justify-end">
+ {columnMetadata.nullable ? (
+ <Check className="size-4" />
+ ) : (
+ <X className="size-4" />
+ )}
+ </div>
+ </InfoItem>
+ {characterSet ? (
+ <InfoItem title={t("db.character-set")}>{characterSet}</InfoItem>
+ ) : null}
+ {collation ? (
+ <InfoItem title={t("db.collation")}>{collation}</InfoItem>
+ ) : null}
+ {columnMetadata.comment ? (
+ <InfoItem title={t("database.comment")}>
+ {columnMetadata.comment}
+ </InfoItem>
+ ) : null}
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/CommonText.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/CommonText.tsx
new file mode 100644
index 0000000000..72590f3ff4
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/CommonText.tsx
@@ -0,0 +1,12 @@
+type Props = {
+ readonly content: string;
+};
+
+/** Replaces `HoverPanel/CommonText.vue`. Wraps long text to ~18rem. */
+export function CommonText({ content }: Props) {
+ return (
+ <div className="max-w-[18rem] whitespace-pre-wrap break-all wrap-break-word">
+ {content}
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ExternalTableInfo.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ExternalTableInfo.tsx
new file mode 100644
index 0000000000..9b356a4070
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ExternalTableInfo.tsx
@@ -0,0 +1,31 @@
+import { useTranslation } from "react-i18next";
+import { useVueState } from "@/react/hooks/useVueState";
+import { useDBSchemaV1Store } from "@/store";
+import { InfoItem } from "./InfoItem";
+
+type Props = {
+ readonly database: string;
+ readonly schema?: string;
+ readonly externalTable: string;
+};
+
+/** Replaces `HoverPanel/ExternalTableInfo.vue`. */
+export function ExternalTableInfo({ database, schema, externalTable }: Props) {
+ const { t } = useTranslation();
+ const dbSchema = useDBSchemaV1Store();
+ const externalTableMetadata = useVueState(() =>
+ dbSchema.getExternalTableMetadata({ database, schema, externalTable })
+ );
+
+ return (
+ <div className="min-w-56 max-w-[18rem] gap-y-1">
+ <InfoItem title={t("common.name")}>{externalTableMetadata.name}</InfoItem>
+ <InfoItem title={t("database.external-server-name")}>
+ {externalTableMetadata.externalServerName}
+ </InfoItem>
+ <InfoItem title={t("database.external-database-name")}>
+ {externalTableMetadata.externalDatabaseName}
+ </InfoItem>
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/HoverPanel.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/HoverPanel.test.tsx
new file mode 100644
index 0000000000..70ba4900fe
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/HoverPanel.test.tsx
@@ -0,0 +1,190 @@
+import { act, type ReactElement } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import type { HoverState } from "../hover-state";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+// jsdom doesn't ship ResizeObserver. Stub it before HoverPanel is imported
+// so its `useLayoutEffect` can wire up without exploding. The stub
+// matches the real-DOM signature so TS type-check is happy.
+class StubResizeObserver implements ResizeObserver {
+ constructor(_cb: ResizeObserverCallback) {}
+ observe(): void {}
+ unobserve(): void {}
+ disconnect(): void {}
+}
+(
+ globalThis as unknown as { ResizeObserver: typeof ResizeObserver }
+).ResizeObserver = StubResizeObserver as unknown as typeof ResizeObserver;
+
+const hoverState: {
+ state: HoverState | undefined;
+ position: { x: number; y: number };
+ update: ReturnType<typeof vi.fn>;
+} = {
+ state: undefined,
+ position: { x: 0, y: 0 },
+ update: vi.fn(),
+};
+
+vi.mock("../hover-state", () => ({
+ useHoverState: () => ({
+ state: hoverState.state,
+ position: hoverState.position,
+ update: hoverState.update,
+ setPosition: vi.fn(),
+ cancel: vi.fn(),
+ }),
+}));
+
+vi.mock("./ColumnInfo", () => ({
+ ColumnInfo: () => <div data-testid="ColumnInfo" />,
+}));
+vi.mock("./TableInfo", () => ({
+ TableInfo: () => <div data-testid="TableInfo" />,
+}));
+vi.mock("./TablePartitionInfo", () => ({
+ TablePartitionInfo: () => <div data-testid="TablePartitionInfo" />,
+}));
+vi.mock("./ExternalTableInfo", () => ({
+ ExternalTableInfo: () => <div data-testid="ExternalTableInfo" />,
+}));
+vi.mock("./ViewInfo", () => ({
+ ViewInfo: () => <div data-testid="ViewInfo" />,
+}));
+
+vi.mock("@/react/components/ui/layer", () => ({
+ LAYER_SURFACE_CLASS: "test-layer",
+ getLayerRoot: () => document.body,
+}));
+
+vi.mock("@/utils", () => ({
+ minmax: (value: number, min: number, max: number) =>
+ Math.max(min, Math.min(max, value)),
+}));
+
+let HoverPanel: typeof import("./HoverPanel").HoverPanel;
+
+const renderInto = (element: ReactElement) => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ act(() => {
+ root.render(element);
+ });
+ return {
+ container,
+ unmount: () => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ },
+ };
+};
+
+beforeEach(async () => {
+ hoverState.state = undefined;
+ hoverState.position = { x: 0, y: 0 };
+ hoverState.update.mockReset();
+ ({ HoverPanel } = await import("./HoverPanel"));
+});
+
+afterEach(() => {
+ // Each render mounts the panel into document.body via the layer-root
+ // mock. Sweep any leftover panels so the next test sees a clean DOM.
+ document.body.innerHTML = "";
+});
+
+describe("HoverPanel dispatch", () => {
+ test("renders nothing when state is undefined", () => {
+ const { container } = renderInto(
+ <HoverPanel offsetX={0} offsetY={0} margin={4} />
+ );
+ expect(container.querySelector("[data-testid]")).toBeNull();
+ expect(document.querySelector("[data-testid]")).toBeNull();
+ });
+
+ test("column + table → ColumnInfo", () => {
+ hoverState.state = { database: "db", table: "users", column: "id" };
+ hoverState.position = { x: 10, y: 20 };
+ renderInto(<HoverPanel offsetX={0} offsetY={0} margin={4} />);
+ expect(document.querySelector('[data-testid="ColumnInfo"]')).not.toBeNull();
+ });
+
+ test("table + partition → TablePartitionInfo", () => {
+ hoverState.state = { database: "db", table: "events", partition: "p1" };
+ hoverState.position = { x: 10, y: 20 };
+ renderInto(<HoverPanel offsetX={0} offsetY={0} margin={4} />);
+ expect(
+ document.querySelector('[data-testid="TablePartitionInfo"]')
+ ).not.toBeNull();
+ });
+
+ test("table only → TableInfo", () => {
+ hoverState.state = { database: "db", table: "users" };
+ hoverState.position = { x: 10, y: 20 };
+ renderInto(<HoverPanel offsetX={0} offsetY={0} margin={4} />);
+ expect(document.querySelector('[data-testid="TableInfo"]')).not.toBeNull();
+ });
+
+ test("externalTable → ExternalTableInfo", () => {
+ hoverState.state = { database: "db", externalTable: "ext" };
+ hoverState.position = { x: 10, y: 20 };
+ renderInto(<HoverPanel offsetX={0} offsetY={0} margin={4} />);
+ expect(
+ document.querySelector('[data-testid="ExternalTableInfo"]')
+ ).not.toBeNull();
+ });
+
+ test("view → ViewInfo", () => {
+ hoverState.state = { database: "db", view: "v" };
+ hoverState.position = { x: 10, y: 20 };
+ renderInto(<HoverPanel offsetX={0} offsetY={0} margin={4} />);
+ expect(document.querySelector('[data-testid="ViewInfo"]')).not.toBeNull();
+ });
+});
+
+describe("HoverPanel clamp + invisibility", () => {
+ test("offsets are applied to the cursor position", () => {
+ hoverState.state = { database: "db", table: "t" };
+ hoverState.position = { x: 100, y: 200 };
+ Object.defineProperty(window, "innerHeight", {
+ configurable: true,
+ value: 1000,
+ });
+ renderInto(<HoverPanel offsetX={4} offsetY={8} margin={4} />);
+ const panel = document.querySelector(".test-layer") as HTMLElement | null;
+ expect(panel).not.toBeNull();
+ expect(panel!.style.left).toBe("104px");
+ expect(panel!.style.top).toBe("208px");
+ });
+
+ test("y is clamped to (margin … innerHeight - popoverHeight - margin)", () => {
+ hoverState.state = { database: "db", table: "t" };
+ hoverState.position = { x: 0, y: 9999 };
+ Object.defineProperty(window, "innerHeight", {
+ configurable: true,
+ value: 600,
+ });
+ renderInto(<HoverPanel offsetX={0} offsetY={0} margin={4} />);
+ const panel = document.querySelector(".test-layer") as HTMLElement | null;
+ // popoverHeight defaults to 0 in jsdom, so the upper bound is
+ // 600 - 0 - 4 = 596. The clamp pulls 9999 down to 596.
+ expect(panel!.style.top).toBe("596px");
+ });
+
+ test("position (0,0) renders the panel as invisible", () => {
+ hoverState.state = { database: "db", table: "t" };
+ hoverState.position = { x: 0, y: 0 };
+ renderInto(<HoverPanel offsetX={0} offsetY={0} margin={4} />);
+ const panel = document.querySelector(".test-layer") as HTMLElement | null;
+ expect(panel).not.toBeNull();
+ // `show` is false → "invisible pointer-events-none" classes are on.
+ expect(panel!.className).toContain("invisible");
+ expect(panel!.className).toContain("pointer-events-none");
+ });
+});
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/HoverPanel.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/HoverPanel.tsx
new file mode 100644
index 0000000000..8f234f7906
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/HoverPanel.tsx
@@ -0,0 +1,159 @@
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { createPortal } from "react-dom";
+import { getLayerRoot, LAYER_SURFACE_CLASS } from "@/react/components/ui/layer";
+import { cn } from "@/react/lib/utils";
+import type { Position } from "@/types";
+import { minmax } from "@/utils";
+import { useHoverState } from "../hover-state";
+import { ColumnInfo } from "./ColumnInfo";
+import { ExternalTableInfo } from "./ExternalTableInfo";
+import { TableInfo } from "./TableInfo";
+import { TablePartitionInfo } from "./TablePartitionInfo";
+import { ViewInfo } from "./ViewInfo";
+
+type Props = {
+ readonly offsetX: number;
+ readonly offsetY: number;
+ readonly margin: number;
+ readonly onClickOutside?: (e: MouseEvent) => void;
+};
+
+/**
+ * Replaces `HoverPanel/HoverPanel.vue`. Floating, cursor-anchored panel
+ * that previews schema metadata for the hovered tree row. Mirrors Vue's
+ * `v-if` chain — most-specific shape wins:
+ * column + table → ColumnInfo
+ * table + partition → TablePartitionInfo
+ * table → TableInfo
+ * externalTable → ExternalTableInfo
+ * view → ViewInfo
+ *
+ * Position is driven by `useHoverState()`'s sparse `state` + cursor
+ * `position`. The y coordinate is clamped so the panel never escapes the
+ * viewport. Mounted into the shared overlay layer via a portal so the
+ * absolute coords are document-relative regardless of where SchemaPane
+ * lives in the DOM.
+ *
+ * Hover-keep: mouseenter on the panel itself reschedules the open delay
+ * to 50ms so the panel doesn't flash off when the cursor crosses from a
+ * row onto the panel. mouseleave triggers the standard 350ms close.
+ */
+export function HoverPanel({
+ offsetX,
+ offsetY,
+ margin,
+ onClickOutside,
+}: Props) {
+ const { state, position, update } = useHoverState();
+ const popoverRef = useRef<HTMLDivElement | null>(null);
+ const [popoverHeight, setPopoverHeight] = useState(0);
+
+ useLayoutEffect(() => {
+ const el = popoverRef.current;
+ if (!el) return;
+ setPopoverHeight(el.getBoundingClientRect().height);
+ const ro = new ResizeObserver(() => {
+ setPopoverHeight(el.getBoundingClientRect().height);
+ });
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [state]);
+
+ const show = state !== undefined && position.x !== 0 && position.y !== 0;
+
+ const displayPosition = useMemo<Position>(() => {
+ const p: Position = {
+ x: position.x + offsetX,
+ y: position.y + offsetY,
+ };
+ if (typeof window !== "undefined") {
+ const yMin = margin;
+ const yMax = window.innerHeight - popoverHeight - margin;
+ p.y = minmax(p.y, yMin, yMax);
+ }
+ return p;
+ }, [position, offsetX, offsetY, margin, popoverHeight]);
+
+ useEffect(() => {
+ if (!show || !onClickOutside) return;
+ const handler = (e: MouseEvent) => {
+ const el = popoverRef.current;
+ if (el && !el.contains(e.target as Node)) {
+ onClickOutside(e);
+ }
+ };
+ document.addEventListener("mousedown", handler);
+ return () => document.removeEventListener("mousedown", handler);
+ }, [show, onClickOutside]);
+
+ // Render nothing at all when there's no state to show — avoids a stray
+ // 0×0 element sitting at top-left until the user hovers something.
+ if (!state) return null;
+
+ let body: React.ReactNode = null;
+ if (state.column && state.table) {
+ body = (
+ <ColumnInfo
+ database={state.database}
+ schema={state.schema}
+ table={state.table}
+ column={state.column}
+ />
+ );
+ } else if (state.table && state.partition) {
+ body = (
+ <TablePartitionInfo
+ database={state.database}
+ schema={state.schema}
+ table={state.table}
+ partition={state.partition}
+ />
+ );
+ } else if (state.table) {
+ body = (
+ <TableInfo
+ database={state.database}
+ schema={state.schema}
+ table={state.table}
+ />
+ );
+ } else if (state.externalTable) {
+ body = (
+ <ExternalTableInfo
+ database={state.database}
+ schema={state.schema}
+ externalTable={state.externalTable}
+ />
+ );
+ } else if (state.view) {
+ body = (
+ <ViewInfo
+ database={state.database}
+ schema={state.schema}
+ view={state.view}
+ />
+ );
+ }
+
+ const panel = (
+ <div
+ ref={popoverRef}
+ className={cn(
+ "fixed border border-gray-100 rounded-sm bg-white p-2 shadow-sm transition-[top] text-sm",
+ LAYER_SURFACE_CLASS,
+ !show && "invisible pointer-events-none"
+ )}
+ style={{
+ left: `${displayPosition.x}px`,
+ top: `${displayPosition.y}px`,
+ }}
+ onMouseEnter={() => update(state, "before", 50)}
+ onMouseLeave={() => update(undefined, "after")}
+ >
+ {body}
+ </div>
+ );
+
+ if (typeof document === "undefined") return null;
+ return createPortal(panel, getLayerRoot("overlay"));
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/InfoItem.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/InfoItem.tsx
new file mode 100644
index 0000000000..4551c641d6
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/InfoItem.tsx
@@ -0,0 +1,32 @@
+import type { ReactNode } from "react";
+
+type Props = {
+ readonly title?: string;
+ readonly titleSlot?: ReactNode;
+ readonly children: ReactNode;
+};
+
+/**
+ * Replaces `HoverPanel/InfoItem.vue`. A 2-column grid row: gray title on
+ * the left, value (right-aligned, ellipsis on overflow) on the right.
+ *
+ * Mirrors the Vue layout — `grid-template-columns: auto 1fr` + 16px gap
+ * — so the title hugs its content and the value column truncates.
+ */
+export function InfoItem({ title, titleSlot, children }: Props) {
+ return (
+ <div
+ className="w-full grid gap-x-4 items-center"
+ style={{ gridTemplateColumns: "auto 1fr" }}
+ >
+ <div className="text-gray-500 font-medium whitespace-nowrap">
+ {titleSlot ?? title}
+ </div>
+ <div className="text-right flex items-center justify-end min-w-0">
+ <span className="truncate flex items-center leading-[20px] h-[20px]">
+ {children}
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TableInfo.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TableInfo.tsx
new file mode 100644
index 0000000000..5bc840209a
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TableInfo.tsx
@@ -0,0 +1,73 @@
+import { useTranslation } from "react-i18next";
+import { EngineIconPath } from "@/components/InstanceForm/constants";
+import { useVueState } from "@/react/hooks/useVueState";
+import { useDatabaseV1Store, useDBSchemaV1Store } from "@/store";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import { bytesToString, getInstanceResource } from "@/utils";
+import { engineNameV1 } from "@/utils/v1/instance";
+import { InfoItem } from "./InfoItem";
+
+type Props = {
+ readonly database: string;
+ readonly schema?: string;
+ readonly table: string;
+};
+
+/**
+ * Replaces `HoverPanel/TableInfo.vue`. Index size and collation are
+ * hidden for ClickHouse + Snowflake; collation is also hidden for
+ * Postgres because the engine reports it at the column level instead of
+ * the table level. Comment is shown only when present.
+ */
+export function TableInfo({ database, schema, table }: Props) {
+ const { t } = useTranslation();
+ const dbSchema = useDBSchemaV1Store();
+ const databaseStore = useDatabaseV1Store();
+
+ const tableMetadata = useVueState(() =>
+ dbSchema.getTableMetadata({ database, schema, table })
+ );
+ const instanceEngine = useVueState(
+ () => getInstanceResource(databaseStore.getDatabaseByName(database)).engine
+ );
+
+ const indexSize =
+ instanceEngine === Engine.CLICKHOUSE || instanceEngine === Engine.SNOWFLAKE
+ ? ""
+ : bytesToString(Number(tableMetadata.indexSize));
+ const collation =
+ instanceEngine === Engine.CLICKHOUSE ||
+ instanceEngine === Engine.SNOWFLAKE ||
+ instanceEngine === Engine.POSTGRES
+ ? ""
+ : tableMetadata.collation;
+ const comment = tableMetadata.comment;
+ const iconPath = EngineIconPath[instanceEngine];
+
+ return (
+ <div className="min-w-56 max-w-[18rem] gap-y-1">
+ <InfoItem title={t("common.name")}>{tableMetadata.name}</InfoItem>
+ <InfoItem title={t("database.engine")}>
+ <span className="flex items-center gap-x-0.5">
+ {iconPath ? <img src={iconPath} alt="" className="size-4" /> : null}
+ {engineNameV1(instanceEngine)}
+ </span>
+ </InfoItem>
+ <InfoItem title={t("database.row-count-estimate")}>
+ {String(tableMetadata.rowCount)}
+ </InfoItem>
+ <InfoItem title={t("database.data-size")}>
+ {bytesToString(Number(tableMetadata.dataSize))}
+ </InfoItem>
+ {indexSize ? (
+ <InfoItem title={t("database.index-size")}>{indexSize}</InfoItem>
+ ) : null}
+ {collation ? (
+ <InfoItem title={t("db.collation")}>{collation}</InfoItem>
+ ) : null}
+ {comment ? (
+ <InfoItem title={t("database.comment")}>{comment}</InfoItem>
+ ) : null}
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TablePartitionInfo.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TablePartitionInfo.tsx
new file mode 100644
index 0000000000..2e5a60446d
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TablePartitionInfo.tsx
@@ -0,0 +1,50 @@
+import { create } from "@bufbuild/protobuf";
+import { useTranslation } from "react-i18next";
+import { useVueState } from "@/react/hooks/useVueState";
+import { useDBSchemaV1Store } from "@/store";
+import {
+ TablePartitionMetadata_Type,
+ TablePartitionMetadataSchema,
+} from "@/types/proto-es/v1/database_service_pb";
+import { InfoItem } from "./InfoItem";
+
+type Props = {
+ readonly database: string;
+ readonly schema?: string;
+ readonly table: string;
+ readonly partition: string;
+};
+
+/** Replaces `HoverPanel/TablePartitionInfo.vue`. */
+export function TablePartitionInfo({
+ database,
+ schema,
+ table,
+ partition,
+}: Props) {
+ const { t } = useTranslation();
+ const dbSchema = useDBSchemaV1Store();
+
+ const partitionMetadata = useVueState(
+ () =>
+ dbSchema
+ .getTableMetadata({ database, schema, table })
+ .partitions.find((p) => p.name === partition) ??
+ create(TablePartitionMetadataSchema, {})
+ );
+
+ return (
+ <div className="min-w-56 max-w-[18rem] gap-y-1">
+ <InfoItem title={t("common.name")}>{partitionMetadata.name}</InfoItem>
+ <InfoItem title={t("schema-editor.table-partition.type")}>
+ {TablePartitionMetadata_Type[partitionMetadata.type]}
+ </InfoItem>
+ <InfoItem title={t("schema-editor.table-partition.expression")}>
+ <code>{partitionMetadata.expression}</code>
+ </InfoItem>
+ <InfoItem title={t("schema-editor.table-partition.value")}>
+ {partitionMetadata.value}
+ </InfoItem>
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ViewInfo.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ViewInfo.tsx
new file mode 100644
index 0000000000..8f3b8d80c3
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ViewInfo.tsx
@@ -0,0 +1,18 @@
+import { useVueState } from "@/react/hooks/useVueState";
+import { useDBSchemaV1Store } from "@/store";
+import { CommonText } from "./CommonText";
+
+type Props = {
+ readonly database: string;
+ readonly schema?: string;
+ readonly view: string;
+};
+
+/** Replaces `HoverPanel/ViewInfo.vue`. Just the view's comment, wrapped. */
+export function ViewInfo({ database, schema, view }: Props) {
+ const dbSchema = useDBSchemaV1Store();
+ const viewMetadata = useVueState(() =>
+ dbSchema.getViewMetadata({ database, schema, view })
+ );
+ return <CommonText content={viewMetadata.comment} />;
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SchemaContextMenu.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SchemaContextMenu.test.tsx
new file mode 100644
index 0000000000..fa46e56a23
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/SchemaContextMenu.test.tsx
@@ -0,0 +1,184 @@
+import { act, createRef, type ReactElement } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import type { TreeNode } from "./schemaTree";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ useSchemaPaneContextMenu: vi.fn(),
+}));
+
+vi.mock("./actions", () => ({
+ useSchemaPaneContextMenu: mocks.useSchemaPaneContextMenu,
+}));
+
+vi.mock("@/react/components/ui/dropdown-menu", () => ({
+ DropdownMenu: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="dropdown-menu">{children}</div>
+ ),
+ DropdownMenuContent: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="dropdown-content">{children}</div>
+ ),
+ DropdownMenuItem: ({
+ children,
+ onClick,
+ }: {
+ children: React.ReactNode;
+ onClick?: () => void;
+ }) => (
+ <button data-testid="dropdown-item" onClick={onClick} type="button">
+ {children}
+ </button>
+ ),
+ DropdownMenuSubmenu: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="dropdown-submenu">{children}</div>
+ ),
+ DropdownMenuSubmenuContent: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="dropdown-submenu-content">{children}</div>
+ ),
+ DropdownMenuSubmenuTrigger: ({ children }: { children: React.ReactNode }) => (
+ <button data-testid="dropdown-submenu-trigger" type="button">
+ {children}
+ </button>
+ ),
+}));
+
+vi.mock("@base-ui/react/menu", () => ({
+ Menu: {
+ Trigger: ({
+ ref,
+ ...rest
+ }: {
+ ref?: React.Ref<HTMLButtonElement>;
+ } & React.HTMLAttributes<HTMLButtonElement>) => (
+ <button ref={ref} data-testid="menu-trigger" {...rest} />
+ ),
+ },
+}));
+
+let SchemaContextMenu: typeof import("./SchemaContextMenu").SchemaContextMenu;
+type Handle = import("./SchemaContextMenu").SchemaContextMenuHandle;
+
+const renderInto = (element: ReactElement) => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ return {
+ container,
+ render: () => act(() => root.render(element)),
+ unmount: () => {
+ act(() => root.unmount());
+ container.remove();
+ },
+ };
+};
+
+const makeNode = (): TreeNode =>
+ ({
+ key: "table/users",
+ meta: {
+ type: "table",
+ target: {
+ database: "instances/i/databases/db",
+ schema: "",
+ table: "users",
+ },
+ },
+ }) as unknown as TreeNode;
+
+const noopDeps = {
+ availableActions: [],
+ setSchemaViewer: () => {},
+};
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ ({ SchemaContextMenu } = await import("./SchemaContextMenu"));
+});
+
+describe("SchemaContextMenu", () => {
+ test("renders nothing when the menu hook returns no items", () => {
+ mocks.useSchemaPaneContextMenu.mockReturnValue([]);
+ const ref = createRef<Handle>();
+ const { container, render, unmount } = renderInto(
+ <SchemaContextMenu ref={ref} {...noopDeps} />
+ );
+ render();
+ expect(container.textContent).toBe("");
+ unmount();
+ });
+
+ test("renders one item per hook result and clicking invokes onSelect", () => {
+ const select = vi.fn();
+ mocks.useSchemaPaneContextMenu.mockReturnValue([
+ { key: "copy-name", label: "Copy", icon: null, onSelect: select },
+ ]);
+ const ref = createRef<Handle>();
+ const { container, render, unmount } = renderInto(
+ <SchemaContextMenu ref={ref} {...noopDeps} />
+ );
+ render();
+ // Force a show so the hook is called with a non-null node.
+ act(() => {
+ ref.current?.show(makeNode(), {
+ preventDefault: () => {},
+ stopPropagation: () => {},
+ clientX: 10,
+ clientY: 20,
+ } as React.MouseEvent);
+ });
+ const items = container.querySelectorAll("[data-testid='dropdown-item']");
+ expect(items.length).toBe(1);
+ act(() => {
+ (items[0] as HTMLButtonElement).dispatchEvent(
+ new MouseEvent("click", { bubbles: true })
+ );
+ });
+ expect(select).toHaveBeenCalled();
+ unmount();
+ });
+
+ test("renders nested submenu for items with children", () => {
+ mocks.useSchemaPaneContextMenu.mockReturnValue([
+ {
+ key: "generate-sql",
+ label: "Generate SQL",
+ icon: null,
+ children: [
+ {
+ key: "generate-sql--select",
+ label: "SELECT",
+ icon: null,
+ onSelect: vi.fn(),
+ },
+ ],
+ },
+ ]);
+ const ref = createRef<Handle>();
+ const { container, render, unmount } = renderInto(
+ <SchemaContextMenu ref={ref} {...noopDeps} />
+ );
+ render();
+ act(() => {
+ ref.current?.show(makeNode(), {
+ preventDefault: () => {},
+ stopPropagation: () => {},
+ clientX: 0,
+ clientY: 0,
+ } as React.MouseEvent);
+ });
+ expect(
+ container.querySelector("[data-testid='dropdown-submenu']")
+ ).not.toBeNull();
+ expect(
+ container.querySelector("[data-testid='dropdown-submenu-trigger']")
+ ).not.toBeNull();
+ expect(
+ container.querySelector("[data-testid='dropdown-submenu-content']")
+ ).not.toBeNull();
+ unmount();
+ });
+});
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SchemaContextMenu.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SchemaContextMenu.tsx
new file mode 100644
index 0000000000..f5d60239b4
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/SchemaContextMenu.tsx
@@ -0,0 +1,140 @@
+import { Menu as BaseMenu } from "@base-ui/react/menu";
+import { forwardRef, useImperativeHandle, useRef, useState } from "react";
+import { flushSync } from "react-dom";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSubmenu,
+ DropdownMenuSubmenuContent,
+ DropdownMenuSubmenuTrigger,
+} from "@/react/components/ui/dropdown-menu";
+import {
+ type SchemaMenuDeps,
+ type SchemaMenuItem,
+ useSchemaPaneContextMenu,
+} from "./actions";
+import type { TreeNode } from "./schemaTree";
+
+export type SchemaContextMenuHandle = {
+ show: (node: TreeNode, e: React.MouseEvent) => void;
+ hide: () => void;
+};
+
+type Target = {
+ x: number;
+ y: number;
+ node: TreeNode;
+};
+
+type Props = SchemaMenuDeps;
+
+/**
+ * Replaces `SchemaPane/actions.tsx`'s NDropdown imperative use in
+ * `SchemaPane.vue`. Mirrors the Stage 14 `ConnectionContextMenu` pattern:
+ * a 0×0 fixed-position trigger at the cursor is programmatically clicked
+ * so Base UI records a click-type open event and the popup stays open
+ * while the pointer moves to a menu item.
+ *
+ * `open` is controlled so `hide()` can dismiss the menu deterministically
+ * (matches the same fix applied to TabContextMenu after the codex review).
+ */
+export const SchemaContextMenu = forwardRef<SchemaContextMenuHandle, Props>(
+ function SchemaContextMenu(deps, ref) {
+ const [target, setTarget] = useState<Target | null>(null);
+ const [open, setOpen] = useState(false);
+ const triggerRef = useRef<HTMLButtonElement>(null);
+
+ const items = useSchemaPaneContextMenu(target?.node ?? null, deps);
+
+ useImperativeHandle(
+ ref,
+ () => ({
+ show(node, e) {
+ e.preventDefault();
+ e.stopPropagation();
+ flushSync(() => {
+ setTarget({ x: e.clientX, y: e.clientY, node });
+ });
+ triggerRef.current?.click();
+ },
+ hide() {
+ setOpen(false);
+ setTarget(null);
+ },
+ }),
+ []
+ );
+
+ if (items.length === 0) return null;
+
+ return (
+ <DropdownMenu
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next);
+ if (!next) setTarget(null);
+ }}
+ >
+ <BaseMenu.Trigger
+ ref={triggerRef}
+ aria-hidden
+ tabIndex={-1}
+ render={
+ <button
+ type="button"
+ style={{
+ position: "fixed",
+ top: target?.y ?? 0,
+ left: target?.x ?? 0,
+ width: 0,
+ height: 0,
+ pointerEvents: "none",
+ opacity: 0,
+ }}
+ />
+ }
+ />
+ <DropdownMenuContent
+ align="start"
+ sideOffset={4}
+ positionMethod="fixed"
+ >
+ {items.map((item) => renderItem(item, () => setOpen(false)))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+ }
+);
+
+function renderItem(item: SchemaMenuItem, close: () => void) {
+ if (item.children && item.children.length > 0) {
+ return (
+ <DropdownMenuSubmenu key={item.key}>
+ <DropdownMenuSubmenuTrigger>
+ <span className="inline-flex items-center gap-x-2">
+ {item.icon}
+ {item.label}
+ </span>
+ </DropdownMenuSubmenuTrigger>
+ <DropdownMenuSubmenuContent>
+ {item.children.map((child) => renderItem(child, close))}
+ </DropdownMenuSubmenuContent>
+ </DropdownMenuSubmenu>
+ );
+ }
+ return (
+ <DropdownMenuItem
+ key={item.key}
+ onClick={() => {
+ item.onSelect?.();
+ close();
+ }}
+ >
+ <span className="inline-flex items-center gap-x-2">
+ {item.icon}
+ {item.label}
+ </span>
+ </DropdownMenuItem>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx
new file mode 100644
index 0000000000..eb00dc6c28
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx
@@ -0,0 +1,278 @@
+import { act, type ReactElement } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+class StubResizeObserver implements ResizeObserver {
+ constructor(_cb: ResizeObserverCallback) {}
+ observe(): void {}
+ unobserve(): void {}
+ disconnect(): void {}
+}
+(
+ globalThis as unknown as { ResizeObserver: typeof ResizeObserver }
+).ResizeObserver = StubResizeObserver as unknown as typeof ResizeObserver;
+
+const mocks = vi.hoisted(() => ({
+ databaseRefValue: { name: "" } as {
+ name: string;
+ instanceResource?: unknown;
+ },
+ instanceRefValue: { engine: 1 },
+ currentTab: null as unknown,
+ getOrFetchDatabaseMetadata: vi
+ .fn()
+ .mockResolvedValue({ name: "instances/i/databases/db", schemas: [] }),
+ isValidDatabaseName: vi.fn(() => false),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (k: string) => k, i18n: { language: "en-US" } }),
+ Trans: ({ i18nKey }: { i18nKey: string }) => <span>{i18nKey}</span>,
+ initReactI18next: { type: "3rdParty", init: () => {} },
+}));
+
+vi.mock("@/react/i18n", () => ({
+ default: { t: (k: string) => k },
+}));
+
+vi.mock("@/store", () => ({
+ useSQLEditorTabStore: () => ({
+ currentTab: mocks.currentTab,
+ openTabList: [],
+ addTab: vi.fn(),
+ setCurrentTabId: vi.fn(),
+ updateCurrentTab: vi.fn(),
+ updateTab: vi.fn(),
+ }),
+ useDBSchemaV1Store: () => ({
+ getOrFetchDatabaseMetadata: mocks.getOrFetchDatabaseMetadata,
+ syncDatabase: vi.fn(),
+ getTableMetadata: vi.fn(),
+ }),
+ useDatabaseV1Store: () => ({ getDatabaseByName: vi.fn() }),
+ useConnectionOfCurrentSQLEditorTab: () => ({
+ database: { value: mocks.databaseRefValue },
+ instance: { value: mocks.instanceRefValue },
+ }),
+ pushNotification: vi.fn(),
+}));
+
+vi.mock("@/types", () => ({
+ isValidDatabaseName: mocks.isValidDatabaseName,
+ DEFAULT_SQL_EDITOR_TAB_MODE: "WORKSHEET",
+ dialectOfEngineV1: () => "MYSQL",
+ languageOfEngineV1: () => "sql",
+ typeToView: (type: string) => type.toUpperCase(),
+ getDateForPbTimestampProtoEs: () => undefined,
+}));
+
+vi.mock("@/types/proto-es/v1/common_pb", () => ({
+ Engine: { REDIS: 7, MYSQL: 1 },
+}));
+
+vi.mock("@/types/proto-es/v1/database_service_pb", () => ({
+ GetSchemaStringRequest_ObjectType: { TABLE: 1, VIEW: 2 },
+}));
+
+vi.mock("@/types/sqlEditor/tabViewState", () => ({
+ defaultViewState: () => ({ view: "CODE" }),
+}));
+
+vi.mock("@/utils", () => ({
+ defaultSQLEditorTab: () => ({
+ id: "n",
+ title: "",
+ connection: { instance: "", database: "" },
+ viewState: { view: "CODE" },
+ treeState: { database: "", keys: [] },
+ editorState: { selection: null },
+ mode: "WORKSHEET",
+ status: "NEW",
+ }),
+ extractDatabaseResourceName: (n: string) => ({
+ instance: "instances/i",
+ databaseName: n.split("/").pop() ?? "",
+ }),
+ extractInstanceResourceName: (n: string) => n,
+ extractProjectResourceName: (n: string) => n,
+ generateSimpleDeleteStatement: () => "",
+ generateSimpleInsertStatement: () => "",
+ generateSimpleSelectAllStatement: () => "",
+ generateSimpleUpdateStatement: () => "",
+ getInstanceResource: () => ({ engine: 1 }),
+ instanceV1HasAlterSchema: () => false,
+ isSameSQLEditorConnection: () => false,
+ sortByDictionary: () => {},
+ supportGetStringSchema: () => false,
+ isDev: () => false,
+ bytesToString: (n: number) => `${n} B`,
+ minmax: (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v)),
+ instanceV1Name: (i: { title?: string }) => i.title ?? "",
+}));
+
+vi.mock("@/utils/dom", () => ({
+ findAncestor: () => null,
+}));
+
+vi.mock("@/utils/v1/instance", () => ({
+ instanceV1SupportsExternalTable: () => false,
+ instanceV1SupportsPackage: () => false,
+ instanceV1SupportsSequence: () => false,
+}));
+
+vi.mock("@/router", () => ({ router: { resolve: () => ({ href: "/" }) } }));
+vi.mock("@/router/sqlEditor", () => ({
+ SQL_EDITOR_DATABASE_MODULE: "sql-editor.database",
+}));
+vi.mock("@/views/sql-editor/EditorCommon/utils", () => ({
+ keyWithPosition: (k: string, p: number) => `${k}###${p}`,
+}));
+vi.mock("@/views/sql-editor/events", () => ({
+ sqlEditorEvents: { emit: vi.fn(), on: vi.fn(() => () => {}) },
+}));
+vi.mock("@/composables/useExecuteSQL", () => ({
+ useExecuteSQL: () => ({ execute: vi.fn() }),
+}));
+vi.mock("@/components/MonacoEditor/sqlFormatter", () => ({
+ default: async (sql: string) => ({ data: sql, error: null }),
+}));
+
+vi.mock("@/react/components/HumanizeTs", () => ({
+ HumanizeTs: () => <span />,
+}));
+
+vi.mock("@/react/components/ui/input", () => ({
+ Input: (props: React.InputHTMLAttributes<HTMLInputElement>) => (
+ <input data-testid="search-input" {...props} />
+ ),
+}));
+
+vi.mock("@/react/components/ui/button", () => ({
+ Button: ({
+ children,
+ onClick,
+ disabled,
+ }: {
+ children: React.ReactNode;
+ onClick?: () => void;
+ disabled?: boolean;
+ }) => (
+ <button type="button" disabled={disabled} onClick={onClick}>
+ {children}
+ </button>
+ ),
+}));
+
+vi.mock("@/react/components/ui/tooltip", () => ({
+ Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+}));
+
+vi.mock("@/react/components/ui/dropdown-menu", () => ({
+ DropdownMenu: () => null,
+ DropdownMenuContent: () => null,
+ DropdownMenuItem: () => null,
+ DropdownMenuSubmenu: () => null,
+ DropdownMenuSubmenuContent: () => null,
+ DropdownMenuSubmenuTrigger: () => null,
+}));
+
+vi.mock("@/react/components/ui/dialog", () => ({
+ Dialog: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+ DialogContent: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DialogTitle: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+}));
+
+vi.mock("@/react/components/TableSchemaViewer", () => ({
+ TableSchemaViewer: () => <div data-testid="table-schema-viewer" />,
+}));
+
+vi.mock("@/components/InstanceForm/constants", () => ({
+ EngineIconPath: { MYSQL: "/mysql.svg" } as Record<string, string>,
+}));
+
+vi.mock("@base-ui/react/menu", () => ({
+ Menu: { Trigger: () => null },
+}));
+
+vi.mock("@/react/components/ui/layer", () => ({
+ LAYER_SURFACE_CLASS: "",
+ getLayerRoot: () => document.body,
+}));
+
+vi.mock("@/react/components/ui/tree", () => ({
+ Tree: () => <div data-testid="tree" />,
+}));
+
+vi.mock("@/react/components/ui/tree-utils", () => ({
+ countVisibleRows: () => 0,
+}));
+
+vi.mock("@/react/hooks/useVueState", () => ({
+ useVueState: <T,>(getter: () => T): T => getter(),
+}));
+
+let SchemaPane: typeof import("./SchemaPane").SchemaPane;
+
+const renderInto = (element: ReactElement) => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ return {
+ container,
+ render: () => act(() => root.render(element)),
+ unmount: () => {
+ act(() => root.unmount());
+ container.remove();
+ },
+ };
+};
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ mocks.databaseRefValue = { name: "" };
+ mocks.currentTab = null;
+ mocks.isValidDatabaseName.mockReturnValue(false);
+ ({ SchemaPane } = await import("./SchemaPane"));
+});
+
+afterEach(() => {
+ document.body.innerHTML = "";
+});
+
+describe("SchemaPane shell", () => {
+ test("renders search input + sync button without a connection", () => {
+ const { container, render, unmount } = renderInto(<SchemaPane />);
+ render();
+ expect(
+ container.querySelector("[data-testid='search-input']")
+ ).not.toBeNull();
+ expect(container.querySelector("button")).not.toBeNull();
+ unmount();
+ });
+
+ test("does not call getOrFetchDatabaseMetadata when database name is invalid", () => {
+ const { render, unmount } = renderInto(<SchemaPane />);
+ render();
+ expect(mocks.getOrFetchDatabaseMetadata).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ test("fetches metadata when database name becomes valid", () => {
+ mocks.isValidDatabaseName.mockReturnValue(true);
+ mocks.databaseRefValue = { name: "instances/i/databases/db" };
+ const { render, unmount } = renderInto(<SchemaPane />);
+ render();
+ expect(mocks.getOrFetchDatabaseMetadata).toHaveBeenCalledWith({
+ database: "instances/i/databases/db",
+ });
+ unmount();
+ });
+});
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.tsx
new file mode 100644
index 0000000000..9b37220e63
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.tsx
@@ -0,0 +1,747 @@
+import { uniq, without } from "lodash-es";
+import { ChevronDown, ChevronRight, Loader2 } from "lucide-react";
+import {
+ type CSSProperties,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { useTranslation } from "react-i18next";
+import { EngineIconPath } from "@/components/InstanceForm/constants";
+import { TableSchemaViewer } from "@/react/components/TableSchemaViewer";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+} from "@/react/components/ui/dialog";
+import { Input } from "@/react/components/ui/input";
+import { Tree, type TreeDataNode } from "@/react/components/ui/tree";
+import { countVisibleRows } from "@/react/components/ui/tree-utils";
+import { useVueState } from "@/react/hooks/useVueState";
+import { cn } from "@/react/lib/utils";
+import {
+ useConnectionOfCurrentSQLEditorTab,
+ useDBSchemaV1Store,
+ useSQLEditorTabStore,
+} from "@/store";
+import { isValidDatabaseName } from "@/types";
+import type {
+ DatabaseMetadata,
+ GetSchemaStringRequest_ObjectType,
+ TableMetadata,
+} from "@/types/proto-es/v1/database_service_pb";
+import {
+ extractDatabaseResourceName,
+ getInstanceResource,
+ instanceV1Name,
+} from "@/utils";
+import { findAncestor } from "@/utils/dom";
+import { useSchemaPaneActions } from "./actions";
+import { useAvailableActions } from "./availableActions";
+import { useClickEvents } from "./click";
+import { FlatTableList } from "./FlatTableList";
+import { HoverPanel } from "./HoverPanel/HoverPanel";
+import { HoverStateProvider, useHoverState } from "./hover-state";
+import {
+ SchemaContextMenu,
+ type SchemaContextMenuHandle,
+} from "./SchemaContextMenu";
+import { SyncSchemaButton } from "./SyncSchemaButton";
+import {
+ buildDatabaseSchemaTree,
+ ExpandableNodeTypes,
+ type NodeTarget,
+ type TreeNode as SchemaTreeNode,
+} from "./schemaTree";
+import { Label } from "./TreeNode/Label";
+
+const ROW_HEIGHT = 21;
+const TREE_FALLBACK_HEIGHT = 360;
+const FLAT_TABLE_THRESHOLD = 1000;
+const SEARCH_DEBOUNCE_MS = 200;
+
+/**
+ * React port of `frontend/src/views/sql-editor/AsidePanel/SchemaPane/SchemaPane.vue`.
+ *
+ * Wires together every Phase 1–4 artifact:
+ * - schemaTree.ts builder (Phase 1)
+ * - useDelayedValue / useHoverState (Phase 1)
+ * - leaf TreeNode/*.tsx (Phase 1)
+ * - heavy nodes + Label dispatcher (Phase 2)
+ * - HoverPanel + *Info cards (Phase 3)
+ * - useSchemaPaneActions / ContextMenu (Phase 4a/4b)
+ * - SyncSchemaButton (Phase 4c)
+ * - FlatTableList (Phase 4d)
+ *
+ * The schema-viewer modal lives in the Vue parent (`AsidePanel.vue`)
+ * since it embeds Vue-only `BBModal` + `TableSchemaViewer`. The menu's
+ * "View schema text" action emits a `show-schema-viewer` event on
+ * `sqlEditorEvents` which the Vue context provider listens for and
+ * mirrors onto its inject ref.
+ */
+export function SchemaPane() {
+ return (
+ <HoverStateProvider>
+ <SchemaPaneInner />
+ <HoverPanel offsetX={8} offsetY={0} margin={4} />
+ </HoverStateProvider>
+ );
+}
+
+function SchemaPaneInner() {
+ const { t } = useTranslation();
+ const tabStore = useSQLEditorTabStore();
+ const dbSchemaStore = useDBSchemaV1Store();
+ const connection = useConnectionOfCurrentSQLEditorTab();
+ const hoverState = useHoverState();
+
+ const database = useVueState(() => connection.database.value);
+ const currentTabId = useVueState(() => tabStore.currentTab?.id);
+ // `connection` is mutated in place via `Object.assign`-style updates,
+ // so depth is required to catch nested-field changes (schema, database,
+ // instance) without a fresh reference.
+ const tabConnection = useVueState(() => tabStore.currentTab?.connection, {
+ deep: true,
+ });
+ const tabConnectionSchema = tabConnection?.schema;
+ // tab.viewState shapes the selectedKeys highlight when the editor
+ // panel is on a non-CODE view (e.g. TABLES drill-down).
+ const panelViewState = useVueState(() => tabStore.currentTab?.viewState, {
+ deep: true,
+ });
+
+ const [searchPattern, setSearchPattern] = useState("");
+ const debouncedSearch = useDebouncedValue(searchPattern, SEARCH_DEBOUNCE_MS);
+
+ // Reset the search box on every tab switch — matches Vue's
+ // `watch(() => currentTab.value?.id, ...)`.
+ useEffect(() => {
+ setSearchPattern("");
+ }, [currentTabId]);
+
+ const [metadata, setMetadata] = useState<DatabaseMetadata | null>(null);
+ const [isFetching, setIsFetching] = useState(false);
+
+ // Fetch metadata on database change. The store de-duplicates so this
+ // is safe to fire on every render where the name flips.
+ useEffect(() => {
+ if (!isValidDatabaseName(database.name)) {
+ setMetadata(null);
+ setIsFetching(false);
+ return;
+ }
+ setIsFetching(true);
+ let cancelled = false;
+ void dbSchemaStore
+ .getOrFetchDatabaseMetadata({ database: database.name })
+ .then((md) => {
+ if (cancelled) return;
+ setMetadata(md);
+ })
+ .finally(() => {
+ if (cancelled) return;
+ setIsFetching(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [database.name, dbSchemaStore]);
+
+ const totalTableCount = useMemo(() => {
+ if (!metadata) return 0;
+ return metadata.schemas.reduce(
+ (sum, schema) => sum + (schema.tables?.length ?? 0),
+ 0
+ );
+ }, [metadata]);
+
+ // Build the tree via requestAnimationFrame so the heavy walk doesn't
+ // block the metadata-fetch teardown's transition. Mirrors Vue's
+ // `requestAnimationFrame(() => { tree.value = buildDatabaseSchemaTree(...) })`.
+ const [tree, setTree] = useState<SchemaTreeNode[] | undefined>(undefined);
+ useEffect(() => {
+ if (isFetching || !metadata) {
+ setTree(undefined);
+ return;
+ }
+ if (totalTableCount > FLAT_TABLE_THRESHOLD) {
+ setTree(undefined);
+ return;
+ }
+ let raf = 0;
+ raf = requestAnimationFrame(() => {
+ const built = buildDatabaseSchemaTree(database, metadata);
+ setTree(built);
+ // First-mount default expand: seed treeState.keys so the user
+ // sees database/schema/Tables/Views opened by default. The Vue
+ // version seeds when `treeStateDb !== connectionDb && connectionDb`.
+ const tab = tabStore.currentTab;
+ const connectionDb = tab?.connection.database;
+ if (tab && connectionDb && tab.treeState.database !== connectionDb) {
+ tab.treeState.database = connectionDb;
+ tab.treeState.keys = defaultExpandedKeys(built);
+ }
+ });
+ return () => cancelAnimationFrame(raf);
+ }, [isFetching, metadata, totalTableCount, database, tabStore]);
+
+ // Reactive proxy for `tab.treeState.keys`. Reads via useVueState +
+ // deep watch (Pinia mutates in place); writes go through a thin
+ // setter so the store mutation triggers the watch.
+ const expandedKeys = useVueState<string[]>(
+ () => {
+ const tab = tabStore.currentTab;
+ if (!tab) return [];
+ if (tab.treeState.database !== database.name) return [];
+ return tab.treeState.keys ?? [];
+ },
+ { deep: true }
+ );
+
+ const setExpandedKeys = useCallback(
+ (keys: string[]) => {
+ const tab = tabStore.currentTab;
+ if (!tab) return;
+ if (tab.treeState.database !== database.name) return;
+ tab.treeState.keys = keys;
+ },
+ [tabStore, database.name]
+ );
+
+ const upsertExpandedKeys = useCallback(
+ (keys: string[]) => {
+ setExpandedKeys(uniq([...expandedKeys, ...keys]));
+ },
+ [expandedKeys, setExpandedKeys]
+ );
+ const removeExpandedKeys = useCallback(
+ (keys: string[]) => {
+ setExpandedKeys(without(expandedKeys, ...keys));
+ },
+ [expandedKeys, setExpandedKeys]
+ );
+
+ // ---- Selected-key highlight (current connection / detail view) ---------
+ const selectedKeys = useMemo(() => {
+ if (!isValidDatabaseName(database.name)) return [];
+ const keys: string[] = [];
+ if (tabConnectionSchema !== undefined) {
+ keys.push(`${database.name}/schemas/${tabConnectionSchema}`);
+ }
+ if (!panelViewState || panelViewState.view === "CODE") return keys;
+
+ const detail = panelViewState.detail ?? {};
+ const parts = [database.name, `schemas/${panelViewState.schema ?? ""}`];
+ if (detail.table) {
+ parts.push(`tables/${detail.table}`);
+ if (detail.column) parts.push(`columns/${detail.column}`);
+ else if (detail.index) parts.push(`indexes/${detail.index}`);
+ else if (detail.partition)
+ parts.push(`partitionTables/${detail.partition}`);
+ else if (detail.trigger) parts.push(`triggers/${detail.trigger}`);
+ else if (detail.foreignKey)
+ parts.push(`foreignKeys/${detail.foreignKey}`);
+ } else if (detail.view) {
+ parts.push(`views/${detail.view}`);
+ if (detail.column) parts.push(`columns/${detail.column}`);
+ } else if (detail.procedure) {
+ parts.push(`procedures/${detail.procedure}`);
+ } else if (detail.func) {
+ parts.push(`functions/${detail.func}`);
+ } else if (detail.sequence) {
+ parts.push(`sequences/${detail.sequence}`);
+ } else if (detail.externalTable) {
+ parts.push(`externalTables/${detail.externalTable}`);
+ } else if (detail.package) {
+ parts.push(`packages/${detail.package}`);
+ }
+ return [parts.join("/")];
+ }, [database.name, tabConnectionSchema, panelViewState]);
+
+ // ---- Adaptive flat / tree -----------------------------------------------
+ const treeData = useMemo<TreeDataNode<SchemaTreeNode>[]>(() => {
+ if (!tree) return [];
+ return tree.map(toTreeData);
+ }, [tree]);
+
+ const expandedKeySet = useMemo(() => new Set(expandedKeys), [expandedKeys]);
+ const searchKeyword = debouncedSearch.trim();
+ const visibleRowCount = useMemo(() => {
+ if (!tree) return 0;
+ return tree.reduce(
+ (sum, root) =>
+ sum +
+ countVisibleRows(root, expandedKeySet, searchKeyword, schemaNodeMatch),
+ 0
+ );
+ }, [tree, expandedKeySet, searchKeyword]);
+
+ // ---- Click discriminator (single vs double) -----------------------------
+ const { events: clickEvents, handleClick } = useClickEvents();
+ const { selectAllFromTableOrView } = useSchemaActionsForClick();
+
+ const toggleNode = useCallback(
+ (node: SchemaTreeNode) => {
+ if (expandedKeys.includes(node.key)) {
+ removeExpandedKeys([node.key]);
+ } else if (ExpandableNodeTypes.includes(node.meta.type)) {
+ upsertExpandedKeys([node.key]);
+ }
+ },
+ [expandedKeys, removeExpandedKeys, upsertExpandedKeys]
+ );
+
+ useEffect(() => {
+ const offSingle = clickEvents.on("single-click", ({ node }) => {
+ // Toggle expand for non-leaf rows. For schema, also push the
+ // selected schema into the tab's connection.
+ if (node.meta.type === "schema") {
+ const tab = tabStore.currentTab;
+ if (tab) {
+ tab.connection.schema = (
+ node.meta.target as NodeTarget<"schema">
+ ).schema;
+ }
+ }
+ toggleNode(node);
+ });
+ const offDouble = clickEvents.on("double-click", ({ node }) => {
+ const type = node.meta.type;
+ if (type === "table" || type === "view") {
+ void selectAllFromTableOrView(node);
+ } else if (type === "schema" || type === "expandable-text") {
+ toggleNode(node);
+ } else {
+ // Leaf nodes: mirror single-click toggle behavior so the tree
+ // state matches what the user expects after a fast double-tap.
+ toggleNode(node);
+ }
+ });
+ return () => {
+ offSingle();
+ offDouble();
+ };
+ }, [clickEvents, selectAllFromTableOrView, tabStore, toggleNode]);
+
+ // ---- Context menu (right-click) -----------------------------------------
+ const contextMenuRef = useRef<SchemaContextMenuHandle>(null);
+ // Schema-viewer modal lives here now (was bridged through Vue parent
+ // until the React TableSchemaViewer landed). Local state because the
+ // SchemaPane right-click menu is the only trigger.
+ const [schemaViewer, setSchemaViewerState] = useState<
+ | {
+ schema?: string;
+ object?: string;
+ type?: GetSchemaStringRequest_ObjectType;
+ }
+ | undefined
+ >(undefined);
+ const setSchemaViewer = useCallback(
+ (
+ viewer:
+ | {
+ schema?: string;
+ object?: string;
+ type?: GetSchemaStringRequest_ObjectType;
+ }
+ | undefined
+ ) => {
+ setSchemaViewerState(viewer);
+ },
+ []
+ );
+ const availableActions = useAvailableActions();
+
+ // ---- Flat list handlers (when totalTableCount > 1000) -------------------
+ const onFlatSelect = useCallback(
+ (item: { schema?: string }) => {
+ const tab = tabStore.currentTab;
+ if (tab && item.schema) {
+ tab.connection.schema = item.schema;
+ }
+ },
+ [tabStore]
+ );
+ const onFlatSelectAll = useCallback(
+ (item: { key: string; schema: string; metadata: TableMetadata }) => {
+ const synthetic: SchemaTreeNode = {
+ key: item.key,
+ meta: {
+ type: "table",
+ target: {
+ database: database.name,
+ schema: item.schema,
+ table: item.metadata.name,
+ },
+ },
+ };
+ void selectAllFromTableOrView(synthetic);
+ },
+ [database.name, selectAllFromTableOrView]
+ );
+ const onFlatContextMenu = useCallback(
+ (
+ e: React.MouseEvent,
+ item: { key: string; schema: string; metadata: TableMetadata }
+ ) => {
+ const synthetic: SchemaTreeNode = {
+ key: item.key,
+ meta: {
+ type: "table",
+ target: {
+ database: database.name,
+ schema: item.schema,
+ table: item.metadata.name,
+ },
+ },
+ };
+ contextMenuRef.current?.show(synthetic, e);
+ },
+ [database.name]
+ );
+
+ return (
+ <div className="gap-y-1 h-full flex flex-col items-stretch relative overflow-hidden">
+ <div className="px-1 flex flex-row gap-1">
+ <div className="flex-1 overflow-hidden">
+ <Input
+ value={searchPattern}
+ placeholder={t("common.search")}
+ disabled={!tabStore.currentTab}
+ onChange={(e) => setSearchPattern(e.target.value)}
+ className="h-8 text-sm w-full"
+ />
+ </div>
+ <div className="shrink-0 flex items-center">
+ <SyncSchemaButton />
+ </div>
+ </div>
+
+ <div className="schema-tree flex-1 px-1 pb-1 text-sm overflow-auto select-none">
+ {isFetching ? (
+ <div className="flex items-center justify-center mt-16 text-control-light">
+ <Loader2 className="size-5 animate-spin" />
+ </div>
+ ) : metadata ? (
+ totalTableCount > FLAT_TABLE_THRESHOLD ? (
+ <FlatTableList
+ metadata={metadata}
+ search={debouncedSearch}
+ database={database.name}
+ onSelect={onFlatSelect}
+ onSelectAll={onFlatSelectAll}
+ onContextMenu={onFlatContextMenu}
+ />
+ ) : tree && tree.length > 0 ? (
+ <Tree<SchemaTreeNode>
+ data={treeData}
+ selectedIds={selectedKeys}
+ expandedIds={expandedKeys}
+ searchTerm={searchKeyword || undefined}
+ searchMatch={searchMatch}
+ onToggle={(id) => {
+ const next = new Set(expandedKeys);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ setExpandedKeys([...next]);
+ }}
+ height={
+ Math.max(visibleRowCount, 1) * ROW_HEIGHT ||
+ TREE_FALLBACK_HEIGHT
+ }
+ rowHeight={ROW_HEIGHT}
+ indent={10}
+ renderNode={({ node, style }) => (
+ <SchemaTreeRow
+ style={style}
+ node={node.data.data}
+ isOpen={!!node.isOpen}
+ hasChildren={
+ !!node.data.data.children &&
+ node.data.data.children.length > 0
+ }
+ keyword={searchKeyword}
+ selected={selectedKeys.includes(node.data.data.key)}
+ hoverUpdate={hoverState.update}
+ hoverHasState={hoverState.state !== undefined}
+ hoverSetPosition={hoverState.setPosition}
+ databaseName={database.name}
+ onClickNode={handleClick}
+ onContextMenu={(n, e) => contextMenuRef.current?.show(n, e)}
+ />
+ )}
+ />
+ ) : (
+ <EmptyHint label={t("common.empty")} />
+ )
+ ) : (
+ <EmptyHint label={t("common.empty")} />
+ )}
+ </div>
+
+ <SchemaContextMenu
+ ref={contextMenuRef}
+ availableActions={availableActions}
+ setSchemaViewer={setSchemaViewer}
+ />
+
+ {/* Schema-viewer modal — Vue's BBModal+TableSchemaViewer used to
+ live in the parent (`SQLEditorHomePage.vue`) bridged via the
+ `show-schema-viewer` event because TableSchemaViewer was Vue.
+ Now the React TableSchemaViewer ships, so the trigger and its
+ modal home in the same place. */}
+ <Dialog
+ open={!!schemaViewer}
+ onOpenChange={(open) => {
+ if (!open) setSchemaViewerState(undefined);
+ }}
+ >
+ <DialogContent
+ className="p-4"
+ style={{
+ width: "calc(100vw - 12rem)",
+ height: "calc(100vh - 12rem)",
+ maxWidth: "calc(100vw - 12rem)",
+ }}
+ >
+ <DialogTitle className="text-base font-medium flex items-center gap-x-1">
+ <DatabaseTitle database={database} />
+ </DialogTitle>
+ {schemaViewer ? (
+ <TableSchemaViewer
+ database={database}
+ schema={schemaViewer.schema}
+ object={schemaViewer.object}
+ type={schemaViewer.type}
+ className="flex-1"
+ />
+ ) : null}
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
+
+// ---- Helpers / sub-components ----------------------------------------------
+
+function toTreeData(node: SchemaTreeNode): TreeDataNode<SchemaTreeNode> {
+ return {
+ id: node.key,
+ data: node,
+ children: node.children?.map(toTreeData),
+ };
+}
+
+const searchMatch = (
+ node: TreeDataNode<SchemaTreeNode>,
+ term: string
+): boolean => {
+ // Mirror Vue's NTree default: case-insensitive substring match against
+ // the node's display label.
+ const label = node.data.label ?? "";
+ return label.toLowerCase().includes(term.toLowerCase());
+};
+
+const schemaNodeMatch = (node: SchemaTreeNode, term: string): boolean => {
+ const label = node.label ?? "";
+ return label.toLowerCase().includes(term.toLowerCase());
+};
+
+function defaultExpandedKeys(tree: SchemaTreeNode[]): string[] {
+ if (tree.length === 0) return [];
+ const keys: string[] = [];
+ const collect = (n: SchemaTreeNode) => {
+ keys.push(n.key);
+ n.children?.forEach(walk);
+ };
+ const walk = (n: SchemaTreeNode) => {
+ const t = n.meta.type;
+ if (t === "database" || t === "schema") {
+ collect(n);
+ } else if (t === "expandable-text") {
+ const mockType = (n.meta.target as NodeTarget<"expandable-text">)
+ .mockType;
+ if (mockType === "table" || mockType === "view") collect(n);
+ }
+ };
+ walk(tree[0]);
+ return keys;
+}
+
+function useDebouncedValue<T>(value: T, delayMs: number): T {
+ const [debounced, setDebounced] = useState(value);
+ useEffect(() => {
+ const id = setTimeout(() => setDebounced(value), delayMs);
+ return () => clearTimeout(id);
+ }, [value, delayMs]);
+ return debounced;
+}
+
+/**
+ * Direct re-export of `useSchemaPaneActions` so SchemaPaneInner can
+ * grab `selectAllFromTableOrView` for the double-click handler. The
+ * full menu-action surface lives inside `useSchemaPaneContextMenu`
+ * (consumed by SchemaContextMenu).
+ */
+function useSchemaActionsForClick() {
+ return useSchemaPaneActions();
+}
+
+/**
+ * Minimal database breadcrumb for the schema-viewer modal title:
+ * engine icon + instance name + chevron + database name. Replaces
+ * Vue's `<RichDatabaseName>` for this single use site — full port
+ * of `RichDatabaseName.vue` is deferred until another React surface
+ * needs it.
+ */
+function DatabaseTitle({
+ database,
+}: {
+ database: { name: string; project: string } & Record<string, unknown>;
+}) {
+ const instance = getInstanceResource(database as never);
+ const iconPath = EngineIconPath[instance.engine];
+ const databaseName = extractDatabaseResourceName(database.name).databaseName;
+ return (
+ <span className="inline-flex items-center gap-x-1">
+ {iconPath ? (
+ <img src={iconPath} alt="" className="size-4 shrink-0" />
+ ) : null}
+ <span className="truncate">{instanceV1Name(instance)}</span>
+ <ChevronRight className="size-3 shrink-0" />
+ <span className="truncate">{databaseName}</span>
+ </span>
+ );
+}
+
+function EmptyHint({ label }: { label: string }) {
+ return (
+ <div className="flex items-center justify-center mt-16 text-control-light text-sm">
+ {label}
+ </div>
+ );
+}
+
+function SchemaTreeRow({
+ style,
+ node,
+ isOpen,
+ hasChildren,
+ keyword,
+ selected,
+ hoverUpdate,
+ hoverHasState,
+ hoverSetPosition,
+ databaseName,
+ onClickNode,
+ onContextMenu,
+}: {
+ style: CSSProperties;
+ node: SchemaTreeNode;
+ isOpen: boolean;
+ hasChildren: boolean;
+ keyword: string;
+ selected: boolean;
+ hoverUpdate: ReturnType<typeof useHoverState>["update"];
+ hoverHasState: boolean;
+ hoverSetPosition: ReturnType<typeof useHoverState>["setPosition"];
+ databaseName: string;
+ onClickNode: (node: SchemaTreeNode) => void;
+ onContextMenu: (node: SchemaTreeNode, e: React.MouseEvent) => void;
+}) {
+ const rowRef = useRef<HTMLDivElement | null>(null);
+
+ const handleMouseEnter = (e: React.MouseEvent<HTMLDivElement>) => {
+ const type = node.meta.type;
+ if (
+ type !== "table" &&
+ type !== "external-table" &&
+ type !== "column" &&
+ type !== "view" &&
+ type !== "partition-table"
+ ) {
+ return;
+ }
+ const target = node.meta.target as
+ | NodeTarget<"table">
+ | NodeTarget<"external-table">
+ | NodeTarget<"column">
+ | NodeTarget<"view">
+ | NodeTarget<"partition-table">;
+ // Build the sparse hover state shape from the current target.
+ const state: {
+ database: string;
+ schema?: string;
+ table?: string;
+ externalTable?: string;
+ view?: string;
+ column?: string;
+ partition?: string;
+ } = { database: databaseName };
+ if ("schema" in target) state.schema = target.schema as string;
+ if ("table" in target) state.table = target.table as string;
+ if ("externalTable" in target)
+ state.externalTable = target.externalTable as string;
+ if ("view" in target) state.view = target.view as string;
+ if ("column" in target) state.column = target.column as string;
+ if ("partition" in target) state.partition = target.partition as string;
+
+ const delay = hoverHasState ? 150 : undefined;
+ hoverUpdate(state, "before", delay);
+
+ // Compute position from the row's bounding rect, like Vue's
+ // `findAncestor(.n-tree-node)` → getBoundingClientRect.
+ const wrapper = findAncestor(
+ e.target as HTMLElement,
+ ".bb-schema-tree-row"
+ );
+ if (!wrapper) {
+ hoverUpdate(undefined, "after", 150);
+ return;
+ }
+ const rect = wrapper.getBoundingClientRect();
+ hoverSetPosition({ x: e.clientX, y: rect.bottom });
+ };
+
+ const handleMouseLeave = () => {
+ hoverUpdate(undefined, "after");
+ };
+
+ return (
+ <div
+ ref={rowRef}
+ style={style}
+ className={cn(
+ "bb-schema-tree-row flex items-center w-full pr-2 cursor-pointer rounded-sm h-full",
+ "hover:bg-control-bg/70",
+ selected && "bg-accent/10 font-medium",
+ node.disabled && "cursor-default opacity-70"
+ )}
+ data-node-key={node.key}
+ data-node-meta-type={node.meta.type}
+ onClick={() => {
+ if (node.disabled) return;
+ onClickNode(node);
+ }}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ onContextMenu(node, e);
+ }}
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ >
+ <span className="shrink-0 inline-flex size-5 items-center justify-center text-control-light">
+ {hasChildren ? (
+ isOpen ? (
+ <ChevronDown className="size-3.5" />
+ ) : (
+ <ChevronRight className="size-3.5" />
+ )
+ ) : null}
+ </span>
+ <Label node={node} keyword={keyword} />
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.test.tsx
new file mode 100644
index 0000000000..5ca61f965e
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.test.tsx
@@ -0,0 +1,152 @@
+import { act, type ReactElement } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ databaseRefValue: {
+ name: "instances/i/databases/db",
+ successfulSyncTime: undefined,
+ },
+ syncDatabase: vi.fn().mockResolvedValue(undefined),
+ getOrFetchDatabaseMetadata: vi.fn().mockResolvedValue(undefined),
+ isValidDatabaseName: vi.fn(() => true),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (k: string) => k,
+ i18n: { language: "en-US" },
+ }),
+ Trans: ({ i18nKey }: { i18nKey: string }) => <span>{i18nKey}</span>,
+}));
+
+vi.mock("@/react/components/HumanizeTs", () => ({
+ HumanizeTs: () => <span data-testid="humanize" />,
+}));
+
+vi.mock("@/react/components/ui/tooltip", () => ({
+ Tooltip: ({
+ children,
+ content,
+ }: {
+ children: React.ReactNode;
+ content: React.ReactNode;
+ }) => (
+ <div data-testid="tooltip-wrap">
+ <div data-testid="tooltip-content">{content}</div>
+ {children}
+ </div>
+ ),
+}));
+
+vi.mock("@/react/components/ui/button", () => ({
+ Button: ({
+ children,
+ onClick,
+ disabled,
+ }: {
+ children: React.ReactNode;
+ onClick?: () => void;
+ disabled?: boolean;
+ }) => (
+ <button
+ type="button"
+ data-testid="sync-button"
+ onClick={onClick}
+ disabled={disabled}
+ >
+ {children}
+ </button>
+ ),
+}));
+
+vi.mock("@/react/hooks/useVueState", () => ({
+ useVueState: (getter: () => unknown) => getter(),
+}));
+
+vi.mock("@/store", () => ({
+ useConnectionOfCurrentSQLEditorTab: () => ({
+ database: { value: mocks.databaseRefValue },
+ }),
+ useDatabaseV1Store: () => ({ syncDatabase: mocks.syncDatabase }),
+ useDBSchemaV1Store: () => ({
+ getOrFetchDatabaseMetadata: mocks.getOrFetchDatabaseMetadata,
+ }),
+}));
+
+vi.mock("@/types", () => ({
+ getDateForPbTimestampProtoEs: () => undefined,
+ isValidDatabaseName: mocks.isValidDatabaseName,
+}));
+
+let SyncSchemaButton: typeof import("./SyncSchemaButton").SyncSchemaButton;
+
+const renderInto = (element: ReactElement) => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ return {
+ container,
+ render: () => act(() => root.render(element)),
+ unmount: () => {
+ act(() => root.unmount());
+ container.remove();
+ },
+ };
+};
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ mocks.isValidDatabaseName.mockReturnValue(true);
+ ({ SyncSchemaButton } = await import("./SyncSchemaButton"));
+});
+
+describe("SyncSchemaButton", () => {
+ test("disables the button when there's no valid database name", () => {
+ mocks.isValidDatabaseName.mockReturnValue(false);
+ const { container, render, unmount } = renderInto(<SyncSchemaButton />);
+ render();
+ const btn = container.querySelector(
+ "[data-testid='sync-button']"
+ ) as HTMLButtonElement;
+ expect(btn).not.toBeNull();
+ expect(btn.disabled).toBe(true);
+ // Disabled state skips the tooltip wrapper.
+ expect(container.querySelector("[data-testid='tooltip-wrap']")).toBeNull();
+ unmount();
+ });
+
+ test("clicking the button calls syncDatabase + getOrFetchDatabaseMetadata", async () => {
+ const { container, render, unmount } = renderInto(<SyncSchemaButton />);
+ render();
+ const btn = container.querySelector(
+ "[data-testid='sync-button']"
+ ) as HTMLButtonElement;
+ await act(async () => {
+ btn.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ expect(mocks.syncDatabase).toHaveBeenCalledWith(
+ "instances/i/databases/db",
+ true
+ );
+ expect(mocks.getOrFetchDatabaseMetadata).toHaveBeenCalledWith({
+ database: "instances/i/databases/db",
+ skipCache: true,
+ });
+ unmount();
+ });
+
+ test("renders a tooltip with the click-to-sync hint when enabled", () => {
+ const { container, render, unmount } = renderInto(<SyncSchemaButton />);
+ render();
+ expect(
+ container.querySelector("[data-testid='tooltip-wrap']")
+ ).not.toBeNull();
+ expect(container.textContent).toContain("sql-editor.click-to-sync-now");
+ unmount();
+ });
+});
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.tsx
new file mode 100644
index 0000000000..dcccc30cf6
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.tsx
@@ -0,0 +1,105 @@
+import { RefreshCcw } from "lucide-react";
+import { useState } from "react";
+import { Trans, useTranslation } from "react-i18next";
+import { HumanizeTs } from "@/react/components/HumanizeTs";
+import { Button } from "@/react/components/ui/button";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { useVueState } from "@/react/hooks/useVueState";
+import { cn } from "@/react/lib/utils";
+import {
+ useConnectionOfCurrentSQLEditorTab,
+ useDatabaseV1Store,
+ useDBSchemaV1Store,
+} from "@/store";
+import { getDateForPbTimestampProtoEs, isValidDatabaseName } from "@/types";
+
+/**
+ * Replaces `SchemaPane/SyncSchemaButton.vue`. RefreshCcw button with a
+ * hover popover showing the last sync time + click-to-sync hint.
+ *
+ * - Disabled when the active tab has no valid database connection (no
+ * `database.name`) or while a sync is in flight.
+ * - On click, calls `databaseStore.syncDatabase(name, refresh=true)`,
+ * then `dbSchemaStore.getOrFetchDatabaseMetadata({ skipCache: true })`
+ * so the SchemaPane reactively rebuilds with the fresh metadata.
+ * - Spinner: same Vue rule — `animate-spin` while `isSyncing` is true.
+ */
+export function SyncSchemaButton({ className }: { className?: string }) {
+ const { t } = useTranslation();
+ const { database: databaseRef } = useConnectionOfCurrentSQLEditorTab();
+ const database = useVueState(() => databaseRef.value);
+ const databaseStore = useDatabaseV1Store();
+ const dbSchemaStore = useDBSchemaV1Store();
+
+ const [isSyncing, setIsSyncing] = useState(false);
+ const disabled = !isValidDatabaseName(database.name);
+
+ const syncNow = async () => {
+ if (disabled) return;
+ setIsSyncing(true);
+ try {
+ await databaseStore.syncDatabase(database.name, true);
+ await dbSchemaStore.getOrFetchDatabaseMetadata({
+ database: database.name,
+ skipCache: true,
+ });
+ } finally {
+ setIsSyncing(false);
+ }
+ };
+
+ const lastSyncDate = getDateForPbTimestampProtoEs(
+ database.successfulSyncTime
+ );
+ const lastSyncTs = lastSyncDate
+ ? Math.floor(lastSyncDate.getTime() / 1000)
+ : 0;
+
+ const button = (
+ <Button
+ variant="outline"
+ size="sm"
+ type="button"
+ disabled={disabled || isSyncing}
+ onClick={syncNow}
+ className={cn("px-1.5", className)}
+ >
+ <RefreshCcw
+ className={cn(
+ "size-4",
+ isSyncing && "animate-[spin_2s_linear_infinite]"
+ )}
+ />
+ </Button>
+ );
+
+ if (disabled) {
+ // Vue disables the popover on disabled state — match that so we don't
+ // surface a "last synced" tooltip with stale-looking placeholder data.
+ return button;
+ }
+
+ return (
+ <Tooltip
+ side="bottom"
+ content={
+ <div className="flex flex-col gap-1">
+ {lastSyncTs > 0 ? (
+ <Trans
+ t={t}
+ i18nKey="sql-editor.last-synced"
+ components={{ time: <HumanizeTs ts={lastSyncTs} /> }}
+ />
+ ) : null}
+ <div>
+ {isSyncing
+ ? t("sql-editor.sync-in-progress")
+ : t("sql-editor.click-to-sync-now")}
+ </div>
+ </div>
+ }
+ >
+ {button}
+ </Tooltip>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/CheckNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/CheckNode.tsx
new file mode 100644
index 0000000000..59f813abe9
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/CheckNode.tsx
@@ -0,0 +1,51 @@
+import { useVueState } from "@/react/hooks/useVueState";
+import { useDBSchemaV1Store } from "@/store";
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+import { CheckConstraintIcon } from "./icons";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+/**
+ * Replaces `TreeNode/CheckNode.vue`. Renders the constraint name plus a
+ * trailing tag with the resolved check expression (if metadata is loaded).
+ */
+export function CheckNode({ node, keyword }: Props) {
+ const dbSchema = useDBSchemaV1Store();
+ const target = (node as TreeNode<"check">).meta.target;
+
+ const checkMetadata = useVueState(() => {
+ if ("table" in target) {
+ const { database, schema, table, check } = target;
+ const tableMetadata = dbSchema.getTableMetadata({
+ database,
+ schema,
+ table,
+ });
+ return tableMetadata?.checkConstraints.find((c) => c.name === check);
+ }
+ return undefined;
+ });
+
+ return (
+ <CommonNode
+ text={target.check}
+ keyword={keyword}
+ highlight={true}
+ indent={0}
+ icon={<CheckConstraintIcon />}
+ suffix={
+ checkMetadata?.expression ? (
+ <div className="flex items-center justify-end gap-1 overflow-hidden whitespace-nowrap shrink opacity-80 font-normal!">
+ <span className="inline-flex items-center rounded-sm border border-control-border bg-control-bg/40 text-control h-4 px-[3px] text-[10px] leading-none">
+ {checkMetadata.expression}
+ </span>
+ </div>
+ ) : null
+ }
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ColumnNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ColumnNode.tsx
new file mode 100644
index 0000000000..97e8d8eabb
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ColumnNode.tsx
@@ -0,0 +1,93 @@
+import { useVueState } from "@/react/hooks/useVueState";
+import { useDBSchemaV1Store } from "@/store";
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+import { ColumnIcon, IndexIcon, PrimaryKeyIcon } from "./icons";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+/**
+ * Replaces `TreeNode/ColumnNode.vue`. The icon and trailing type-tag both
+ * depend on the column's resolved metadata:
+ * - PrimaryKeyIcon when the column is part of the primary index.
+ * - IndexIcon when it's part of any other index (and not the PK).
+ * - ColumnIcon otherwise.
+ * - The trailing type-tag (`int`, `varchar(255)`, …) is rendered when
+ * the metadata fetch has resolved.
+ *
+ * Reads from `dbSchemaStore.getTableMetadata` / `getSchemaMetadata`
+ * through `useVueState` so cache hydration triggers a re-render.
+ */
+export function ColumnNode({ node, keyword }: Props) {
+ const dbSchema = useDBSchemaV1Store();
+ const target = (node as TreeNode<"column">).meta.target;
+
+ const tableMetadata = useVueState(() => {
+ if ("table" in target) {
+ const { database, schema, table } = target;
+ return dbSchema.getTableMetadata({ database, schema, table });
+ }
+ return undefined;
+ });
+
+ const columnMetadata = useVueState(() => {
+ const { database, schema, column } = target;
+ const schemaMetadata = dbSchema.getSchemaMetadata({ database, schema });
+
+ if ("table" in target) {
+ return tableMetadata?.columns.find((c) => c.name === column);
+ } else if ("externalTable" in target) {
+ return schemaMetadata?.externalTables
+ .find((t) => t.name === target.externalTable)
+ ?.columns.find((c) => c.name === column);
+ } else if ("view" in target) {
+ return schemaMetadata?.views
+ .find((v) => v.name === target.view)
+ ?.columns.find((c) => c.name === column);
+ }
+ return undefined;
+ });
+
+ let isPrimaryKey = false;
+ let isIndex = false;
+ if ("table" in target) {
+ const { column } = target;
+ const pk = tableMetadata?.indexes.find((idx) => idx.primary);
+ isPrimaryKey = pk ? pk.expressions.includes(column) : false;
+ if (!isPrimaryKey) {
+ isIndex = !!tableMetadata?.indexes.some((idx) =>
+ idx.expressions.includes(column)
+ );
+ }
+ }
+
+ const icon = isPrimaryKey ? (
+ <PrimaryKeyIcon />
+ ) : isIndex ? (
+ <IndexIcon className="size-4! text-accent/80" />
+ ) : (
+ <ColumnIcon />
+ );
+
+ return (
+ <CommonNode
+ text={target.column}
+ keyword={keyword}
+ highlight={true}
+ indent={0}
+ icon={icon}
+ suffix={
+ columnMetadata?.type ? (
+ <div className="flex items-center justify-end gap-1 overflow-hidden whitespace-nowrap shrink opacity-80 font-normal!">
+ <span className="inline-flex items-center rounded-sm border border-control-border bg-control-bg/40 text-control h-4 px-[3px] text-[10px] leading-none">
+ {columnMetadata.type}
+ </span>
+ </div>
+ ) : null
+ }
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/CommonNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/CommonNode.tsx
new file mode 100644
index 0000000000..729c16b454
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/CommonNode.tsx
@@ -0,0 +1,91 @@
+import type { ReactNode } from "react";
+import { HighlightLabelText } from "@/react/components/HighlightLabelText";
+import { cn } from "@/react/lib/utils";
+
+type Props = {
+ readonly text: string;
+ readonly indent?: number;
+ readonly keyword?: string;
+ readonly highlight?: boolean;
+ readonly hideIcon?: boolean;
+ readonly icon?: ReactNode;
+ readonly suffix?: ReactNode;
+ /**
+ * Renders when `text` is empty (e.g. SchemaNode falling back to "default").
+ */
+ readonly fallbackText?: ReactNode;
+ /**
+ * Override the default rendered children entirely. Mirrors Vue's
+ * `<template #default>` slot — used by `TextNode` to inject custom
+ * content when `node.meta.target.render` is set.
+ */
+ readonly children?: ReactNode;
+ readonly className?: string;
+};
+
+/**
+ * Replaces `frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/CommonNode.vue`.
+ *
+ * Layout: [optional indent spacers] [icon] [text|highlight|fallback] [suffix].
+ * Mirrors the Vue widths (20×20 indent + icon, 2px text padding) so rows
+ * align across the Vue→React swap.
+ */
+export function CommonNode({
+ text,
+ indent,
+ keyword,
+ highlight,
+ hideIcon,
+ icon,
+ suffix,
+ fallbackText,
+ children,
+ className,
+}: Props) {
+ if (children !== undefined) {
+ return (
+ <div
+ className={cn(
+ "flex items-center max-w-full overflow-hidden",
+ className
+ )}
+ >
+ {children}
+ </div>
+ );
+ }
+ return (
+ <div
+ className={cn("flex items-center max-w-full overflow-hidden", className)}
+ >
+ {indent
+ ? Array.from({ length: indent }, (_, i) => (
+ <span
+ key={`indent-#${i}`}
+ className="inline-block w-[20px] h-[20px] shrink-0 invisible"
+ data-indent={i + 1}
+ />
+ ))
+ : null}
+ {!hideIcon ? (
+ <span className="flex items-center justify-center shrink-0 w-[20px] h-[20px]">
+ {icon}
+ </span>
+ ) : null}
+ {text ? (
+ highlight ? (
+ <HighlightLabelText
+ text={text}
+ keyword={keyword ?? ""}
+ className="flex-1 truncate pl-[2px] min-w-16"
+ />
+ ) : (
+ <span className="pl-[2px]">{text}</span>
+ )
+ ) : (
+ fallbackText
+ )}
+ {suffix}
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DatabaseNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DatabaseNode.tsx
new file mode 100644
index 0000000000..a6e662c971
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DatabaseNode.tsx
@@ -0,0 +1,37 @@
+import { EngineIconPath } from "@/components/InstanceForm/constants";
+import { useVueState } from "@/react/hooks/useVueState";
+import { useDatabaseV1Store } from "@/store";
+import { extractDatabaseResourceName, getInstanceResource } from "@/utils";
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+/**
+ * Replaces `TreeNode/DatabaseNode.vue`. The schema tree's root node:
+ * engine icon + database display name (highlight-aware).
+ */
+export function DatabaseNode({ node, keyword }: Props) {
+ const databaseStore = useDatabaseV1Store();
+ const target = (node as TreeNode<"database">).meta.target;
+
+ const database = useVueState(() =>
+ databaseStore.getDatabaseByName(target.database)
+ );
+
+ const databaseName = extractDatabaseResourceName(database.name).databaseName;
+ const instance = getInstanceResource(database);
+ const iconPath = EngineIconPath[instance.engine];
+
+ return (
+ <CommonNode
+ text={databaseName}
+ keyword={keyword}
+ highlight={true}
+ icon={iconPath ? <img src={iconPath} alt="" className="size-4" /> : null}
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DependencyColumnNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DependencyColumnNode.tsx
new file mode 100644
index 0000000000..abddc9022c
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DependencyColumnNode.tsx
@@ -0,0 +1,30 @@
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+import { ColumnIcon } from "./icons";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+/**
+ * Replaces `TreeNode/DependencyColumnNode.vue`. Renders a view's
+ * upstream column in `[schema.]table.column` form.
+ */
+export function DependencyColumnNode({ node, keyword }: Props) {
+ const target = (node as TreeNode<"dependency-column">).meta.target;
+ const { schema, table, column } = target.dependencyColumn;
+ const parts = [table, column];
+ if (schema) parts.unshift(schema);
+ const text = parts.join(".");
+
+ return (
+ <CommonNode
+ text={text}
+ keyword={keyword}
+ highlight={true}
+ indent={0}
+ icon={<ColumnIcon />}
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DummyNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DummyNode.tsx
new file mode 100644
index 0000000000..9f1b67c98c
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DummyNode.tsx
@@ -0,0 +1,36 @@
+import { useTranslation } from "react-i18next";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import type { TreeNode } from "../schemaTree";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+/**
+ * Replaces `TreeNode/DummyNode.vue`. Renders an "<Empty>" / "<Error>"
+ * placeholder span; if the underlying target carries an `error`, the
+ * span exposes that message via Tooltip on hover.
+ */
+export function DummyNode({ node }: Props) {
+ const { t } = useTranslation();
+ const error = (node as TreeNode<"error">).meta.target.error;
+ const text = `<${error ? t("common.error") : t("common.empty")}>`;
+ const span = (
+ <span className="text-control-placeholder ml-[2px]">{text}</span>
+ );
+
+ if (!error) return span;
+
+ return (
+ <Tooltip
+ content={
+ <div className="text-error wrap-break-word break-all">
+ {String(error)}
+ </div>
+ }
+ >
+ {span}
+ </Tooltip>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ExternalTableNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ExternalTableNode.tsx
new file mode 100644
index 0000000000..e2e7a87bcb
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ExternalTableNode.tsx
@@ -0,0 +1,20 @@
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+import { ExternalTableIcon } from "./icons";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+export function ExternalTableNode({ node, keyword }: Props) {
+ const target = (node as TreeNode<"external-table">).meta.target;
+ return (
+ <CommonNode
+ text={target.externalTable}
+ keyword={keyword}
+ highlight={true}
+ icon={<ExternalTableIcon />}
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ForeignKeyNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ForeignKeyNode.tsx
new file mode 100644
index 0000000000..b89060ed2b
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ForeignKeyNode.tsx
@@ -0,0 +1,21 @@
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+import { ForeignKeyIcon } from "./icons";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+export function ForeignKeyNode({ node, keyword }: Props) {
+ const target = (node as TreeNode<"foreign-key">).meta.target;
+ return (
+ <CommonNode
+ text={target.foreignKey}
+ keyword={keyword}
+ highlight={true}
+ indent={0}
+ icon={<ForeignKeyIcon />}
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/FunctionNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/FunctionNode.tsx
new file mode 100644
index 0000000000..bc40964ad3
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/FunctionNode.tsx
@@ -0,0 +1,35 @@
+import { useVueState } from "@/react/hooks/useVueState";
+import { useDBSchemaV1Store } from "@/store";
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+import { FunctionIcon } from "./icons";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+/** Replaces `TreeNode/FunctionNode.vue`. Same signature-vs-name fallback
+ * as ProcedureNode. */
+export function FunctionNode({ node, keyword }: Props) {
+ const dbSchema = useDBSchemaV1Store();
+ const target = (node as TreeNode<"function">).meta.target;
+
+ const functionMetadata = useVueState(
+ () =>
+ dbSchema.getSchemaMetadata({
+ database: target.database,
+ schema: target.schema,
+ })?.functions[target.position]
+ );
+
+ return (
+ <CommonNode
+ text={(functionMetadata?.signature || functionMetadata?.name) ?? ""}
+ keyword={keyword}
+ highlight={true}
+ indent={0}
+ icon={<FunctionIcon />}
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/IndexNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/IndexNode.tsx
new file mode 100644
index 0000000000..7f575db2e0
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/IndexNode.tsx
@@ -0,0 +1,45 @@
+import { useVueState } from "@/react/hooks/useVueState";
+import { useDBSchemaV1Store } from "@/store";
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+import { IndexIcon, PrimaryKeyIcon } from "./icons";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+/**
+ * Replaces `TreeNode/IndexNode.vue`. PrimaryKeyIcon when the index is
+ * marked `primary`, IndexIcon otherwise.
+ */
+export function IndexNode({ node, keyword }: Props) {
+ const dbSchema = useDBSchemaV1Store();
+ const target = (node as TreeNode<"index">).meta.target;
+
+ const isPrimaryKey = useVueState(() => {
+ const { database, schema, table, index } = target;
+ const tableMetadata = dbSchema.getTableMetadata({
+ database,
+ schema,
+ table,
+ });
+ return !!tableMetadata.indexes.find((i) => i.name === index)?.primary;
+ });
+
+ return (
+ <CommonNode
+ text={target.index}
+ keyword={keyword}
+ highlight={true}
+ indent={0}
+ icon={
+ isPrimaryKey ? (
+ <PrimaryKeyIcon />
+ ) : (
+ <IndexIcon className="size-4! text-accent/80" />
+ )
+ }
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/Label.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/Label.test.tsx
new file mode 100644
index 0000000000..8f3c791ed7
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/Label.test.tsx
@@ -0,0 +1,135 @@
+import { act, type ReactElement } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import type { NodeType, TreeNode } from "../schemaTree";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+// Mock every leaf so Label's dispatch is the only thing exercised here.
+// Each mock renders a deterministic data-testid so the assertion can match
+// type → component without standing up the real render path (the leaves
+// already have their own tests).
+vi.mock("./DatabaseNode", () => ({
+ DatabaseNode: () => <div data-testid="DatabaseNode" />,
+}));
+vi.mock("./SchemaNode", () => ({
+ SchemaNode: () => <div data-testid="SchemaNode" />,
+}));
+vi.mock("./TableNode", () => ({
+ TableNode: () => <div data-testid="TableNode" />,
+}));
+vi.mock("./ExternalTableNode", () => ({
+ ExternalTableNode: () => <div data-testid="ExternalTableNode" />,
+}));
+vi.mock("./ViewNode", () => ({
+ ViewNode: () => <div data-testid="ViewNode" />,
+}));
+vi.mock("./ColumnNode", () => ({
+ ColumnNode: () => <div data-testid="ColumnNode" />,
+}));
+vi.mock("./IndexNode", () => ({
+ IndexNode: () => <div data-testid="IndexNode" />,
+}));
+vi.mock("./ForeignKeyNode", () => ({
+ ForeignKeyNode: () => <div data-testid="ForeignKeyNode" />,
+}));
+vi.mock("./CheckNode", () => ({
+ CheckNode: () => <div data-testid="CheckNode" />,
+}));
+vi.mock("./PartitionTableNode", () => ({
+ PartitionTableNode: () => <div data-testid="PartitionTableNode" />,
+}));
+vi.mock("./DependencyColumnNode", () => ({
+ DependencyColumnNode: () => <div data-testid="DependencyColumnNode" />,
+}));
+vi.mock("./ProcedureNode", () => ({
+ ProcedureNode: () => <div data-testid="ProcedureNode" />,
+}));
+vi.mock("./PackageNode", () => ({
+ PackageNode: () => <div data-testid="PackageNode" />,
+}));
+vi.mock("./FunctionNode", () => ({
+ FunctionNode: () => <div data-testid="FunctionNode" />,
+}));
+vi.mock("./SequenceNode", () => ({
+ SequenceNode: () => <div data-testid="SequenceNode" />,
+}));
+vi.mock("./TriggerNode", () => ({
+ TriggerNode: () => <div data-testid="TriggerNode" />,
+}));
+vi.mock("./TextNode", () => ({
+ TextNode: () => <div data-testid="TextNode" />,
+}));
+vi.mock("./DummyNode", () => ({
+ DummyNode: () => <div data-testid="DummyNode" />,
+}));
+
+let Label: typeof import("./Label").Label;
+
+const renderIntoContainer = (element: ReactElement) => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ document.body.appendChild(container);
+ return {
+ container,
+ render: () => {
+ act(() => {
+ root.render(element);
+ });
+ },
+ unmount: () => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ },
+ };
+};
+
+const makeNode = (type: NodeType): TreeNode =>
+ ({
+ key: `${type}/k`,
+ meta: { type, target: {} },
+ }) as unknown as TreeNode;
+
+beforeEach(async () => {
+ ({ Label } = await import("./Label"));
+});
+
+const cases: ReadonlyArray<readonly [NodeType, string]> = [
+ ["database", "DatabaseNode"],
+ ["schema", "SchemaNode"],
+ ["table", "TableNode"],
+ ["external-table", "ExternalTableNode"],
+ ["view", "ViewNode"],
+ ["column", "ColumnNode"],
+ ["index", "IndexNode"],
+ ["foreign-key", "ForeignKeyNode"],
+ ["check", "CheckNode"],
+ ["partition-table", "PartitionTableNode"],
+ ["dependency-column", "DependencyColumnNode"],
+ ["procedure", "ProcedureNode"],
+ ["package", "PackageNode"],
+ ["function", "FunctionNode"],
+ ["sequence", "SequenceNode"],
+ ["trigger", "TriggerNode"],
+ ["expandable-text", "TextNode"],
+ ["error", "DummyNode"],
+];
+
+describe("SchemaPane Label", () => {
+ for (const [type, expectedTestId] of cases) {
+ test(`dispatches to ${expectedTestId} for type=${type}`, () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <Label node={makeNode(type)} keyword="" />
+ );
+ render();
+ expect(
+ container.querySelector(`[data-testid="${expectedTestId}"]`)
+ ).not.toBeNull();
+ unmount();
+ });
+ }
+});
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/Label.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/Label.tsx
new file mode 100644
index 0000000000..122ed1582f
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/Label.tsx
@@ -0,0 +1,72 @@
+import type { TreeNode } from "../schemaTree";
+import { CheckNode } from "./CheckNode";
+import { ColumnNode } from "./ColumnNode";
+import { DatabaseNode } from "./DatabaseNode";
+import { DependencyColumnNode } from "./DependencyColumnNode";
+import { DummyNode } from "./DummyNode";
+import { ExternalTableNode } from "./ExternalTableNode";
+import { ForeignKeyNode } from "./ForeignKeyNode";
+import { FunctionNode } from "./FunctionNode";
+import { IndexNode } from "./IndexNode";
+import { PackageNode } from "./PackageNode";
+import { PartitionTableNode } from "./PartitionTableNode";
+import { ProcedureNode } from "./ProcedureNode";
+import { SchemaNode } from "./SchemaNode";
+import { SequenceNode } from "./SequenceNode";
+import { TableNode } from "./TableNode";
+import { TextNode } from "./TextNode";
+import { TriggerNode } from "./TriggerNode";
+import { ViewNode } from "./ViewNode";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+/**
+ * Replaces `TreeNode/Label.vue`. Renders the right per-type leaf
+ * component for the given tree node. Mirrors the Vue dispatcher's order
+ * exactly — the 18 branches map 1:1 to Vue's `<template v-if>` chain.
+ */
+export function Label({ node, keyword }: Props) {
+ switch (node.meta.type) {
+ case "database":
+ return <DatabaseNode node={node} keyword={keyword} />;
+ case "schema":
+ return <SchemaNode node={node} keyword={keyword} />;
+ case "table":
+ return <TableNode node={node} keyword={keyword} />;
+ case "external-table":
+ return <ExternalTableNode node={node} keyword={keyword} />;
+ case "column":
+ return <ColumnNode node={node} keyword={keyword} />;
+ case "index":
+ return <IndexNode node={node} keyword={keyword} />;
+ case "foreign-key":
+ return <ForeignKeyNode node={node} keyword={keyword} />;
+ case "check":
+ return <CheckNode node={node} keyword={keyword} />;
+ case "partition-table":
+ return <PartitionTableNode node={node} keyword={keyword} />;
+ case "view":
+ return <ViewNode node={node} keyword={keyword} />;
+ case "dependency-column":
+ return <DependencyColumnNode node={node} keyword={keyword} />;
+ case "procedure":
+ return <ProcedureNode node={node} keyword={keyword} />;
+ case "package":
+ return <PackageNode node={node} keyword={keyword} />;
+ case "function":
+ return <FunctionNode node={node} keyword={keyword} />;
+ case "sequence":
+ return <SequenceNode node={node} keyword={keyword} />;
+ case "trigger":
+ return <TriggerNode node={node} keyword={keyword} />;
+ case "expandable-text":
+ return <TextNode node={node} keyword={keyword} />;
+ case "error":
+ return <DummyNode node={node} keyword={keyword} />;
+ default:
+ return null;
+ }
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/PackageNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/PackageNode.tsx
new file mode 100644
index 0000000000..d40e22d0a3
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/PackageNode.tsx
@@ -0,0 +1,21 @@
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+import { PackageIcon } from "./icons";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+export function PackageNode({ node, keyword }: Props) {
+ const target = (node as TreeNode<"package">).meta.target;
+ return (
+ <CommonNode
+ text={target.package}
+ keyword={keyword}
+ highlight={true}
+ indent={0}
+ icon={<PackageIcon />}
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/PartitionTableNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/PartitionTableNode.tsx
new file mode 100644
index 0000000000..6e93118b0e
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/PartitionTableNode.tsx
@@ -0,0 +1,21 @@
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+import { TablePartitionIcon } from "./icons";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+export function PartitionTableNode({ node, keyword }: Props) {
+ const target = (node as TreeNode<"partition-table">).meta.target;
+ return (
+ <CommonNode
+ text={target.partition}
+ keyword={keyword}
+ highlight={true}
+ indent={0}
+ icon={<TablePartitionIcon />}
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ProcedureNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ProcedureNode.tsx
new file mode 100644
index 0000000000..688fba527d
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ProcedureNode.tsx
@@ -0,0 +1,38 @@
+import { useVueState } from "@/react/hooks/useVueState";
+import { useDBSchemaV1Store } from "@/store";
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+import { ProcedureIcon } from "./icons";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+/**
+ * Replaces `TreeNode/ProcedureNode.vue`. Reads procedure metadata to
+ * prefer the resolved `signature` over the bare `name` (engines like
+ * Oracle expose overloads where signature is the disambiguator).
+ */
+export function ProcedureNode({ node, keyword }: Props) {
+ const dbSchema = useDBSchemaV1Store();
+ const target = (node as TreeNode<"procedure">).meta.target;
+
+ const procedureMetadata = useVueState(
+ () =>
+ dbSchema.getSchemaMetadata({
+ database: target.database,
+ schema: target.schema,
+ })?.procedures[target.position]
+ );
+
+ return (
+ <CommonNode
+ text={(procedureMetadata?.signature || procedureMetadata?.name) ?? ""}
+ keyword={keyword}
+ highlight={true}
+ indent={0}
+ icon={<ProcedureIcon />}
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/SchemaNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/SchemaNode.tsx
new file mode 100644
index 0000000000..68c73212e7
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/SchemaNode.tsx
@@ -0,0 +1,28 @@
+import { Box } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+/**
+ * Replaces `TreeNode/SchemaNode.vue`. Schema namespace node — falls
+ * back to the i18n "default" label when the schema name is empty.
+ */
+export function SchemaNode({ node, keyword }: Props) {
+ const { t } = useTranslation();
+ const target = (node as TreeNode<"schema">).meta.target;
+
+ return (
+ <CommonNode
+ text={target.schema}
+ keyword={keyword}
+ highlight={true}
+ icon={<Box className="size-4" />}
+ fallbackText={<>{t("db.schema.default")}</>}
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/SequenceNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/SequenceNode.tsx
new file mode 100644
index 0000000000..2792e258f5
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/SequenceNode.tsx
@@ -0,0 +1,21 @@
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+import { SequenceIcon } from "./icons";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+export function SequenceNode({ node, keyword }: Props) {
+ const target = (node as TreeNode<"sequence">).meta.target;
+ return (
+ <CommonNode
+ text={target.sequence}
+ keyword={keyword}
+ highlight={true}
+ indent={0}
+ icon={<SequenceIcon />}
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/TableNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/TableNode.tsx
new file mode 100644
index 0000000000..18835c2e0e
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/TableNode.tsx
@@ -0,0 +1,20 @@
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+import { TableLeafIcon } from "./icons";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+export function TableNode({ node, keyword }: Props) {
+ const target = (node as TreeNode<"table">).meta.target;
+ return (
+ <CommonNode
+ text={target.table}
+ keyword={keyword}
+ highlight={true}
+ icon={<TableLeafIcon />}
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/TextNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/TextNode.tsx
new file mode 100644
index 0000000000..173ecaf9da
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/TextNode.tsx
@@ -0,0 +1,32 @@
+import { Folder } from "lucide-react";
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+/**
+ * Replaces `TreeNode/TextNode.vue`. Folder-style row used for "Tables /
+ * Views / Indexes / …" headers. If the target sets a `render` ReactNode,
+ * we pass it through CommonNode's `children` slot to override the
+ * default text+icon layout entirely.
+ */
+export function TextNode({ node }: Props) {
+ const target = (node as TreeNode<"expandable-text">).meta.target;
+ const text = typeof target.text === "function" ? target.text() : target.text;
+
+ if (target.render) {
+ return <CommonNode text={text}>{target.render}</CommonNode>;
+ }
+
+ return (
+ <CommonNode
+ text={text}
+ highlight={false}
+ data-mock-type={target.mockType}
+ icon={<Folder className="size-4 stroke-accent fill-accent/10" />}
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/TriggerNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/TriggerNode.tsx
new file mode 100644
index 0000000000..8707962180
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/TriggerNode.tsx
@@ -0,0 +1,21 @@
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+import { TriggerIcon } from "./icons";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+export function TriggerNode({ node, keyword }: Props) {
+ const target = (node as TreeNode<"trigger">).meta.target;
+ return (
+ <CommonNode
+ text={target.trigger}
+ keyword={keyword}
+ highlight={true}
+ indent={0}
+ icon={<TriggerIcon />}
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ViewNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ViewNode.tsx
new file mode 100644
index 0000000000..61564484b8
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ViewNode.tsx
@@ -0,0 +1,21 @@
+import type { TreeNode } from "../schemaTree";
+import { CommonNode } from "./CommonNode";
+import { ViewIcon } from "./icons";
+
+type Props = {
+ readonly node: TreeNode;
+ readonly keyword: string;
+};
+
+export function ViewNode({ node, keyword }: Props) {
+ const target = (node as TreeNode<"view">).meta.target;
+ return (
+ <CommonNode
+ text={target.view}
+ keyword={keyword}
+ highlight={true}
+ indent={0}
+ icon={<ViewIcon />}
+ />
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/icons.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/icons.tsx
new file mode 100644
index 0000000000..4e6b9fff6f
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/icons.tsx
@@ -0,0 +1,151 @@
+import {
+ Check,
+ Diamond,
+ Glasses,
+ Key,
+ Link,
+ Package,
+ Parentheses,
+ SquareFunction,
+ Table,
+ TableProperties,
+ TableRowsSplit,
+ Zap,
+} from "lucide-react";
+import { cn } from "@/react/lib/utils";
+
+/**
+ * React equivalents of `frontend/src/components/Icon/*Icon.vue`. Kept
+ * local to the SchemaPane port for now; will lift to a shared
+ * `src/react/components/Icon/` directory if Stage 16+ surfaces need them.
+ *
+ * Each icon mirrors its Vue counterpart's tint / stroke choices so the
+ * tree visually matches the Vue version 1:1.
+ */
+
+type IconProps = {
+ readonly className?: string;
+};
+
+const baseSize = "size-4";
+
+export function TableLeafIcon({ className }: IconProps) {
+ return <Table className={cn(baseSize, className)} />;
+}
+
+export function ExternalTableIcon({ className }: IconProps) {
+ return <TableProperties className={cn(baseSize, className)} />;
+}
+
+export function ViewIcon({ className }: IconProps) {
+ return (
+ <div className={cn("relative", baseSize, className)}>
+ <Table className={cn(baseSize, "text-gray-400")} />
+ <Glasses
+ className="absolute bottom-0 right-0 w-3/4 h-3/4 fill-white"
+ stroke="rgb(var(--color-accent))"
+ strokeWidth={3.5}
+ />
+ </div>
+ );
+}
+
+export function ProcedureIcon({ className }: IconProps) {
+ return <Parentheses className={cn(baseSize, "text-gray-400", className)} />;
+}
+
+export function FunctionIcon({ className }: IconProps) {
+ return (
+ <SquareFunction className={cn(baseSize, "text-gray-400", className)} />
+ );
+}
+
+/**
+ * Vue's SequenceIcon is a custom 3.5×3-rem framed "123" — there is no
+ * lucide equivalent, so we replicate the markup verbatim.
+ */
+export function SequenceIcon({ className }: IconProps) {
+ return (
+ <div
+ className={cn(
+ "relative w-4 h-4 inline-flex items-center justify-center text-gray-500",
+ className
+ )}
+ >
+ <div className="border-y border-current w-3.5 h-3 inline-flex items-center justify-center text-[7px] overflow-visible whitespace-nowrap font-semibold">
+ <span className="leading-3">123</span>
+ </div>
+ </div>
+ );
+}
+
+export function TriggerIcon({ className }: IconProps) {
+ return <Zap className={cn(baseSize, "text-amber-500", className)} />;
+}
+
+export function PackageIcon({ className }: IconProps) {
+ return <Package className={cn(baseSize, "text-gray-400", className)} />;
+}
+
+export function ForeignKeyIcon({ className }: IconProps) {
+ return <Link className={cn("size-3.5 text-gray-500", className)} />;
+}
+
+export function TablePartitionIcon({ className }: IconProps) {
+ return (
+ <TableRowsSplit
+ className={cn(baseSize, "opacity-75", className)}
+ strokeWidth={1.75}
+ />
+ );
+}
+
+/**
+ * Vue's PrimaryKeyIcon is heroicons/key in `text-amber-500`.
+ */
+export function PrimaryKeyIcon({ className }: IconProps) {
+ return (
+ <div className={cn("relative overflow-hidden", baseSize, className)}>
+ <Key className="w-full h-full mx-auto text-amber-500" />
+ </div>
+ );
+}
+
+/**
+ * Vue's IndexIcon is tabler/diamonds (a 3-diamond cluster) — lucide's
+ * Diamond is a single diamond which is close enough at 12-14px.
+ */
+export function IndexIcon({ className }: IconProps) {
+ return <Diamond className={cn("w-3 h-3", className)} />;
+}
+
+/**
+ * Vue's CheckIcon is tabler/check at 12px in `text-gray-500`.
+ */
+export function CheckConstraintIcon({ className }: IconProps) {
+ return <Check className={cn("size-3.5 text-gray-500", className)} />;
+}
+
+/**
+ * Vue's ColumnIcon is a hand-edited "lucide:columns-3" with the second
+ * gap line removed (single column instead of two). Reproduce the SVG.
+ */
+export function ColumnIcon({ className }: IconProps) {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className={cn(baseSize, "text-gray-500", className)}
+ >
+ <rect width="18" height="18" x="3" y="3" rx="2" />
+ <path d="M9 3v18" />
+ </svg>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx
new file mode 100644
index 0000000000..d205b0c02a
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx
@@ -0,0 +1,305 @@
+import { act, type ReactElement } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import type { NodeTarget, NodeType, TreeNode } from "./schemaTree";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => {
+ return {
+ getDatabaseByName: vi.fn(() => ({
+ name: "instances/i/databases/db",
+ project: "projects/p",
+ effectiveEnvironment: "environments/prod",
+ labels: {},
+ // shape is enough for getInstanceResource → engine
+ instanceResource: {
+ engine: 1, // MYSQL
+ engineVersion: "8.0",
+ },
+ })),
+ getTableMetadata: vi.fn(() => ({
+ columns: [{ name: "id" }, { name: "email" }],
+ })),
+ getInstanceResource: vi.fn(() => ({ engine: 1 })),
+ instanceV1HasAlterSchema: vi.fn(() => true),
+ supportGetStringSchema: vi.fn(() => true),
+ sortByDictionary: vi.fn(
+ <T,>(arr: T[], order: string[], keyFn: (i: T) => string) => {
+ arr.sort((a, b) => {
+ const ai = order.indexOf(keyFn(a));
+ const bi = order.indexOf(keyFn(b));
+ if (ai === -1 && bi === -1) return 0;
+ if (ai === -1) return 1;
+ if (bi === -1) return -1;
+ return ai - bi;
+ });
+ }
+ ),
+ };
+});
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (k: string) => k }),
+ initReactI18next: { type: "3rdParty", init: () => {} },
+}));
+
+vi.mock("@/react/i18n", () => ({
+ default: { t: (k: string) => k },
+}));
+
+vi.mock("@/store", () => ({
+ pushNotification: vi.fn(),
+ useDatabaseV1Store: () => ({ getDatabaseByName: mocks.getDatabaseByName }),
+ useDBSchemaV1Store: () => ({ getTableMetadata: mocks.getTableMetadata }),
+ useSQLEditorTabStore: () => ({
+ currentTab: { id: "t1", viewState: { schema: "" } },
+ openTabList: [],
+ addTab: vi.fn(),
+ setCurrentTabId: vi.fn(),
+ updateCurrentTab: vi.fn(),
+ updateTab: vi.fn(),
+ }),
+}));
+
+vi.mock("@/utils", () => ({
+ // Stub everything actions.tsx imports. We don't `importOriginal` here
+ // because the real `@/utils` transitively pulls in monaco / vue
+ // surfaces that vitest can't load.
+ defaultSQLEditorTab: () => ({
+ id: "new",
+ title: "Untitled",
+ connection: { instance: "", database: "" },
+ viewState: { view: "CODE" },
+ treeState: {},
+ editorState: { selection: null },
+ mode: "WORKSHEET",
+ status: "NEW",
+ }),
+ extractDatabaseResourceName: (n: string) => ({
+ instance: "instances/i",
+ databaseName: n.split("/").pop() ?? "",
+ }),
+ extractInstanceResourceName: (n: string) => n.split("/").pop() ?? "",
+ extractProjectResourceName: (n: string) => n.split("/").pop() ?? "",
+ generateSimpleDeleteStatement: () => "DELETE",
+ generateSimpleInsertStatement: () => "INSERT",
+ generateSimpleSelectAllStatement: () => "SELECT *",
+ generateSimpleUpdateStatement: () => "UPDATE",
+ getInstanceResource: mocks.getInstanceResource,
+ instanceV1HasAlterSchema: mocks.instanceV1HasAlterSchema,
+ isSameSQLEditorConnection: () => false,
+ sortByDictionary: mocks.sortByDictionary,
+ supportGetStringSchema: mocks.supportGetStringSchema,
+ isDev: () => false,
+}));
+
+vi.mock("@/types", () => ({
+ DEFAULT_SQL_EDITOR_TAB_MODE: "WORKSHEET",
+ dialectOfEngineV1: () => "MYSQL",
+ languageOfEngineV1: () => "sql",
+ typeToView: (type: string) => type.toUpperCase(),
+}));
+
+vi.mock("@/types/proto-es/v1/common_pb", () => ({
+ Engine: { REDIS: 7, MYSQL: 1 },
+}));
+
+vi.mock("@/types/proto-es/v1/database_service_pb", () => ({
+ GetSchemaStringRequest_ObjectType: { TABLE: 1, VIEW: 2 },
+}));
+
+vi.mock("@/router", () => ({
+ router: {
+ resolve: () => ({ href: "/sql-editor/db" }),
+ },
+}));
+
+vi.mock("@/router/sqlEditor", () => ({
+ SQL_EDITOR_DATABASE_MODULE: "sql-editor.database",
+}));
+
+vi.mock("@/views/sql-editor/EditorCommon/utils", () => ({
+ keyWithPosition: (k: string, p: number) => `${k}###${p}`,
+}));
+
+vi.mock("@/views/sql-editor/events", () => ({
+ sqlEditorEvents: { emit: vi.fn() },
+}));
+
+vi.mock("@/composables/useExecuteSQL", () => ({
+ useExecuteSQL: () => ({ execute: vi.fn() }),
+}));
+
+vi.mock("@/components/MonacoEditor/sqlFormatter", () => ({
+ default: async (sql: string) => ({ data: sql, error: null }),
+}));
+
+vi.mock("@/types/sqlEditor/tabViewState", () => ({
+ defaultViewState: () => ({ view: "CODE" }),
+}));
+
+let useSchemaPaneContextMenu: typeof import("./actions").useSchemaPaneContextMenu;
+type SchemaMenuItem = import("./actions").SchemaMenuItem;
+
+beforeEach(async () => {
+ ({ useSchemaPaneContextMenu } = await import("./actions"));
+});
+
+const DATABASE = "instances/i/databases/db";
+
+const makeNode = (type: NodeType, target: Partial<NodeTarget>): TreeNode =>
+ ({
+ key: `${type}/k`,
+ meta: {
+ type,
+ target: { database: DATABASE, ...target },
+ },
+ }) as unknown as TreeNode;
+
+function captureItems(
+ node: TreeNode | null,
+ deps: { availableActions: never[]; setSchemaViewer: () => void }
+) {
+ const captured: { items?: SchemaMenuItem[] } = {};
+ function Probe() {
+ captured.items = useSchemaPaneContextMenu(node, deps);
+ return null;
+ }
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ act(() => {
+ root.render((<Probe />) as ReactElement);
+ });
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ return captured.items ?? [];
+}
+
+const noopDeps = {
+ availableActions: [] as never[],
+ setSchemaViewer: () => {},
+};
+
+describe("useSchemaPaneContextMenu", () => {
+ test("returns empty for a null node", () => {
+ expect(captureItems(null, noopDeps)).toEqual([]);
+ });
+
+ test("returns empty for a disabled node", () => {
+ const node = {
+ ...makeNode("error", { id: "x", expandable: false, text: () => "" }),
+ disabled: true,
+ } as unknown as TreeNode;
+ expect(captureItems(node, noopDeps)).toEqual([]);
+ });
+
+ test("table node populates copy-name / copy-all-columns / view-schema-text / edit-schema / copy-url / preview / generate-sql / view-detail", () => {
+ const node = makeNode("table", {
+ database: DATABASE,
+ schema: "public",
+ table: "users",
+ });
+ const items = captureItems(node, noopDeps);
+ const keys = items.map((i) => i.key);
+ expect(keys).toEqual([
+ "copy-name",
+ "copy-all-column-names",
+ "preview-table-data",
+ "generate-sql",
+ "view-schema-text",
+ "view-detail",
+ "edit-schema",
+ "copy-url",
+ ]);
+ const generate = items.find((i) => i.key === "generate-sql");
+ expect(generate?.children?.map((c) => c.key)).toEqual([
+ "generate-sql--select",
+ "generate-sql--insert",
+ "generate-sql--update",
+ "generate-sql--delete",
+ ]);
+ });
+
+ test("view node yields copy-name + view-schema-text + preview-table + generate-sql(SELECT only) + view-detail", () => {
+ const node = makeNode("view", {
+ database: DATABASE,
+ schema: "public",
+ view: "v_active",
+ });
+ const items = captureItems(node, noopDeps);
+ const keys = items.map((i) => i.key);
+ expect(keys).toEqual([
+ "copy-name",
+ "preview-table-data",
+ "generate-sql",
+ "view-schema-text",
+ "view-detail",
+ ]);
+ const generate = items.find((i) => i.key === "generate-sql");
+ expect(generate?.children?.map((c) => c.key)).toEqual([
+ "generate-sql--select",
+ ]);
+ });
+
+ test("procedure / function / trigger nodes only yield view-detail", () => {
+ for (const type of ["procedure", "function", "trigger"] as const) {
+ const node = makeNode(type, {
+ database: DATABASE,
+ schema: "public",
+ ...(type === "procedure"
+ ? { procedure: "p", position: 0 }
+ : type === "function"
+ ? { function: "f", position: 0 }
+ : { trigger: "trg", position: 0, table: "t" }),
+ });
+ const items = captureItems(node, noopDeps);
+ expect(items.map((i) => i.key)).toEqual(["view-detail"]);
+ }
+ });
+
+ test("schema node renders one item per availableAction in given order", () => {
+ const node = makeNode("schema", {
+ database: DATABASE,
+ schema: "public",
+ });
+ const deps = {
+ availableActions: [
+ { view: "TABLES", title: "Tables", icon: null },
+ { view: "VIEWS", title: "Views", icon: null },
+ ],
+ setSchemaViewer: () => {},
+ };
+ const items = captureItems(node, deps as unknown as typeof noopDeps);
+ expect(items.map((i) => i.label)).toEqual(["Tables", "Views"]);
+ });
+
+ test("REDIS engine drops generate-sql + preview", () => {
+ // The hook calls getInstanceResource several times across schema /
+ // generate-sql / view-schema-text checks, so we need a persistent
+ // mock for this test rather than `mockReturnValueOnce`.
+ mocks.getInstanceResource.mockReturnValue({ engine: 7 }); // REDIS
+ mocks.supportGetStringSchema.mockReturnValue(false);
+ mocks.instanceV1HasAlterSchema.mockReturnValue(false);
+ try {
+ const node = makeNode("table", {
+ database: DATABASE,
+ schema: "",
+ table: "users",
+ });
+ const items = captureItems(node, noopDeps);
+ const keys = items.map((i) => i.key);
+ expect(keys).not.toContain("preview-table-data");
+ expect(keys).not.toContain("generate-sql");
+ } finally {
+ mocks.getInstanceResource.mockReturnValue({ engine: 1 });
+ mocks.supportGetStringSchema.mockReturnValue(true);
+ mocks.instanceV1HasAlterSchema.mockReturnValue(true);
+ }
+ });
+});
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx b/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx
new file mode 100644
index 0000000000..20a3e990a0
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx
@@ -0,0 +1,665 @@
+import { cloneDeep } from "lodash-es";
+import {
+ Code,
+ Copy,
+ ExternalLink,
+ FileCode,
+ FileDiff,
+ FileMinus,
+ FilePlus,
+ FileSearch2,
+ Link as LinkIcon,
+ SquarePen,
+ Table as TableIcon,
+} from "lucide-react";
+import type { ReactNode } from "react";
+import { useCallback, useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import formatSQL from "@/components/MonacoEditor/sqlFormatter";
+import { useExecuteSQL } from "@/composables/useExecuteSQL";
+import { router } from "@/router";
+import { SQL_EDITOR_DATABASE_MODULE } from "@/router/sqlEditor";
+import {
+ pushNotification,
+ useDatabaseV1Store,
+ useDBSchemaV1Store,
+ useSQLEditorTabStore,
+} from "@/store";
+import {
+ DEFAULT_SQL_EDITOR_TAB_MODE,
+ dialectOfEngineV1,
+ type EditorPanelView,
+ type EditorPanelViewState,
+ languageOfEngineV1,
+ type SQLEditorConnection,
+ type SQLEditorTab,
+ typeToView,
+} from "@/types";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import {
+ type Database,
+ GetSchemaStringRequest_ObjectType,
+} from "@/types/proto-es/v1/database_service_pb";
+import { defaultViewState } from "@/types/sqlEditor/tabViewState";
+import {
+ defaultSQLEditorTab,
+ extractDatabaseResourceName,
+ extractInstanceResourceName,
+ extractProjectResourceName,
+ generateSimpleDeleteStatement,
+ generateSimpleInsertStatement,
+ generateSimpleSelectAllStatement,
+ generateSimpleUpdateStatement,
+ getInstanceResource,
+ instanceV1HasAlterSchema,
+ isSameSQLEditorConnection,
+ sortByDictionary,
+ supportGetStringSchema,
+} from "@/utils";
+import { keyWithPosition } from "@/views/sql-editor/EditorCommon/utils";
+import { sqlEditorEvents } from "@/views/sql-editor/events";
+import {
+ type NodeTarget,
+ type NodeType,
+ readableTextForNodeTarget,
+ type TreeNode,
+} from "./schemaTree";
+
+const SELECT_ALL_LIMIT = 50;
+
+/**
+ * Schema-pane "view detail" panel actions. Mirrors Vue's
+ * `useCurrentTabViewStateContext().availableActions` — the consumer
+ * (SchemaPane.tsx) computes this from the active connection's instance
+ * and passes it in. We don't recompute it here so the per-instance
+ * support gating stays a single source of truth.
+ */
+export type AvailableAction = {
+ readonly view: EditorPanelView;
+ readonly title: string;
+ readonly icon: ReactNode;
+};
+
+/**
+ * Replaces `SchemaPane/actions.tsx` Vue exports. Two factories:
+ * - `useSchemaPaneActions()` — invokable handlers (selectAll, viewDetail,
+ * openNewTab).
+ * - `useSchemaPaneContextMenu(node, deps)` — nested menu items keyed by
+ * `node.meta.type`, mirroring the Vue dropdown 1:1 (item order +
+ * nesting + i18n keys).
+ *
+ * The schema-viewer modal's lifecycle stays in SchemaPane.tsx (it owns
+ * the React state). The hook receives `setSchemaViewer` so menu items
+ * can ask the panel to open the viewer.
+ */
+
+/**
+ * Pure helper: resolve the engine for a target without standing up a
+ * Vue reactive computed.
+ */
+const engineForDatabase = (database: string): Engine => {
+ const db = useDatabaseV1Store().getDatabaseByName(database);
+ return getInstanceResource(db).engine;
+};
+
+const targetSupportsGenerateSQL = (target: NodeTarget): boolean => {
+ const { database } = target as NodeTarget<"database">;
+ return engineForDatabase(database) !== Engine.REDIS;
+};
+
+const formatCode = async (code: string, engine: Engine): Promise<string> => {
+ const lang = languageOfEngineV1(engine);
+ if (lang !== "sql") return code;
+ try {
+ const result = await formatSQL(code, dialectOfEngineV1(engine));
+ return result.error ? code : result.data;
+ } catch {
+ return code;
+ }
+};
+
+/**
+ * Push the generated SQL into the active editor tab. If there is no
+ * active tab, fall back to copying to the clipboard so the user doesn't
+ * lose the work.
+ */
+const applyContentToCurrentTabOrCopyToClipboard = async (
+ content: string,
+ notify: (key: string) => void
+) => {
+ const tab = useSQLEditorTabStore().currentTab;
+ if (!tab) {
+ await copyToClipboard(content, notify);
+ return;
+ }
+ void sqlEditorEvents.emit("append-editor-content", {
+ content,
+ select: true,
+ });
+};
+
+const copyToClipboard = async (
+ content: string,
+ notify: (key: string) => void
+) => {
+ if (typeof navigator === "undefined" || !navigator.clipboard) return;
+ try {
+ await navigator.clipboard.writeText(content);
+ notify("common.copied");
+ } catch {
+ // Silent fail — matches Vue's `if (!isSupported.value) return` behavior.
+ }
+};
+
+const updateCurrentTabViewState = (patch: Partial<EditorPanelViewState>) => {
+ const tabStore = useSQLEditorTabStore();
+ const tab = tabStore.currentTab;
+ if (!tab) return;
+ tabStore.updateTab(tab.id, {
+ viewState: {
+ ...defaultViewState(),
+ ...tab.viewState,
+ ...patch,
+ },
+ });
+};
+
+const runQuery = async (
+ database: Database,
+ schema: string | undefined,
+ tableOrViewName: string,
+ statement: string
+) => {
+ const tabStore = useSQLEditorTabStore();
+ const tab = tabStore.currentTab;
+ if (!tab) return;
+ if (tab.mode === "ADMIN") {
+ tabStore.updateCurrentTab({ mode: DEFAULT_SQL_EDITOR_TAB_MODE });
+ }
+ const { execute } = useExecuteSQL();
+ const connection: SQLEditorConnection = {
+ instance: extractDatabaseResourceName(database.name).instance,
+ database: database.name,
+ schema: schema ?? "",
+ table: tableOrViewName,
+ };
+ // Yield once so any state updates above flush before execute reads
+ // the tab — mirrors Vue's `await nextTick()` in the original.
+ await Promise.resolve();
+ execute({
+ statement,
+ connection,
+ explain: false,
+ engine: getInstanceResource(database).engine,
+ selection: tab.editorState.selection,
+ });
+};
+
+export function useSchemaPaneActions() {
+ const databaseStore = useDatabaseV1Store();
+ const tabStore = useSQLEditorTabStore();
+
+ const openNewTab = useCallback(
+ (params: {
+ title: string;
+ schema?: string;
+ table?: string;
+ view: EditorPanelView;
+ }) => {
+ const currentViewState = tabStore.currentTab?.viewState;
+ const schema = params.schema ?? currentViewState?.schema;
+ const table = params.table ?? currentViewState?.table;
+
+ const fromTab = tabStore.currentTab;
+ const clonedTab: SQLEditorTab = {
+ ...defaultSQLEditorTab(),
+ status: "CLEAN",
+ title: params.title,
+ };
+ if (fromTab) {
+ clonedTab.connection = cloneDeep(fromTab.connection);
+ clonedTab.treeState = cloneDeep(fromTab.treeState);
+ }
+
+ const findExistedTab = tabStore.openTabList.find((tab) => {
+ if (tab.status !== "CLEAN" || tab.id === fromTab?.id) return false;
+ if (!isSameSQLEditorConnection(tab.connection, clonedTab.connection))
+ return false;
+ const viewState = tab.viewState;
+ if (
+ viewState.view !== params.view ||
+ (schema && viewState.schema !== schema)
+ ) {
+ return false;
+ }
+ return true;
+ });
+
+ if (findExistedTab) {
+ tabStore.setCurrentTabId(findExistedTab.id);
+ } else {
+ tabStore.addTab(clonedTab);
+ updateCurrentTabViewState({ view: params.view, schema, table });
+ }
+ },
+ [tabStore]
+ );
+
+ const selectAllFromTableOrView = useCallback(
+ async (node: TreeNode) => {
+ const { target, type } = (node as TreeNode<"table" | "view">).meta;
+ if (!targetSupportsGenerateSQL(target)) return;
+
+ const tableOrViewName = readableTextForNodeTarget(type, target);
+ if (!tableOrViewName) return;
+
+ const { database, schema } = target;
+ const db = databaseStore.getDatabaseByName(database);
+ const engine = getInstanceResource(db).engine;
+
+ const query = await formatCode(
+ generateSimpleSelectAllStatement(
+ engine,
+ schema,
+ tableOrViewName,
+ SELECT_ALL_LIMIT
+ ),
+ engine
+ );
+ updateCurrentTabViewState({ view: "CODE" });
+ await runQuery(db, schema, tableOrViewName, query);
+ },
+ [databaseStore]
+ );
+
+ const viewDetail = useCallback(
+ async (node: TreeNode) => {
+ const { type, target } = node.meta;
+ const SUPPORTED: NodeType[] = [
+ "table",
+ "view",
+ "procedure",
+ "function",
+ "trigger",
+ ];
+ if (!SUPPORTED.includes(type)) return;
+
+ const schema = (target as NodeTarget<"schema">).schema;
+ const table = (target as NodeTarget<"table">).table;
+ openNewTab({
+ title: "View detail",
+ view: typeToView(type),
+ schema,
+ table,
+ });
+ await Promise.resolve();
+
+ const detail: EditorPanelViewState["detail"] = {};
+ let name = "";
+ switch (type) {
+ case "table":
+ name = (target as NodeTarget<"table">).table;
+ detail.table = name;
+ break;
+ case "view":
+ name = (target as NodeTarget<"view">).view;
+ detail.view = name;
+ break;
+ case "procedure": {
+ const { procedure, position } = target as NodeTarget<"procedure">;
+ name = procedure;
+ detail.procedure = keyWithPosition(procedure, position);
+ break;
+ }
+ case "function": {
+ const { function: func, position: funcPosition } =
+ target as NodeTarget<"function">;
+ name = func;
+ detail.func = keyWithPosition(func, funcPosition);
+ break;
+ }
+ case "trigger": {
+ const { trigger, position: triggerPosition } =
+ target as NodeTarget<"trigger">;
+ name = trigger;
+ detail.trigger = keyWithPosition(trigger, triggerPosition);
+ break;
+ }
+ }
+ updateCurrentTabViewState({ detail });
+ if (name) {
+ tabStore.updateCurrentTab({ title: `Detail for ${type} ${name}` });
+ }
+ },
+ [openNewTab, tabStore]
+ );
+
+ return { selectAllFromTableOrView, viewDetail, openNewTab };
+}
+
+export type SchemaMenuItem = {
+ readonly key: string;
+ readonly label: string;
+ readonly icon: ReactNode;
+ readonly onSelect?: () => void;
+ readonly children?: readonly SchemaMenuItem[];
+};
+
+export type SchemaMenuDeps = {
+ readonly availableActions: readonly AvailableAction[];
+ readonly setSchemaViewer: (
+ viewer:
+ | {
+ schema?: string;
+ object?: string;
+ type?: GetSchemaStringRequest_ObjectType;
+ }
+ | undefined
+ ) => void;
+};
+
+const ITEM_ORDER = [
+ "copy-name",
+ "copy-all-column-names",
+ "copy-select-statement",
+ "preview-table-data",
+ "generate-sql",
+ "view-schema-text",
+ "view-detail",
+ "edit-schema",
+ "copy-url",
+];
+
+/**
+ * Mirror Vue's `useDropdown().options` 1:1 — same item ordering, same
+ * branching, same keys. Schema-typed nodes use the consumer-supplied
+ * `availableActions` list (from `useCurrentTabViewStateContext` on the
+ * Vue side) so per-instance support gating lives in one place.
+ *
+ * Returns `[]` for disabled / unsupported nodes; callers should hide
+ * the popup in that case.
+ */
+export function useSchemaPaneContextMenu(
+ node: TreeNode | null,
+ deps: SchemaMenuDeps
+): SchemaMenuItem[] {
+ const { t } = useTranslation();
+ const databaseStore = useDatabaseV1Store();
+ const dbSchema = useDBSchemaV1Store();
+ const { selectAllFromTableOrView, viewDetail, openNewTab } =
+ useSchemaPaneActions();
+
+ const notify = useCallback(
+ (key: string) => {
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t(key),
+ });
+ },
+ [t]
+ );
+
+ return useMemo<SchemaMenuItem[]>(() => {
+ if (!node || node.disabled) return [];
+ const { type, target } = node.meta;
+ const { database, schema } = target as NodeTarget<"schema">;
+ if (!database) return [];
+
+ const db = databaseStore.getDatabaseByName(database);
+ const items: SchemaMenuItem[] = [];
+
+ if (type === "schema") {
+ for (const action of deps.availableActions) {
+ items.push({
+ key: action.view,
+ label: action.title,
+ icon: action.icon,
+ onSelect: () => {
+ openNewTab({
+ title: `[${
+ extractDatabaseResourceName(db.name).databaseName
+ }] ${action.title}`,
+ view: action.view,
+ schema,
+ });
+ },
+ });
+ }
+ }
+
+ if (type === "table" || type === "view") {
+ const tableOrView = readableTextForNodeTarget(
+ type,
+ target as NodeTarget<"table" | "view">
+ );
+
+ items.push({
+ key: "copy-name",
+ label: t("sql-editor.copy-name"),
+ icon: <Copy className="size-4" />,
+ onSelect: () => {
+ const name = schema ? `${schema}.${tableOrView}` : tableOrView;
+ void copyToClipboard(name, notify);
+ },
+ });
+
+ if (type === "view") {
+ const { view } = target as NodeTarget<"view">;
+ if (supportGetStringSchema(getInstanceResource(db).engine)) {
+ items.push({
+ key: "view-schema-text",
+ label: t("sql-editor.view-schema-text"),
+ icon: <Code className="size-4" />,
+ onSelect: () => {
+ deps.setSchemaViewer({
+ schema,
+ object: view,
+ type: GetSchemaStringRequest_ObjectType.VIEW,
+ });
+ },
+ });
+ }
+ }
+
+ if (type === "table") {
+ const { table } = target as NodeTarget<"table">;
+
+ items.push({
+ key: "copy-all-column-names",
+ label: t("sql-editor.copy-all-column-names"),
+ icon: <Copy className="size-4" />,
+ onSelect: () => {
+ const tableMetadata = dbSchema.getTableMetadata({
+ database,
+ schema,
+ table,
+ });
+ const name = tableMetadata.columns
+ .map((col) => col.name)
+ .join(", ");
+ void copyToClipboard(name, notify);
+ },
+ });
+
+ if (supportGetStringSchema(getInstanceResource(db).engine)) {
+ items.push({
+ key: "view-schema-text",
+ label: t("sql-editor.view-schema-text"),
+ icon: <Code className="size-4" />,
+ onSelect: () => {
+ deps.setSchemaViewer({
+ schema,
+ object: table,
+ type: GetSchemaStringRequest_ObjectType.TABLE,
+ });
+ },
+ });
+ }
+
+ if (instanceV1HasAlterSchema(getInstanceResource(db))) {
+ items.push({
+ key: "edit-schema",
+ label: t("database.edit-schema"),
+ icon: <SquarePen className="size-4" />,
+ onSelect: () => {
+ void sqlEditorEvents.emit("alter-schema", {
+ databaseName: db.name,
+ schema: schema,
+ table: table,
+ });
+ },
+ });
+ }
+
+ items.push({
+ key: "copy-url",
+ label: t("sql-editor.copy-url"),
+ icon: <LinkIcon className="size-4" />,
+ onSelect: () => {
+ const { instance, databaseName } = extractDatabaseResourceName(
+ db.name
+ );
+ const route = router.resolve({
+ name: SQL_EDITOR_DATABASE_MODULE,
+ params: {
+ project: extractProjectResourceName(db.project),
+ instance: extractInstanceResourceName(instance),
+ database: databaseName,
+ },
+ query: { table, schema },
+ });
+ const url = new URL(route.href, window.location.origin).href;
+ void copyToClipboard(url, notify);
+ },
+ });
+ }
+
+ if (targetSupportsGenerateSQL(target)) {
+ items.push({
+ key: "preview-table-data",
+ label: t("sql-editor.preview-table-data"),
+ icon: <TableIcon className="size-4" />,
+ onSelect: () => {
+ void selectAllFromTableOrView(node);
+ },
+ });
+ }
+
+ const generateSQLChildren: SchemaMenuItem[] = [];
+ if (targetSupportsGenerateSQL(target)) {
+ const engine = engineForDatabase(database);
+ generateSQLChildren.push({
+ key: "generate-sql--select",
+ label: "SELECT",
+ icon: <FileSearch2 className="size-4" />,
+ onSelect: async () => {
+ const statement = await formatCode(
+ generateSimpleSelectAllStatement(
+ engine,
+ schema,
+ tableOrView,
+ SELECT_ALL_LIMIT
+ ),
+ engine
+ );
+ await applyContentToCurrentTabOrCopyToClipboard(statement, notify);
+ },
+ });
+ if (type === "table") {
+ const { table } = target as NodeTarget<"table">;
+ const tableMetadata = dbSchema.getTableMetadata({
+ database,
+ schema,
+ table,
+ });
+ const columns = tableMetadata.columns.map((c) => c.name);
+
+ generateSQLChildren.push({
+ key: "generate-sql--insert",
+ label: "INSERT",
+ icon: <FilePlus className="size-4" />,
+ onSelect: async () => {
+ const statement = await formatCode(
+ generateSimpleInsertStatement(engine, schema, table, columns),
+ engine
+ );
+ await applyContentToCurrentTabOrCopyToClipboard(
+ statement,
+ notify
+ );
+ },
+ });
+ generateSQLChildren.push({
+ key: "generate-sql--update",
+ label: "UPDATE",
+ icon: <FileDiff className="size-4" />,
+ onSelect: async () => {
+ const statement = await formatCode(
+ generateSimpleUpdateStatement(engine, schema, table, columns),
+ engine
+ );
+ await applyContentToCurrentTabOrCopyToClipboard(
+ statement,
+ notify
+ );
+ },
+ });
+ generateSQLChildren.push({
+ key: "generate-sql--delete",
+ label: "DELETE",
+ icon: <FileMinus className="size-4" />,
+ onSelect: async () => {
+ const statement = await formatCode(
+ generateSimpleDeleteStatement(engine, schema, table),
+ engine
+ );
+ await applyContentToCurrentTabOrCopyToClipboard(
+ statement,
+ notify
+ );
+ },
+ });
+ }
+ }
+ if (generateSQLChildren.length > 0) {
+ items.push({
+ key: "generate-sql",
+ label: t("sql-editor.generate-sql"),
+ icon: <FileCode className="size-4" />,
+ children: generateSQLChildren,
+ });
+ }
+ }
+
+ if (
+ type === "table" ||
+ type === "view" ||
+ type === "procedure" ||
+ type === "function" ||
+ type === "trigger"
+ ) {
+ items.push({
+ key: "view-detail",
+ label: t("sql-editor.view-detail"),
+ icon: <ExternalLink className="size-4" />,
+ onSelect: () => {
+ void viewDetail(node);
+ },
+ });
+ }
+
+ sortByDictionary(items, ITEM_ORDER, (item) => item.key);
+ return items;
+ }, [
+ node,
+ deps,
+ databaseStore,
+ dbSchema,
+ notify,
+ openNewTab,
+ selectAllFromTableOrView,
+ t,
+ viewDetail,
+ ]);
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/availableActions.tsx b/frontend/src/react/components/sql-editor/SchemaPane/availableActions.tsx
new file mode 100644
index 0000000000..86eeb49b63
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/availableActions.tsx
@@ -0,0 +1,81 @@
+import { Box, Info } from "lucide-react";
+import { useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import { useVueState } from "@/react/hooks/useVueState";
+import { useConnectionOfCurrentSQLEditorTab } from "@/store";
+import {
+ instanceV1SupportsExternalTable,
+ instanceV1SupportsPackage,
+ instanceV1SupportsSequence,
+} from "@/utils/v1/instance";
+import type { AvailableAction } from "./actions";
+import {
+ ExternalTableIcon,
+ FunctionIcon,
+ PackageIcon,
+ ProcedureIcon,
+ SequenceIcon,
+ TableLeafIcon,
+ ViewIcon,
+} from "./TreeNode/icons";
+
+/**
+ * React equivalent of Vue's
+ * `useCurrentTabViewStateContext().availableActions`. Returns the same
+ * ordered list, with the same per-instance support gating for
+ * Sequences / External Tables / Packages, plus the trailing Diagram.
+ *
+ * Lifted to its own module (out of `SchemaPane.tsx`) so the AsidePanel
+ * `ActionBar` and the SchemaPane right-click menu can share a single
+ * source of truth.
+ */
+export function useAvailableActions(): AvailableAction[] {
+ const { t } = useTranslation();
+ const { instance: instanceRef } = useConnectionOfCurrentSQLEditorTab();
+ const instance = useVueState(() => instanceRef.value);
+
+ return useMemo(() => {
+ const actions: AvailableAction[] = [
+ {
+ view: "INFO",
+ title: t("common.info"),
+ icon: <Info className="size-4" />,
+ },
+ { view: "TABLES", title: t("db.tables"), icon: <TableLeafIcon /> },
+ { view: "VIEWS", title: t("db.views"), icon: <ViewIcon /> },
+ { view: "FUNCTIONS", title: t("db.functions"), icon: <FunctionIcon /> },
+ {
+ view: "PROCEDURES",
+ title: t("db.procedures"),
+ icon: <ProcedureIcon />,
+ },
+ ];
+ if (instanceV1SupportsSequence(instance)) {
+ actions.push({
+ view: "SEQUENCES",
+ title: t("db.sequences"),
+ icon: <SequenceIcon />,
+ });
+ }
+ if (instanceV1SupportsExternalTable(instance)) {
+ actions.push({
+ view: "EXTERNAL_TABLES",
+ title: t("db.external-tables"),
+ icon: <ExternalTableIcon />,
+ });
+ }
+ if (instanceV1SupportsPackage(instance)) {
+ actions.push({
+ view: "PACKAGES",
+ title: t("db.packages"),
+ icon: <PackageIcon />,
+ });
+ }
+ actions.push({
+ view: "DIAGRAM",
+ title: t("schema-diagram.self"),
+ icon: <Box className="size-4" />,
+ });
+ return actions;
+ }, [t, instance]);
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/click.ts b/frontend/src/react/components/sql-editor/SchemaPane/click.ts
new file mode 100644
index 0000000000..f4990fc18d
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/click.ts
@@ -0,0 +1,62 @@
+import Emittery from "emittery";
+import { useMemo } from "react";
+import type { TreeNode } from "./schemaTree";
+
+const DELAY = 250;
+
+type ClickEvents = Emittery<{
+ "single-click": { node: TreeNode };
+ "double-click": { node: TreeNode };
+}>;
+
+type PendingState = {
+ timeout: ReturnType<typeof setTimeout>;
+ node: TreeNode;
+};
+
+export type UseClickEventsResult = {
+ events: ClickEvents;
+ handleClick: (node: TreeNode) => void;
+};
+
+/**
+ * React port of `src/views/sql-editor/AsidePanel/SchemaPane/click.ts`.
+ *
+ * 250ms single/double-click discriminator. Same Emittery API surface,
+ * but the timing state lives in a closure (returned via `useMemo`) so
+ * it persists across renders without resubscribing.
+ */
+export function useClickEvents(): UseClickEventsResult {
+ return useMemo(() => {
+ let pending: PendingState | undefined;
+ const events: ClickEvents = new Emittery();
+
+ const clear = () => {
+ if (!pending) return;
+ clearTimeout(pending.timeout);
+ pending = undefined;
+ };
+
+ const queue = (node: TreeNode) => {
+ pending = {
+ timeout: setTimeout(() => {
+ events.emit("single-click", { node });
+ clear();
+ }, DELAY),
+ node,
+ };
+ };
+
+ const handleClick = (node: TreeNode) => {
+ if (pending && pending.node.key === node.key) {
+ events.emit("double-click", { node });
+ clear();
+ return;
+ }
+ clear();
+ queue(node);
+ };
+
+ return { events, handleClick };
+ }, []);
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/hover-state.tsx b/frontend/src/react/components/sql-editor/SchemaPane/hover-state.tsx
new file mode 100644
index 0000000000..b20c41f1fd
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/hover-state.tsx
@@ -0,0 +1,82 @@
+import {
+ createContext,
+ type ReactNode,
+ useCallback,
+ useContext,
+ useMemo,
+ useState,
+} from "react";
+import {
+ type DelayedValueUpdate,
+ useDelayedValue,
+} from "@/react/hooks/useDelayedValue";
+import type { Position } from "@/types";
+
+/**
+ * The hover-state shape consumed by SchemaPane's HoverPanel. Mirrors
+ * `src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/hover-state.ts`
+ * — a sparse path through the schema tree where the most-specific
+ * populated field decides which `*Info` card the panel renders.
+ */
+export type HoverState = {
+ database: string;
+ schema?: string;
+ table?: string;
+ externalTable?: string;
+ view?: string;
+ column?: string;
+ partition?: string;
+};
+
+export type HoverStateContextValue = {
+ state: HoverState | undefined;
+ position: Position;
+ setPosition: (position: Position) => void;
+ update: DelayedValueUpdate<HoverState | undefined>;
+ cancel: () => void;
+};
+
+const DELAY_BEFORE = 1000;
+const DELAY_AFTER = 350;
+
+const HoverStateContext = createContext<HoverStateContextValue | null>(null);
+
+/**
+ * Mount under SchemaPane to provide hover-state to descendant `HoverPanel`
+ * + tree nodes. Scoped to this surface — not a global context — so we
+ * don't pay re-render costs for unrelated parts of the editor.
+ */
+export function HoverStateProvider({ children }: { children: ReactNode }) {
+ const {
+ value: state,
+ update,
+ cancel,
+ } = useDelayedValue<HoverState | undefined>(undefined, {
+ delayBefore: DELAY_BEFORE,
+ delayAfter: DELAY_AFTER,
+ });
+ const [position, setPositionState] = useState<Position>({ x: 0, y: 0 });
+
+ const setPosition = useCallback((next: Position) => {
+ setPositionState(next);
+ }, []);
+
+ const value = useMemo<HoverStateContextValue>(
+ () => ({ state, position, setPosition, update, cancel }),
+ [state, position, setPosition, update, cancel]
+ );
+
+ return (
+ <HoverStateContext.Provider value={value}>
+ {children}
+ </HoverStateContext.Provider>
+ );
+}
+
+export function useHoverState(): HoverStateContextValue {
+ const value = useContext(HoverStateContext);
+ if (!value) {
+ throw new Error("useHoverState must be used inside <HoverStateProvider>");
+ }
+ return value;
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/schemaTree.test.ts b/frontend/src/react/components/sql-editor/SchemaPane/schemaTree.test.ts
new file mode 100644
index 0000000000..272ef7e960
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SchemaPane/schemaTree.test.ts
@@ -0,0 +1,658 @@
+import { create } from "@bufbuild/protobuf";
+import { describe, expect, test, vi } from "vitest";
+import {
+ CheckConstraintMetadataSchema,
+ ColumnMetadataSchema,
+ DatabaseMetadataSchema,
+ DatabaseSchema$,
+ DependencyColumnSchema,
+ ExternalTableMetadataSchema,
+ ForeignKeyMetadataSchema,
+ FunctionMetadataSchema,
+ IndexMetadataSchema,
+ PackageMetadataSchema,
+ ProcedureMetadataSchema,
+ SchemaMetadataSchema,
+ SequenceMetadataSchema,
+ TableMetadataSchema,
+ TablePartitionMetadataSchema,
+ TriggerMetadataSchema,
+ ViewMetadataSchema,
+} from "@/types/proto-es/v1/database_service_pb";
+import {
+ buildDatabaseSchemaTree,
+ ExpandableNodeTypes,
+ keyForNodeTarget,
+ LeafNodeTypes,
+ mapTreeNodeByType,
+ type NodeTarget,
+ type NodeType,
+ readableTextForNodeTarget,
+ type TextTarget,
+ type TreeNode,
+} from "./schemaTree";
+
+vi.mock("@/react/i18n", () => ({
+ default: { t: (key: string) => key },
+}));
+
+const DATABASE = "instances/i1/databases/db1";
+
+describe("keyForNodeTarget", () => {
+ test("database key is the database resource name", () => {
+ expect(keyForNodeTarget("database", { database: DATABASE })).toBe(DATABASE);
+ });
+
+ test("schema key joins under the database", () => {
+ expect(
+ keyForNodeTarget("schema", { database: DATABASE, schema: "public" })
+ ).toBe(`${DATABASE}/schemas/public`);
+ });
+
+ test("table key joins under the schema", () => {
+ expect(
+ keyForNodeTarget("table", {
+ database: DATABASE,
+ schema: "public",
+ table: "users",
+ })
+ ).toBe(`${DATABASE}/schemas/public/tables/users`);
+ });
+
+ test("external-table key joins under the schema", () => {
+ expect(
+ keyForNodeTarget("external-table", {
+ database: DATABASE,
+ schema: "ext",
+ externalTable: "logs",
+ })
+ ).toBe(`${DATABASE}/schemas/ext/externalTables/logs`);
+ });
+
+ test("view key joins under the schema", () => {
+ expect(
+ keyForNodeTarget("view", {
+ database: DATABASE,
+ schema: "public",
+ view: "active_users",
+ })
+ ).toBe(`${DATABASE}/schemas/public/views/active_users`);
+ });
+
+ test("procedure key uses keyWithPosition under the schema", () => {
+ expect(
+ keyForNodeTarget("procedure", {
+ database: DATABASE,
+ schema: "public",
+ procedure: "do_thing",
+ position: 0,
+ })
+ ).toBe(`${DATABASE}/schemas/public/procedures/do_thing###0`);
+ });
+
+ test("package key uses keyWithPosition under the schema", () => {
+ expect(
+ keyForNodeTarget("package", {
+ database: DATABASE,
+ schema: "public",
+ package: "pkg",
+ position: 1,
+ })
+ ).toBe(`${DATABASE}/schemas/public/packages/pkg###1`);
+ });
+
+ test("function key uses keyWithPosition under the schema", () => {
+ expect(
+ keyForNodeTarget("function", {
+ database: DATABASE,
+ schema: "public",
+ function: "fn",
+ position: 2,
+ })
+ ).toBe(`${DATABASE}/schemas/public/functions/fn###2`);
+ });
+
+ test("sequence key uses keyWithPosition under the schema", () => {
+ expect(
+ keyForNodeTarget("sequence", {
+ database: DATABASE,
+ schema: "public",
+ sequence: "seq",
+ position: 3,
+ })
+ ).toBe(`${DATABASE}/schemas/public/sequences/seq###3`);
+ });
+
+ test("trigger key uses keyWithPosition under the table", () => {
+ expect(
+ keyForNodeTarget("trigger", {
+ database: DATABASE,
+ schema: "public",
+ table: "users",
+ trigger: "trg",
+ position: 4,
+ })
+ ).toBe(`${DATABASE}/schemas/public/tables/users/triggers/trg###4`);
+ });
+
+ test("index key joins under the table", () => {
+ expect(
+ keyForNodeTarget("index", {
+ database: DATABASE,
+ schema: "public",
+ table: "users",
+ index: "ix_email",
+ })
+ ).toBe(`${DATABASE}/schemas/public/tables/users/indexes/ix_email`);
+ });
+
+ test("foreign-key joins under the table", () => {
+ expect(
+ keyForNodeTarget("foreign-key", {
+ database: DATABASE,
+ schema: "public",
+ table: "users",
+ foreignKey: "fk_org",
+ })
+ ).toBe(`${DATABASE}/schemas/public/tables/users/foreignKeys/fk_org`);
+ });
+
+ test("check joins under the table", () => {
+ expect(
+ keyForNodeTarget("check", {
+ database: DATABASE,
+ schema: "public",
+ table: "users",
+ check: "ck_age",
+ })
+ ).toBe(`${DATABASE}/schemas/public/tables/users/checks/ck_age`);
+ });
+
+ test("partition-table joins under the table", () => {
+ expect(
+ keyForNodeTarget("partition-table", {
+ database: DATABASE,
+ schema: "public",
+ table: "events",
+ partition: "p2026",
+ })
+ ).toBe(`${DATABASE}/schemas/public/tables/events/partitionTables/p2026`);
+ });
+
+ test("dependency-column joins under the view", () => {
+ const dep = create(DependencyColumnSchema, {
+ schema: "public",
+ table: "users",
+ column: "id",
+ });
+ expect(
+ keyForNodeTarget("dependency-column", {
+ database: DATABASE,
+ schema: "public",
+ view: "active_users",
+ dependencyColumn: dep,
+ })
+ ).toBe(
+ `${DATABASE}/schemas/public/views/active_users/dependencyColumns/public/users/id`
+ );
+ });
+
+ test("column under a table joins under the table", () => {
+ expect(
+ keyForNodeTarget("column", {
+ database: DATABASE,
+ schema: "public",
+ table: "users",
+ column: "id",
+ })
+ ).toBe(`${DATABASE}/schemas/public/tables/users/columns/id`);
+ });
+
+ test("expandable-text + error keys join type/id", () => {
+ expect(
+ keyForNodeTarget("expandable-text", {
+ id: "x/y/tables",
+ expandable: true,
+ text: () => "Tables",
+ })
+ ).toBe("expandable-text/x/y/tables");
+ expect(
+ keyForNodeTarget("error", {
+ id: "x/y/dummy-table-0",
+ expandable: false,
+ text: () => "",
+ })
+ ).toBe("error/x/y/dummy-table-0");
+ });
+});
+
+describe("readableTextForNodeTarget", () => {
+ test("error nodes are empty (so search ignores them)", () => {
+ expect(
+ readableTextForNodeTarget("error", {
+ id: "x",
+ expandable: false,
+ text: () => "anything",
+ })
+ ).toBe("");
+ });
+
+ test("non-searchable expandable-text returns empty", () => {
+ expect(
+ readableTextForNodeTarget("expandable-text", {
+ id: "x",
+ expandable: true,
+ text: () => "Tables",
+ })
+ ).toBe("");
+ });
+
+ test("searchable expandable-text returns the text() value", () => {
+ expect(
+ readableTextForNodeTarget("expandable-text", {
+ id: "x",
+ expandable: true,
+ text: () => "Tables",
+ searchable: true,
+ })
+ ).toBe("Tables");
+ });
+
+ test("dependency-column joins schema.table.column", () => {
+ const dep = create(DependencyColumnSchema, {
+ schema: "public",
+ table: "users",
+ column: "id",
+ });
+ expect(
+ readableTextForNodeTarget("dependency-column", {
+ database: DATABASE,
+ schema: "public",
+ view: "v",
+ dependencyColumn: dep,
+ })
+ ).toBe("public.users.id");
+ });
+
+ test("dependency-column without schema joins table.column only", () => {
+ const dep = create(DependencyColumnSchema, {
+ table: "users",
+ column: "id",
+ });
+ expect(
+ readableTextForNodeTarget("dependency-column", {
+ database: DATABASE,
+ schema: "public",
+ view: "v",
+ dependencyColumn: dep,
+ })
+ ).toBe("users.id");
+ });
+
+ test("default case returns the last path segment", () => {
+ expect(
+ readableTextForNodeTarget("table", {
+ database: DATABASE,
+ schema: "public",
+ table: "users",
+ })
+ ).toBe("users");
+ });
+});
+
+describe("LeafNodeTypes / ExpandableNodeTypes", () => {
+ test("type unions partition cleanly", () => {
+ const allTypes: NodeType[] = [
+ "database",
+ "schema",
+ "table",
+ "external-table",
+ "view",
+ "procedure",
+ "function",
+ "sequence",
+ "trigger",
+ "package",
+ "partition-table",
+ "column",
+ "index",
+ "foreign-key",
+ "check",
+ "dependency-column",
+ "expandable-text",
+ "error",
+ ];
+ for (const t of allTypes) {
+ expect(
+ LeafNodeTypes.includes(t) ||
+ ExpandableNodeTypes.includes(t) ||
+ [
+ "database",
+ "schema",
+ "table",
+ "view",
+ "external-table",
+ "partition-table",
+ "expandable-text",
+ ].includes(t) ||
+ LeafNodeTypes.includes(t)
+ ).toBe(true);
+ }
+ });
+
+ test("mapTreeNodeByType marks leaves correctly", () => {
+ const colNode = mapTreeNodeByType("column", {
+ database: DATABASE,
+ schema: "public",
+ table: "users",
+ column: "id",
+ });
+ expect(colNode.isLeaf).toBe(true);
+
+ const schemaNode = mapTreeNodeByType("schema", {
+ database: DATABASE,
+ schema: "public",
+ });
+ expect(schemaNode.isLeaf).toBe(false);
+ });
+});
+
+// ---------- buildDatabaseSchemaTree ----------
+
+const makeDatabase = () => create(DatabaseSchema$, { name: DATABASE });
+
+const makeColumn = (name: string) => create(ColumnMetadataSchema, { name });
+
+const makeIndex = (name: string) => create(IndexMetadataSchema, { name });
+
+const makeForeignKey = (name: string) =>
+ create(ForeignKeyMetadataSchema, { name });
+
+const makeCheck = (name: string) =>
+ create(CheckConstraintMetadataSchema, { name });
+
+const makePartition = (name: string, subs: string[] = []) =>
+ create(TablePartitionMetadataSchema, {
+ name,
+ subpartitions: subs.map((n) =>
+ create(TablePartitionMetadataSchema, { name: n })
+ ),
+ });
+
+const makeTable = (
+ name: string,
+ opts: Partial<{
+ columns: string[];
+ indexes: string[];
+ foreignKeys: string[];
+ checks: string[];
+ triggers: string[];
+ partitions: ReturnType<typeof makePartition>[];
+ }> = {}
+) =>
+ create(TableMetadataSchema, {
+ name,
+ columns: (opts.columns ?? []).map(makeColumn),
+ indexes: (opts.indexes ?? []).map(makeIndex),
+ foreignKeys: (opts.foreignKeys ?? []).map(makeForeignKey),
+ checkConstraints: (opts.checks ?? []).map(makeCheck),
+ triggers: (opts.triggers ?? []).map((n) =>
+ create(TriggerMetadataSchema, { name: n })
+ ),
+ partitions: opts.partitions ?? [],
+ });
+
+const makeView = (name: string, columns: string[] = []) =>
+ create(ViewMetadataSchema, {
+ name,
+ columns: columns.map(makeColumn),
+ });
+
+const makeExternalTable = (name: string, columns: string[] = []) =>
+ create(ExternalTableMetadataSchema, {
+ name,
+ columns: columns.map(makeColumn),
+ });
+
+const makeSchema = (
+ name: string,
+ opts: Partial<{
+ tables: ReturnType<typeof makeTable>[];
+ externalTables: ReturnType<typeof makeExternalTable>[];
+ views: ReturnType<typeof makeView>[];
+ procedures: string[];
+ functions: string[];
+ sequences: string[];
+ packages: string[];
+ }> = {}
+) =>
+ create(SchemaMetadataSchema, {
+ name,
+ tables: opts.tables ?? [],
+ externalTables: opts.externalTables ?? [],
+ views: opts.views ?? [],
+ procedures: (opts.procedures ?? []).map((n) =>
+ create(ProcedureMetadataSchema, { name: n })
+ ),
+ functions: (opts.functions ?? []).map((n) =>
+ create(FunctionMetadataSchema, { name: n })
+ ),
+ sequences: (opts.sequences ?? []).map((n) =>
+ create(SequenceMetadataSchema, { name: n })
+ ),
+ packages: (opts.packages ?? []).map((n) =>
+ create(PackageMetadataSchema, { name: n })
+ ),
+ });
+
+const makeMetadata = (schemas: ReturnType<typeof makeSchema>[]) =>
+ create(DatabaseMetadataSchema, { schemas });
+
+// Walk a TreeNode tree and yield (key, type) for every node.
+function* walk(
+ nodes: TreeNode[]
+): Generator<{ key: string; type: NodeType; label: string | undefined }> {
+ for (const n of nodes) {
+ yield { key: n.key, type: n.meta.type, label: n.label };
+ if (n.children) yield* walk(n.children);
+ }
+}
+
+const findKey = (nodes: TreeNode[], predicate: (k: string) => boolean) =>
+ [...walk(nodes)].find((n) => predicate(n.key));
+
+describe("buildDatabaseSchemaTree", () => {
+ test("empty metadata returns a dummy 'empty' placeholder", () => {
+ const tree = buildDatabaseSchemaTree(makeDatabase(), makeMetadata([]));
+ expect(tree).toHaveLength(1);
+ expect(tree[0].meta.type).toBe("error");
+ expect(tree[0].disabled).toBe(true);
+ });
+
+ test("single anonymous schema (MySQL-style) flattens schema's children to root", () => {
+ const md = makeMetadata([
+ makeSchema("", {
+ tables: [makeTable("users", { columns: ["id", "email"] })],
+ }),
+ ]);
+ const tree = buildDatabaseSchemaTree(makeDatabase(), md);
+ // Top-level should be the "Tables" expandable folder, not a schema node.
+ expect(tree[0].meta.type).toBe("expandable-text");
+ const tablesFolder = tree[0];
+ expect(tablesFolder.children?.[0].meta.type).toBe("table");
+ expect(tablesFolder.children?.[0].key).toBe(
+ `${DATABASE}/schemas//tables/users`
+ );
+ });
+
+ test("multi-schema (Postgres-style) wraps children in schema nodes", () => {
+ const md = makeMetadata([
+ makeSchema("public", { tables: [makeTable("users")] }),
+ makeSchema("audit", { tables: [makeTable("events")] }),
+ ]);
+ const tree = buildDatabaseSchemaTree(makeDatabase(), md);
+ expect(tree).toHaveLength(2);
+ expect(tree[0].meta.type).toBe("schema");
+ expect(tree[0].key).toBe(`${DATABASE}/schemas/public`);
+ expect(tree[1].key).toBe(`${DATABASE}/schemas/audit`);
+ });
+
+ test("a table builds Columns / Indexes / FKs / Checks / Triggers / Partitions folders only when populated", () => {
+ const md = makeMetadata([
+ makeSchema("public", {
+ tables: [
+ makeTable("users", {
+ columns: ["id"],
+ indexes: ["ix_id"],
+ foreignKeys: ["fk_org"],
+ checks: ["ck_age"],
+ triggers: ["trg_audit"],
+ partitions: [makePartition("p1")],
+ }),
+ makeTable("plain", { columns: ["x"] }),
+ ],
+ }),
+ ]);
+ const tree = buildDatabaseSchemaTree(makeDatabase(), md);
+ const usersTable = findKey(
+ tree,
+ (k) => k === `${DATABASE}/schemas/public/tables/users`
+ );
+ expect(usersTable).toBeDefined();
+
+ const plainTable = [...walk(tree)].filter(
+ (n) => n.key === `${DATABASE}/schemas/public/tables/plain`
+ );
+ expect(plainTable).toHaveLength(1);
+
+ // Plain table has only the Columns folder.
+ const plainNode = tree[0].children![0].children!.find(
+ (c) => c.key === `${DATABASE}/schemas/public/tables/plain`
+ );
+ expect(plainNode!.children).toHaveLength(1);
+ expect(plainNode!.children![0].meta.type).toBe("expandable-text");
+ });
+
+ test("nested partitions recurse and reuse the table-level key prefix", () => {
+ // Vue's keyForNodeTarget("partition-table", ...) always keys directly
+ // under the table — not under the parent partition. Sub-partitions
+ // therefore share the same `<table>/partitionTables/<name>` prefix as
+ // top-level partitions; preserving this behavior keeps persisted
+ // treeState keys valid.
+ const md = makeMetadata([
+ makeSchema("public", {
+ tables: [
+ makeTable("events", {
+ columns: ["id"],
+ partitions: [makePartition("p2026", ["q1", "q2"])],
+ }),
+ ],
+ }),
+ ]);
+ const tree = buildDatabaseSchemaTree(makeDatabase(), md);
+ const parent = findKey(
+ tree,
+ (k) =>
+ k === `${DATABASE}/schemas/public/tables/events/partitionTables/p2026`
+ );
+ expect(parent).toBeDefined();
+ expect(parent!.type).toBe("partition-table");
+
+ // The sub-partitions are children of `parent` but key directly under
+ // the table (not nested under `p2026`).
+ const q1 = findKey(
+ tree,
+ (k) => k === `${DATABASE}/schemas/public/tables/events/partitionTables/q1`
+ );
+ expect(q1).toBeDefined();
+ expect(q1!.type).toBe("partition-table");
+ });
+
+ test("empty Tables folder still emits an <Empty> child for parity", () => {
+ const md = makeMetadata([
+ makeSchema("public", {
+ tables: [],
+ views: [makeView("v")],
+ }),
+ ]);
+ const tree = buildDatabaseSchemaTree(makeDatabase(), md);
+ const tablesFolder = tree[0].children!.find(
+ (c) =>
+ c.meta.type === "expandable-text" &&
+ (c.meta.target as TextTarget).id === `${DATABASE}/schemas/public/table`
+ );
+ expect(tablesFolder).toBeDefined();
+ expect(tablesFolder!.children![0].meta.type).toBe("error");
+ });
+
+ test("external tables / views / procedures / functions / packages / sequences only appear when populated", () => {
+ const md = makeMetadata([
+ makeSchema("public", {
+ tables: [makeTable("t")],
+ externalTables: [makeExternalTable("ext_t", ["c"])],
+ views: [makeView("v", ["c"])],
+ procedures: ["p"],
+ functions: ["f"],
+ packages: ["pk"],
+ sequences: ["s"],
+ }),
+ ]);
+ const tree = buildDatabaseSchemaTree(makeDatabase(), md);
+ const folderTypes = tree[0].children!.map(
+ (c) => (c.meta.target as TextTarget).mockType
+ );
+ expect(folderTypes).toEqual([
+ "table",
+ "external-table",
+ "view",
+ "procedure",
+ "package",
+ "function",
+ "sequence",
+ ]);
+ });
+
+ test("dependency-column children would key under the view (synthetic check)", () => {
+ // dependency-column is built externally (lineage feature) but the key
+ // path must remain stable. Verify keyForNodeTarget output directly.
+ const dep = create(DependencyColumnSchema, {
+ schema: "ext",
+ table: "raw_users",
+ column: "id",
+ });
+ expect(
+ keyForNodeTarget("dependency-column", {
+ database: DATABASE,
+ schema: "public",
+ view: "active",
+ dependencyColumn: dep,
+ })
+ ).toBe(
+ `${DATABASE}/schemas/public/views/active/dependencyColumns/ext/raw_users/id`
+ );
+ });
+});
+
+// Compile-time check that NodeTarget specializations remain assignable.
+const _typeCheckTargets: {
+ database: NodeTarget<"database">;
+ schema: NodeTarget<"schema">;
+ trigger: NodeTarget<"trigger">;
+ expandableText: NodeTarget<"expandable-text">;
+} = {
+ database: { database: DATABASE },
+ schema: { database: DATABASE, schema: "public" },
+ trigger: {
+ database: DATABASE,
+ schema: "public",
+ table: "t",
+ trigger: "trg",
+ position: 0,
+ },
+ expandableText: {
+ id: "x",
+ expandable: true,
+ text: () => "x",
+ },
+};
+void _typeCheckTargets;
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/tree.ts b/frontend/src/react/components/sql-editor/SchemaPane/schemaTree.ts
similarity index 87%
rename from frontend/src/views/sql-editor/AsidePanel/SchemaPane/tree.ts
rename to frontend/src/react/components/sql-editor/SchemaPane/schemaTree.ts
index 0a0c4f7cc7..67352a6ee0 100644
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/tree.ts
+++ b/frontend/src/react/components/sql-editor/SchemaPane/schemaTree.ts
@@ -1,6 +1,5 @@
-import type { TreeOption } from "naive-ui";
-import { type RenderFunction } from "vue";
-import { t } from "@/plugins/i18n";
+import type { ReactNode } from "react";
+import i18n from "@/react/i18n";
import type {
CheckConstraintMetadata,
ColumnMetadata,
@@ -13,8 +12,21 @@ import type {
TableMetadata,
TablePartitionMetadata,
} from "@/types/proto-es/v1/database_service_pb";
-import { keyForDependencyColumn } from "@/utils";
-import { keyWithPosition } from "../../EditorCommon";
+// Deep-import both helpers to avoid pulling barrels that transitively
+// reach monaco / Vue surfaces. Both files are framework-agnostic pure TS.
+import { keyForDependencyColumn } from "@/utils/v1/dbSchema";
+import { keyWithPosition } from "@/views/sql-editor/EditorCommon/utils";
+
+/**
+ * React port of `src/views/sql-editor/AsidePanel/SchemaPane/tree.ts`.
+ *
+ * Pure type-driven tree builder: walks DatabaseMetadata and produces a
+ * TreeNode tree with stable string keys that mirror the Vue version
+ * byte-for-byte (so persisted `tab.treeState.keys` survives the migration).
+ *
+ * Renamed from `tree.ts` → `schemaTree.ts` to disambiguate from
+ * `src/react/components/sql-editor/ConnectionPane/tree.ts`.
+ */
export type NodeType =
| "database"
@@ -33,8 +45,8 @@ export type NodeType =
| "foreign-key"
| "check"
| "dependency-column"
- | "expandable-text" // Text nodes to display "Tables / Views / Functions / Triggers" etc.
- | "error"; // Error nodes to display "<Empty>" or "Cannot fetch ..." etc.
+ | "expandable-text" // "Tables / Views / Functions / Triggers" folder headers
+ | "error"; // "<Empty>" / "Cannot fetch …" placeholders
export type RichDatabaseMetadata = {
database: string;
@@ -99,9 +111,9 @@ export type TextTarget<
> = {
expandable: E;
id: string;
- mockType?: NodeType; // mock as a node type if needed
+ mockType?: NodeType;
text: () => string;
- render?: RenderFunction;
+ render?: ReactNode;
searchable?: S;
};
export type ErrorTarget = TextTarget<false, false> & {
@@ -153,10 +165,19 @@ export type NodeMeta<T extends NodeType = NodeType> = {
target: NodeTarget<T>;
};
-export type TreeNode<T extends NodeType = NodeType> = TreeOption & {
+/**
+ * Minimal tree-row contract we share with the React `Tree` primitive.
+ * Mirrors the subset of naive-ui's `TreeOption` the schema pane uses:
+ * `key`, `label`, `disabled`, `isLeaf`, plus our `meta` payload and
+ * recursive `children`.
+ */
+export type TreeNode<T extends NodeType = NodeType> = {
key: string;
meta: NodeMeta<T>;
children?: TreeNode[];
+ label?: string;
+ disabled?: boolean;
+ isLeaf?: boolean;
};
export const ExpandableNodeTypes: readonly NodeType[] = [
@@ -191,88 +212,102 @@ export const keyForNodeTarget = <T extends NodeType>(
switch (type) {
case "database":
return database;
- case "schema":
+ case "schema": {
const { schema } = target as NodeTarget<"schema">;
return [database, `schemas/${schema}`].join("/");
- case "table":
+ }
+ case "table": {
const { table } = target as NodeTarget<"table">;
return [
keyForNodeTarget("schema", target as NodeTarget<"schema">),
`tables/${table}`,
].join("/");
- case "external-table":
+ }
+ case "external-table": {
const { externalTable } = target as NodeTarget<"external-table">;
return [
keyForNodeTarget("schema", target as NodeTarget<"schema">),
`externalTables/${externalTable}`,
].join("/");
- case "view":
+ }
+ case "view": {
const { view } = target as NodeTarget<"view">;
return [
keyForNodeTarget("schema", target as NodeTarget<"schema">),
`views/${view}`,
].join("/");
- case "procedure":
+ }
+ case "procedure": {
const { procedure, position } = target as NodeTarget<"procedure">;
return [
keyForNodeTarget("schema", target as NodeTarget<"schema">),
`procedures/${keyWithPosition(procedure, position)}`,
].join("/");
- case "package":
+ }
+ case "package": {
const { package: pack, position: pos } = target as NodeTarget<"package">;
return [
keyForNodeTarget("schema", target as NodeTarget<"schema">),
`packages/${keyWithPosition(pack, pos)}`,
].join("/");
- case "function":
+ }
+ case "function": {
const { function: func, position: fp } = target as NodeTarget<"function">;
return [
keyForNodeTarget("schema", target as NodeTarget<"schema">),
`functions/${keyWithPosition(func, fp)}`,
].join("/");
- case "sequence":
+ }
+ case "sequence": {
const { sequence, position: sp } = target as NodeTarget<"sequence">;
return [
keyForNodeTarget("schema", target as NodeTarget<"schema">),
`sequences/${keyWithPosition(sequence, sp)}`,
].join("/");
- case "trigger":
+ }
+ case "trigger": {
const { trigger, position: tp } = target as NodeTarget<"trigger">;
return [
keyForNodeTarget("table", target as NodeTarget<"table">),
`triggers/${keyWithPosition(trigger, tp)}`,
].join("/");
- case "index":
+ }
+ case "index": {
const { index } = target as NodeTarget<"index">;
return [
keyForNodeTarget("table", target as NodeTarget<"table">),
`indexes/${index}`,
].join("/");
- case "foreign-key":
+ }
+ case "foreign-key": {
const { foreignKey } = target as NodeTarget<"foreign-key">;
return [
keyForNodeTarget("table", target as NodeTarget<"table">),
`foreignKeys/${foreignKey}`,
].join("/");
- case "check":
+ }
+ case "check": {
const { check } = target as NodeTarget<"check">;
return [
keyForNodeTarget("table", target as NodeTarget<"table">),
`checks/${check}`,
].join("/");
- case "partition-table":
+ }
+ case "partition-table": {
const { partition } = target as NodeTarget<"partition-table">;
return [
keyForNodeTarget("table", target as NodeTarget<"table">),
`partitionTables/${partition}`,
].join("/");
- case "dependency-column":
+ }
+ case "dependency-column": {
const { dependencyColumn } = target as NodeTarget<"dependency-column">;
return [
keyForNodeTarget("view", target as NodeTarget<"view">),
`dependencyColumns/${keyForDependencyColumn(dependencyColumn)}`,
].join("/");
- case "column":
+ }
+ case "column": {
const { column } = target as NodeTarget<"column">;
const key = `columns/${column}`;
if ("table" in target) {
@@ -295,9 +330,11 @@ export const keyForNodeTarget = <T extends NodeType>(
].join("/");
}
return "";
- default:
+ }
+ default: {
const { id } = target as NodeTarget<"expandable-text" | "error">;
return `${type}/${id}`;
+ }
}
};
@@ -307,20 +344,23 @@ export const readableTextForNodeTarget = <T extends NodeType>(
): string => {
switch (type) {
case "error":
- // Use empty strings for error nodes to make them unsearchable
+ // Empty string keeps error rows out of search matches.
return "";
- case "expandable-text":
+ case "expandable-text": {
const { text, searchable } = target as TextTarget;
if (!searchable) return "";
return text();
- case "dependency-column":
+ }
+ case "dependency-column": {
const dep = (target as NodeTarget<"dependency-column">).dependencyColumn;
const parts = [dep.table, dep.column];
if (dep.schema) parts.unshift(dep.schema);
return parts.join(".");
- default:
+ }
+ default: {
const key = keyForNodeTarget(type, target);
return key.split("/").slice(-1)[0];
+ }
}
};
@@ -368,7 +408,7 @@ const createExpandableTextNode = (
type: NodeType,
parentKey: string,
text: () => string,
- render?: RenderFunction
+ render?: ReactNode
) => {
return mapTreeNodeByType("expandable-text", {
id: `${parentKey}/${type}`,
@@ -388,18 +428,15 @@ const mapColumnNodes = (
parentKey: string
) => {
if (columns.length === 0) {
- // Create a "<Empty>" columns node placeholder
return [createDummyNode("column", parentKey)];
}
- const children = columns.map((column) => {
- const node = mapTreeNodeByType("column", {
+ return columns.map((column) =>
+ mapTreeNodeByType("column", {
...target,
column: column.name,
- });
- return node;
- });
- return children;
+ })
+ );
};
const mapIndexNodes = (
@@ -408,15 +445,12 @@ const mapIndexNodes = (
parentKey: string
) => {
if (indexes.length === 0) {
- // Create a "<Empty>" index node placeholder
return [createDummyNode("index", parentKey)];
}
- const children = indexes.map((index) => {
- const node = mapTreeNodeByType("index", { ...target, index: index.name });
- return node;
- });
- return children;
+ return indexes.map((index) =>
+ mapTreeNodeByType("index", { ...target, index: index.name })
+ );
};
const mapForeignKeyNodes = (
@@ -425,18 +459,15 @@ const mapForeignKeyNodes = (
parentKey: string
) => {
if (foreignKeys.length === 0) {
- // Create a "<Empty>" foreignKey node placeholder
return [createDummyNode("foreign-key", parentKey)];
}
- const children = foreignKeys.map((foreignKey) => {
- const node = mapTreeNodeByType("foreign-key", {
+ return foreignKeys.map((foreignKey) =>
+ mapTreeNodeByType("foreign-key", {
...target,
foreignKey: foreignKey.name,
- });
- return node;
- });
- return children;
+ })
+ );
};
const mapCheckNodes = (
@@ -445,20 +476,19 @@ const mapCheckNodes = (
parentKey: string
) => {
if (checks.length === 0) {
- // Create a "<Empty>" check node placeholder
return [createDummyNode("check", parentKey)];
}
- const children = checks.map((check) => {
- const node = mapTreeNodeByType("check", {
+ return checks.map((check) =>
+ mapTreeNodeByType("check", {
...target,
check: check.name,
- });
- return node;
- });
- return children;
+ })
+ );
};
+const t = (key: string) => i18n.t(key);
+
const mapTableNodes = (
schema: SchemaMetadata,
target: NodeTarget<"schema">,
@@ -473,14 +503,12 @@ const mapTableNodes = (
t("database.columns")
);
node.children = [columnsFolderNode];
- // Map column columns
columnsFolderNode.children = mapColumnNodes(
node.meta.target,
table.columns,
columnsFolderNode.key
);
- // Map indexes
if (table.indexes.length > 0) {
const indexesFolderNode = createExpandableTextNode(
"index",
@@ -495,7 +523,6 @@ const mapTableNodes = (
node.children.push(indexesFolderNode);
}
- // Map foreign keys
if (table.foreignKeys.length > 0) {
const foreignKeysFolderNode = createExpandableTextNode(
"foreign-key",
@@ -510,7 +537,6 @@ const mapTableNodes = (
node.children.push(foreignKeysFolderNode);
}
- // Show "Triggers" if there's at least 1 function
if (table.triggers.length > 0) {
const triggerNode = createExpandableTextNode("trigger", node.key, () =>
t("db.triggers")
@@ -523,7 +549,6 @@ const mapTableNodes = (
node.children.push(triggerNode);
}
- // Map checks
if (table.checkConstraints.length > 0) {
const checksFolderNode = createExpandableTextNode("check", node.key, () =>
t("database.checks")
@@ -536,7 +561,6 @@ const mapTableNodes = (
node.children.push(checksFolderNode);
}
- // Map table-level partitions.
if (table.partitions.length > 0) {
const partitionsFolderNode = createExpandableTextNode(
"partition-table",
@@ -574,7 +598,7 @@ const mapExternalTableNodes = (
schema: SchemaMetadata,
target: NodeTarget<"schema">
) => {
- const externalTableNodes = schema.externalTables.map((externalTable) => {
+ return schema.externalTables.map((externalTable) => {
const node = mapTreeNodeByType("external-table", {
...target,
externalTable: externalTable.name,
@@ -584,7 +608,6 @@ const mapExternalTableNodes = (
);
node.children = [folderNode];
- // columns
folderNode.children = mapColumnNodes(
node.meta.target,
externalTable.columns,
@@ -593,15 +616,13 @@ const mapExternalTableNodes = (
return node;
});
- return externalTableNodes;
};
-// Map partition-table-level partitions.
const mapPartitionTableNodes = (
parentPartition: TablePartitionMetadata,
target: RichPartitionTableMetadata
) => {
- const children = parentPartition.subpartitions.map((partition) => {
+ return parentPartition.subpartitions.map((partition) => {
const node = mapTreeNodeByType("partition-table", {
...target,
partition: partition.name,
@@ -614,7 +635,6 @@ const mapPartitionTableNodes = (
}
return node;
});
- return children;
};
const mapViewNodes = (
@@ -633,7 +653,6 @@ const mapViewNodes = (
() => t("database.columns")
);
viewNode.children = [columnsFolderNode];
- // Map column columns
columnsFolderNode.children = mapColumnNodes(
viewNode.meta.target,
view.columns,
@@ -714,6 +733,9 @@ const mapSequenceNodes = (
})
);
if (children.length === 0) {
+ // Vue passes "function" here intentionally; preserve the bug for parity
+ // so persisted treeState keys match. Fixing would silently break stored
+ // expand state.
return [createDummyNode("function", parentKey)];
}
return children;
@@ -728,6 +750,8 @@ const mapTriggerNodes = (
mapTreeNodeByType("trigger", { ...target, trigger: trigger.name, position })
);
if (children.length === 0) {
+ // Same intentional Vue parity quirk as mapSequenceNodes — passes
+ // "function" instead of "trigger". Preserve.
return [createDummyNode("function", parentKey)];
}
return children;
@@ -750,15 +774,12 @@ const buildSchemaNodeChildren = (
const children: TreeNode[] = [];
- // Always show "Tables" node
- // If no tables, show "<Empty>"
const tablesNode = createExpandableTextNode("table", parentKey, () =>
t("db.tables")
);
tablesNode.children = mapTableNodes(schema, target, tablesNode.key);
children.push(tablesNode);
- // Only show "External Tables" node if the schema do have external tables.
if (schema.externalTables.length > 0) {
const externalTablesNode = createExpandableTextNode(
"external-table",
@@ -769,7 +790,6 @@ const buildSchemaNodeChildren = (
children.push(externalTablesNode);
}
- // Only show "Views" node if the schema do have views.
if (schema.views.length > 0) {
const viewsNode = createExpandableTextNode("view", parentKey, () =>
t("db.views")
@@ -778,7 +798,6 @@ const buildSchemaNodeChildren = (
children.push(viewsNode);
}
- // Show "Procedures" if there's at least 1 procedure
if (schema.procedures.length > 0) {
const procedureNode = createExpandableTextNode("procedure", parentKey, () =>
t("db.procedures")
@@ -791,7 +810,6 @@ const buildSchemaNodeChildren = (
children.push(procedureNode);
}
- // Show "Packages" if there's at least 1 package
if (schema.packages.length > 0) {
const packageNode = createExpandableTextNode("package", parentKey, () =>
t("db.packages")
@@ -800,7 +818,6 @@ const buildSchemaNodeChildren = (
children.push(packageNode);
}
- // Show "Functions" if there's at least 1 function
if (schema.functions.length > 0) {
const functionNode = createExpandableTextNode("function", parentKey, () =>
t("db.functions")
@@ -809,7 +826,6 @@ const buildSchemaNodeChildren = (
children.push(functionNode);
}
- // Show "Sequences" if there's at least 1 function
if (schema.sequences.length > 0) {
const sequenceNode = createExpandableTextNode("sequence", parentKey, () =>
t("db.sequences")
@@ -830,21 +846,17 @@ export const buildDatabaseSchemaTree = (
});
const { schemas } = metadata;
if (schemas.length === 0) {
- // Empty database, show "<Empty>"
return [createDummyNode("table", dummyRoot.key)];
}
if (schemas.length === 1 && schemas[0].name === "") {
const schema = schemas[0];
- // A single schema database, should render tables as views directly as a database
- // node's children
return buildSchemaNodeChildren(
schema,
{ ...dummyRoot.meta.target, schema: schema.name },
dummyRoot.key
);
} else {
- // Multiple schema database
return schemas.map((schema) => {
const schemaNode = mapTreeNodeByType("schema", {
...dummyRoot.meta.target,
diff --git a/frontend/src/react/components/ui/combobox.tsx b/frontend/src/react/components/ui/combobox.tsx
index 19938c40dd..6a46e8d681 100644
--- a/frontend/src/react/components/ui/combobox.tsx
+++ b/frontend/src/react/components/ui/combobox.tsx
@@ -54,8 +54,12 @@ type ComboboxBaseProps = {
placeholder?: string;
/** Custom render for the selected value in the trigger (single mode only) */
renderValue?: (option: ComboboxOption) => React.ReactNode;
- /** Text shown when no options match the search */
+ /** Text shown when no options match the search. Ignored when
+ * `noResultsContent` is provided. */
noResultsText?: string;
+ /** Custom rich empty-state node — replaces `noResultsText`. Useful when
+ * the empty state needs links or conditional copy beyond a flat string. */
+ noResultsContent?: React.ReactNode;
/** Server-side search callback. When provided, filters via this instead of client-side. */
onSearch?: (query: string) => void;
className?: string;
@@ -89,6 +93,7 @@ export function Combobox(props: ComboboxProps) {
placeholder = "",
renderValue,
noResultsText,
+ noResultsContent,
onSearch,
className,
disabled,
@@ -381,9 +386,13 @@ export function Combobox(props: ComboboxProps) {
/>
<div className="max-h-60 overflow-y-auto">
{filteredGroups.every((g) => g.options.length === 0) ? (
- <div className="px-3 py-6 text-sm text-control-placeholder text-center">
- {noResultsText ?? "—"}
- </div>
+ noResultsContent !== undefined ? (
+ <div className="p-3">{noResultsContent}</div>
+ ) : (
+ <div className="px-3 py-6 text-sm text-control-placeholder text-center">
+ {noResultsText ?? "—"}
+ </div>
+ )
) : (
filteredGroups.map((group) => (
<div key={group.label}>
diff --git a/frontend/src/react/hooks/useDelayedValue.test.tsx b/frontend/src/react/hooks/useDelayedValue.test.tsx
new file mode 100644
index 0000000000..f80eb55d65
--- /dev/null
+++ b/frontend/src/react/hooks/useDelayedValue.test.tsx
@@ -0,0 +1,141 @@
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { type UseDelayedValueResult, useDelayedValue } from "./useDelayedValue";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+type HarnessHandle = UseDelayedValueResult<string>;
+
+function Harness({
+ handleRef,
+}: {
+ handleRef: { current: HarnessHandle | null };
+}) {
+ const result = useDelayedValue("idle", {
+ delayBefore: 1000,
+ delayAfter: 350,
+ });
+ handleRef.current = result;
+ return null;
+}
+
+let container: HTMLDivElement;
+let root: Root;
+let handle: { current: HarnessHandle | null };
+
+function mount() {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ handle = { current: null };
+ act(() => {
+ root.render(<Harness handleRef={handle} />);
+ });
+}
+
+function unmount() {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+}
+
+describe("useDelayedValue", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ mount();
+ });
+
+ afterEach(() => {
+ unmount();
+ vi.useRealTimers();
+ });
+
+ test("commits the value after the before-delay elapses", () => {
+ act(() => {
+ handle.current!.update("open", "before");
+ });
+ expect(handle.current!.value).toBe("idle");
+ act(() => {
+ vi.advanceTimersByTime(999);
+ });
+ expect(handle.current!.value).toBe("idle");
+ act(() => {
+ vi.advanceTimersByTime(1);
+ });
+ expect(handle.current!.value).toBe("open");
+ });
+
+ test("uses the after-delay when direction is 'after'", () => {
+ act(() => {
+ handle.current!.update("closed", "after");
+ });
+ act(() => {
+ vi.advanceTimersByTime(349);
+ });
+ expect(handle.current!.value).toBe("idle");
+ act(() => {
+ vi.advanceTimersByTime(1);
+ });
+ expect(handle.current!.value).toBe("closed");
+ });
+
+ test("rapid update bursts collapse to the latest value", () => {
+ act(() => {
+ handle.current!.update("first", "before");
+ });
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ act(() => {
+ handle.current!.update("second", "before");
+ });
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ // The first scheduled write was cancelled at t=500; the second
+ // scheduled write fires at t=500+1000=1500. At now=1000 we are
+ // still 500ms shy of it.
+ expect(handle.current!.value).toBe("idle");
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(handle.current!.value).toBe("second");
+ });
+
+ test("overrideDelay takes precedence over direction default", () => {
+ act(() => {
+ handle.current!.update("now", "before", 0);
+ });
+ expect(handle.current!.value).toBe("now");
+ });
+
+ test("cancel() prevents a pending commit", () => {
+ act(() => {
+ handle.current!.update("never", "before");
+ });
+ act(() => {
+ handle.current!.cancel();
+ });
+ act(() => {
+ vi.advanceTimersByTime(2000);
+ });
+ expect(handle.current!.value).toBe("idle");
+ });
+
+ test("unmount clears any pending timer", () => {
+ act(() => {
+ handle.current!.update("late", "before");
+ });
+ unmount();
+ // If the timer survived unmount, this would throw a React warning
+ // about updating an unmounted component. The test passes silently
+ // when cleanup is correct.
+ expect(() => vi.advanceTimersByTime(2000)).not.toThrow();
+ // Re-mount for the afterEach unmount call to succeed.
+ mount();
+ });
+});
diff --git a/frontend/src/react/hooks/useDelayedValue.ts b/frontend/src/react/hooks/useDelayedValue.ts
new file mode 100644
index 0000000000..5379a08ace
--- /dev/null
+++ b/frontend/src/react/hooks/useDelayedValue.ts
@@ -0,0 +1,68 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+
+export type UseDelayedValueOptions = {
+ delayBefore?: number;
+ delayAfter?: number;
+};
+
+export type DelayedValueUpdate<T> = (
+ value: T,
+ direction: "before" | "after",
+ overrideDelay?: number
+) => void;
+
+export type UseDelayedValueResult<T> = {
+ value: T;
+ update: DelayedValueUpdate<T>;
+ cancel: () => void;
+};
+
+/**
+ * React port of `src/composables/useDelayedValue.ts`.
+ *
+ * Schedules transitions to a value after a configurable delay; commits
+ * immediately when delay is 0. The "before"/"after" direction lets the
+ * caller use a longer open delay (e.g. 1000ms before showing a hover
+ * panel) and a shorter close delay (e.g. 350ms before hiding it).
+ *
+ * The timer lives in a ref so it survives re-renders without resetting,
+ * and is unconditionally cleared on every reschedule + on unmount —
+ * so rapid update bursts can never leave a stale callback to fire
+ * after the component has gone away.
+ */
+export function useDelayedValue<T>(
+ initialValue: T,
+ options: UseDelayedValueOptions = {}
+): UseDelayedValueResult<T> {
+ const { delayBefore = 0, delayAfter = 0 } = options;
+ const [value, setValue] = useState<T>(initialValue);
+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const cancel = useCallback(() => {
+ if (timerRef.current !== null) {
+ clearTimeout(timerRef.current);
+ timerRef.current = null;
+ }
+ }, []);
+
+ const update = useCallback<DelayedValueUpdate<T>>(
+ (next, direction, overrideDelay) => {
+ const delay =
+ overrideDelay ?? (direction === "before" ? delayBefore : delayAfter);
+ cancel();
+ if (delay > 0) {
+ timerRef.current = setTimeout(() => {
+ timerRef.current = null;
+ setValue(next);
+ }, delay);
+ } else {
+ setValue(next);
+ }
+ },
+ [cancel, delayBefore, delayAfter]
+ );
+
+ useEffect(() => cancel, [cancel]);
+
+ return { value, update, cancel };
+}
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index 7a3e375bad..1973f8bcaa 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -196,6 +196,7 @@
"show-diff": "Show diff"
},
"common": {
+ "Default": "Default",
"action-required": "Action Required",
"actions": "Actions",
"activated": "Activated",
@@ -295,6 +296,7 @@
"home": "Home",
"id": "ID",
"import": "Import",
+ "info": "Info",
"instance": "Instance",
"instances": "Instances",
"is-required": "is required",
@@ -710,17 +712,22 @@
"database": {
"all": "All databases",
"change-database": "Change Database",
+ "checks": "Checks",
"classification": {
"description": "Define classification levels to apply consistent masking policies across columns and databases."
},
"columns": "Columns",
+ "comment": "Comment",
"data-size": "Data size",
"edit-environment": "Edit Environment",
"edit-labels": "Edit Labels",
"edit-schema": "Edit Schema",
"engine": "Engine",
"expression": "Expression",
+ "external-database-name": "External Database Name",
+ "external-server-name": "External Server Name",
"filter-database": "Filter database",
+ "foreign-keys": "Foreign keys",
"index-size": "Index size",
"indexes": "Indexes",
"last-sync": "Last sync",
@@ -843,6 +850,8 @@
"functions": "Functions",
"n-databases-had-sync-errors": "{{0}} database(s) had sync errors",
"packages": "Packages",
+ "partitions": "Partitions",
+ "procedures": "Procedures",
"schema": {
"default": "Default schema"
},
@@ -1904,6 +1913,9 @@
"rollout.task.no-tasks": "No tasks in this stage",
"rollout.task.selected-count": "{{count}} task selected",
"rollout.task.statement-truncated-hint": "Statement truncated due to large size.",
+ "schema-diagram": {
+ "self": "Schema Diagram"
+ },
"schema-editor": {
"actions": {
"add-column": "Add column",
@@ -1965,6 +1977,11 @@
"name-placeholder": "Table name",
"no-match": "No tables match the search",
"no-tables": "No tables"
+ },
+ "table-partition": {
+ "expression": "Expression",
+ "type": "Type",
+ "value": "Value"
}
},
"schema-template": {
@@ -2562,9 +2579,13 @@
},
"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",
"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-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.",
"duration-day": "{{days}} day",
"duration-days": "{{days}} days",
@@ -2573,6 +2594,7 @@
"expire-in": "Expire in {{time}}",
"expired": "Expired",
"format-sql": "Format SQL",
+ "generate-sql": "Generate SQL",
"grant-type-unmask": "Unmask",
"hint-tips": {
"confirm-to-close-unsaved-sheet": {
@@ -2581,15 +2603,22 @@
}
},
"jit": "Just-In-Time Access",
+ "last-synced": "Last synced: <time></time>",
"link-access": "Link access",
"loading-databases": "Loading Databases...",
"manage-connections": "Manage connections",
"no-access-requests": "No access requests",
"no-database-selected": "No database selected",
"no-history-found": "No history found",
+ "no-project": {
+ "contact-the-admin-to-grant-access": "Contact to the admin to grant access.",
+ "go-to-create": "Go to create",
+ "not-member-of-any-projects": "You are not any member of any projects."
+ },
"no-queriable-database": "No queriable database",
"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",
"private": "Private",
"private-desc": "Only you can access this sheet",
"project-read": "Project read",
@@ -2621,6 +2650,7 @@
"select-a-database-to-start": "Select a database to start",
"self": "SQL Editor",
"show-databases-without-query-permission": "Show databases without query permissions",
+ "sync-in-progress": "Sync in progress",
"tab": {
"context-menu": {
"actions": {
@@ -2639,7 +2669,9 @@
"unmask-warning": "The query result may include unmasked sensitive data.",
"url-copied-to-clipboard": "The URL is copied to your clipboard",
"view-database-detail": "View database detail",
+ "view-detail": "View detail",
"view-issue": "View Issue",
+ "view-schema-text": "View schema text",
"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.json
index 62c04e5de0..ec219bd999 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -195,6 +195,7 @@
"show-diff": "Mostrar diferencias"
},
"common": {
+ "Default": "Predeterminado",
"action-required": "Acción requerida",
"actions": "Acciones",
"activated": "Activado",
@@ -292,6 +293,7 @@
"home": "Inicio",
"id": "ID",
"import": "Importar",
+ "info": "Información",
"instance": "Instancia",
"instances": "Instancias",
"is-required": "is required",
@@ -703,17 +705,22 @@
"database": {
"all": "Todas las bases de datos",
"change-database": "Modificar base de datos",
+ "checks": "Verificaciones",
"classification": {
"description": "Define classification levels to apply consistent masking policies across columns and databases."
},
"columns": "Columnas",
+ "comment": "Comentario",
"data-size": "Tamaño de datos",
"edit-environment": "Editar entorno",
"edit-labels": "Editar etiquetas",
"edit-schema": "Modificar esquema",
"engine": "Motor",
"expression": "Expression",
+ "external-database-name": "Nombre de la base de datos externa",
+ "external-server-name": "Nombre del servidor externo",
"filter-database": "Filtrar base de datos",
+ "foreign-keys": "claves foráneas",
"index-size": "Tamaño del índice",
"indexes": "Índices",
"last-sync": "Última sincronización",
@@ -836,6 +843,8 @@
"functions": "Funciones",
"n-databases-had-sync-errors": "{{0}} base(s) de datos tuvieron errores de sincronización",
"packages": "Paquetes",
+ "partitions": "Particiones",
+ "procedures": "Procedimientos",
"schema": {
"default": "Esquema predeterminado"
},
@@ -1891,6 +1900,9 @@
"rollout.task.no-tasks": "No hay tareas en esta etapa",
"rollout.task.selected-count": "{{count}} tarea seleccionada",
"rollout.task.statement-truncated-hint": "Declaración truncada debido al gran tamaño.",
+ "schema-diagram": {
+ "self": "Diagrama de Esquema"
+ },
"schema-editor": {
"actions": {
"add-column": "Add column",
@@ -1952,6 +1964,11 @@
"name-placeholder": "Table name",
"no-match": "No tables match the search",
"no-tables": "No tables"
+ },
+ "table-partition": {
+ "expression": "Expresión",
+ "type": "Tipo",
+ "value": "Valor"
}
},
"schema-template": {
@@ -2548,9 +2565,13 @@
},
"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",
"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-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.",
"duration-day": "{{days}} day",
"duration-days": "{{days}} days",
@@ -2559,6 +2580,7 @@
"expire-in": "Expire in {{time}}",
"expired": "Expired",
"format-sql": "Format SQL",
+ "generate-sql": "Generar SQL",
"grant-type-unmask": "Unmask",
"hint-tips": {
"confirm-to-close-unsaved-sheet": {
@@ -2567,15 +2589,22 @@
}
},
"jit": "Just-In-Time Access",
+ "last-synced": "Última sincronización: <time></time>",
"link-access": "Acceso al enlace",
"loading-databases": "Cargando bases de datos...",
"manage-connections": "Gestionar las conexiones",
"no-access-requests": "No access requests",
"no-database-selected": "No se ha seleccionado una base de datos",
"no-history-found": "No se encontró historial",
+ "no-project": {
+ "contact-the-admin-to-grant-access": "Póngase en contacto con el administrador para otorgar acceso.",
+ "go-to-create": "ir a crear",
+ "not-member-of-any-projects": "No eres miembro de ningún proyecto."
+ },
"no-queriable-database": "No hay base de datos consultable",
"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",
"private": "Privado",
"private-desc": "Solo tú puedes acceder a esta hoja",
"project-read": "Lectura del proyecto",
@@ -2607,6 +2636,7 @@
"select-a-database-to-start": "Seleccione una base de datos para comenzar",
"self": "Editor de SQL",
"show-databases-without-query-permission": "Muestra las bases de datos que no tienen permisos de consulta",
+ "sync-in-progress": "Sincronización en progreso",
"tab": {
"context-menu": {
"actions": {
@@ -2625,7 +2655,9 @@
"unmask-warning": "The query result may include unmasked sensitive data.",
"url-copied-to-clipboard": "La URL se copia al portapapeles.",
"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",
"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.json
index f51ca39230..75c92cc96a 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -195,6 +195,7 @@
"show-diff": "違いを表示"
},
"common": {
+ "Default": "デフォルト",
"action-required": "対応が必要",
"actions": "アクション",
"activated": "有効化しました",
@@ -292,6 +293,7 @@
"home": "ホームページ",
"id": "ID",
"import": "インポート",
+ "info": "情報",
"instance": "インスタンス",
"instances": "インスタンス",
"is-required": "is required",
@@ -703,17 +705,22 @@
"database": {
"all": "すべてのデータベース",
"change-database": "データベースの変更",
+ "checks": "チェック",
"classification": {
"description": "Define classification levels to apply consistent masking policies across columns and databases."
},
"columns": "カラム",
+ "comment": "コメント",
"data-size": "データサイズ",
"edit-environment": "環境の編集",
"edit-labels": "ラベルを編集",
"edit-schema": "スキーマの変更",
"engine": "エンジン",
"expression": "Expression",
+ "external-database-name": "外部データベース名",
+ "external-server-name": "外部サーバー名",
"filter-database": "データベースをフィルター",
+ "foreign-keys": "外部キー",
"index-size": "インデックスサイズ",
"indexes": "索引",
"last-sync": "最後の同期",
@@ -836,6 +843,8 @@
"functions": "関数",
"n-databases-had-sync-errors": "{{0}} 個のデータベースで同期エラーが発生しました",
"packages": "パッケージ",
+ "partitions": "パーティション",
+ "procedures": "ストアドプロシージャ",
"schema": {
"default": "デフォルトスキーマ"
},
@@ -1891,6 +1900,9 @@
"rollout.task.no-tasks": "このステージにはタスクがありません",
"rollout.task.selected-count": "{{count}} 件のタスクを選択中",
"rollout.task.statement-truncated-hint": "サイズが大きいため、ステートメントは切り捨てられました。",
+ "schema-diagram": {
+ "self": "スキーマ図"
+ },
"schema-editor": {
"actions": {
"add-column": "Add column",
@@ -1952,6 +1964,11 @@
"name-placeholder": "Table name",
"no-match": "No tables match the search",
"no-tables": "No tables"
+ },
+ "table-partition": {
+ "expression": "表現",
+ "type": "タイプ",
+ "value": "値"
}
},
"schema-template": {
@@ -2548,9 +2565,13 @@
},
"choose-folder": "フォルダを選択または作成",
"choose-folder-tips": "存在しないパスを入力することで新しいフォルダを作成できます。フォルダは「/」で結合する必要があります。",
+ "click-to-sync-now": "クリックして今すぐ同期します",
"close-sheet": "ワークシートを閉じる",
"connect-in-admin-mode": "管理者モードで接続する",
"connect-to-a-database": "データベースに接続",
+ "copy-all-column-names": "すべての列名をコピーします",
+ "copy-name": "名前をコピーする",
+ "copy-url": "URLをコピー",
"ddl-dml-requires-data-change-plan": "<environment></environment> で DDL/DML ステートメントを実行するには、承認のためデータ変更プランを送信してください。",
"duration-day": "{{days}} day",
"duration-days": "{{days}} days",
@@ -2559,6 +2580,7 @@
"expire-in": "Expire in {{time}}",
"expired": "Expired",
"format-sql": "Format SQL",
+ "generate-sql": "SQLの生成",
"grant-type-unmask": "Unmask",
"hint-tips": {
"confirm-to-close-unsaved-sheet": {
@@ -2567,15 +2589,22 @@
}
},
"jit": "Just-In-Time Access",
+ "last-synced": "最終同期時間: <time></time>",
"link-access": "リンクアクセス",
"loading-databases": "データベース情報をロードしています...",
"manage-connections": "接続を管理する",
"no-access-requests": "No access requests",
"no-database-selected": "データベースが選択されていません",
"no-history-found": "まだ履歴がありません",
+ "no-project": {
+ "contact-the-admin-to-grant-access": "管理者に連絡してアクセスを許可してください。",
+ "go-to-create": "作成に行く",
+ "not-member-of-any-projects": "あなたはどのプロジェクトのメンバーでもありません。"
+ },
"no-queriable-database": "クエリ可能なデータベースがありません",
"only-select-allowed": "読み取り専用ステートメントのみが実行を許可されます",
"open-in-new-tab": "新しいタブで開く",
+ "preview-table-data": "テーブルデータのプレビュー",
"private": "プライベート",
"private-desc": "このシートにアクセスできるのはあなただけです",
"project-read": "プロジェクト内で読み取り可能",
@@ -2607,6 +2636,7 @@
"select-a-database-to-start": "開始するにはデータベースを選択してください",
"self": "SQLエディタ",
"show-databases-without-query-permission": "クエリ権限のないデータベースを表示します",
+ "sync-in-progress": "同期中",
"tab": {
"context-menu": {
"actions": {
@@ -2625,7 +2655,9 @@
"unmask-warning": "The query result may include unmasked sensitive data.",
"url-copied-to-clipboard": "URLがクリップボードにコピーされました",
"view-database-detail": "データベースの詳細を表示する",
+ "view-detail": "詳細を見る",
"view-issue": "View Issue",
+ "view-schema-text": "テキストの表示 スキーマ",
"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.json
index b91712f119..36c6267b1f 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -195,6 +195,7 @@
"show-diff": "Hiển thị khác biệt"
},
"common": {
+ "Default": "Mặc định",
"action-required": "Cần thực hiện hành động",
"actions": "Hành động",
"activated": "Đã kích hoạt",
@@ -292,6 +293,7 @@
"home": "Trang chủ",
"id": "ID",
"import": "Nhập",
+ "info": "Thông tin",
"instance": "Phiên bản",
"instances": "Phiên bản",
"is-required": "is required",
@@ -703,17 +705,22 @@
"database": {
"all": "Tất cả cơ sở dữ liệu",
"change-database": "Thay đổi cơ sở dữ liệu",
+ "checks": "Kiểm tra",
"classification": {
"description": "Define classification levels to apply consistent masking policies across columns and databases."
},
"columns": "Cột",
+ "comment": "Bình luận",
"data-size": "Kích thước dữ liệu",
"edit-environment": "Chỉnh sửa Môi trường",
"edit-labels": "Chỉnh sửa nhãn",
"edit-schema": "Chỉnh sửa lược đồ",
"engine": "Engine",
"expression": "Expression",
+ "external-database-name": "Tên cơ sở dữ liệu bên ngoài",
+ "external-server-name": "Tên máy chủ bên ngoài",
"filter-database": "Lọc cơ sở dữ liệu",
+ "foreign-keys": "Khóa ngoại",
"index-size": "Kích thước chỉ mục",
"indexes": "Chỉ mục",
"last-sync": "Lần đồng bộ cuối cùng",
@@ -836,6 +843,8 @@
"functions": "Hàm",
"n-databases-had-sync-errors": "{{0}} cơ sở dữ liệu gặp lỗi đồng bộ",
"packages": "Gói",
+ "partitions": "Phân vùng",
+ "procedures": "Thủ tục",
"schema": {
"default": "Schema mặc định"
},
@@ -1891,6 +1900,9 @@
"rollout.task.no-tasks": "Không có tác vụ trong giai đoạn này",
"rollout.task.selected-count": "Đã chọn {{count}} tác vụ",
"rollout.task.statement-truncated-hint": "Câu lệnh bị cắt bớt do kích thước lớn.",
+ "schema-diagram": {
+ "self": "Sơ đồ Lược đồ"
+ },
"schema-editor": {
"actions": {
"add-column": "Add column",
@@ -1952,6 +1964,11 @@
"name-placeholder": "Table name",
"no-match": "No tables match the search",
"no-tables": "No tables"
+ },
+ "table-partition": {
+ "expression": "Biểu thức",
+ "type": "Loại",
+ "value": "Giá trị"
}
},
"schema-template": {
@@ -2548,9 +2565,13 @@
},
"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",
"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-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.",
"duration-day": "{{days}} day",
"duration-days": "{{days}} days",
@@ -2559,6 +2580,7 @@
"expire-in": "Expire in {{time}}",
"expired": "Expired",
"format-sql": "Format SQL",
+ "generate-sql": "Tạo SQL",
"grant-type-unmask": "Unmask",
"hint-tips": {
"confirm-to-close-unsaved-sheet": {
@@ -2567,15 +2589,22 @@
}
},
"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-databases": "Đang tải Cơ sở dữ liệu...",
"manage-connections": "Quản lý kết nối",
"no-access-requests": "No access requests",
"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": {
+ "contact-the-admin-to-grant-access": "Liên hệ với quản trị viên để cấp quyền truy cập.",
+ "go-to-create": "Đi tới tạo",
+ "not-member-of-any-projects": "Bạn không phải là thành viên của bất kỳ dự án nào."
+ },
"no-queriable-database": "Không có cơ sở dữ liệu có thể truy vấn",
"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",
"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",
@@ -2607,6 +2636,7 @@
"select-a-database-to-start": "Chọn một cơ sở dữ liệu để bắt đầu",
"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",
+ "sync-in-progress": "Đang đồng bộ",
"tab": {
"context-menu": {
"actions": {
@@ -2625,7 +2655,9 @@
"unmask-warning": "The query result may include unmasked sensitive data.",
"url-copied-to-clipboard": "URL đã được sao chép vào bảng nhớ tạm của bạn",
"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 đồ",
"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.json
index ed1d9a148b..4df48a77e3 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -195,6 +195,7 @@
"show-diff": "显示差异"
},
"common": {
+ "Default": "默认",
"action-required": "需要操作",
"actions": "操作",
"activated": "已激活",
@@ -292,6 +293,7 @@
"home": "主页",
"id": "ID",
"import": "导入",
+ "info": "信息",
"instance": "实例",
"instances": "实例",
"is-required": "is required",
@@ -703,17 +705,22 @@
"database": {
"all": "所有数据库",
"change-database": "变更数据库",
+ "checks": "Check 约束",
"classification": {
"description": "定义分类分级,跨列和数据库统一应用脱敏策略。"
},
"columns": "列",
+ "comment": "注释",
"data-size": "数据大小",
"edit-environment": "编辑环境",
"edit-labels": "编辑标签",
"edit-schema": "变更 Schema",
"engine": "引擎",
"expression": "Expression",
+ "external-database-name": "外部数据库名称",
+ "external-server-name": "外部服务器名称",
"filter-database": "筛选数据库",
+ "foreign-keys": "外键",
"index-size": "索引大小",
"indexes": "索引",
"last-sync": "最后一次同步",
@@ -836,6 +843,8 @@
"functions": "函数",
"n-databases-had-sync-errors": "{{0}} 个数据库同步出错",
"packages": "包",
+ "partitions": "分区",
+ "procedures": "存储过程",
"schema": {
"default": "默认 Schema"
},
@@ -1891,6 +1900,9 @@
"rollout.task.no-tasks": "此阶段没有任务",
"rollout.task.selected-count": "已选择 {{count}} 个任务",
"rollout.task.statement-truncated-hint": "由于语句过长,已被截断。",
+ "schema-diagram": {
+ "self": "Schema 关系图"
+ },
"schema-editor": {
"actions": {
"add-column": "Add column",
@@ -1952,6 +1964,11 @@
"name-placeholder": "Table name",
"no-match": "No tables match the search",
"no-tables": "No tables"
+ },
+ "table-partition": {
+ "expression": "表达式",
+ "type": "类型",
+ "value": "值"
}
},
"schema-template": {
@@ -2548,9 +2565,13 @@
},
"choose-folder": "选择或创建文件夹",
"choose-folder-tips": "您可以通过输入不存在的路径来创建新文件夹。文件夹之间应以\"/\"连接。",
+ "click-to-sync-now": "点击立即同步",
"close-sheet": "关闭工作表",
"connect-in-admin-mode": "以管理员模式连接",
"connect-to-a-database": "连接数据库",
+ "copy-all-column-names": "复制所有列名",
+ "copy-name": "复制名称",
+ "copy-url": "复制 URL",
"ddl-dml-requires-data-change-plan": "如需在 <environment></environment> 中执行 DDL/DML 语句,请创建变更计划以获得审批。",
"duration-day": "{{days}} 天",
"duration-days": "{{days}} 天",
@@ -2559,6 +2580,7 @@
"expire-in": "{{time}} 后过期",
"expired": "已过期",
"format-sql": "格式化 SQL",
+ "generate-sql": "生成 SQL",
"grant-type-unmask": "脱敏豁免",
"hint-tips": {
"confirm-to-close-unsaved-sheet": {
@@ -2567,15 +2589,22 @@
}
},
"jit": "即时访问",
+ "last-synced": "上次同步时间:<time></time>",
"link-access": "链接访问权限",
"loading-databases": "加载数据库信息...",
"manage-connections": "管理连接",
"no-access-requests": "暂无访问请求",
"no-database-selected": "未选择数据库",
"no-history-found": "暂无历史记录",
+ "no-project": {
+ "contact-the-admin-to-grant-access": "联系管理员以授予访问权限。",
+ "go-to-create": "去创建",
+ "not-member-of-any-projects": "你不是任何项目的成员。"
+ },
"no-queriable-database": "没有可查询的数据库",
"only-select-allowed": "只允许执行只读语句",
"open-in-new-tab": "在新选项卡中打开",
+ "preview-table-data": "预览表数据",
"private": "私有",
"private-desc": "只有您自己可以访问此工作表",
"project-read": "项目内可读",
@@ -2607,6 +2636,7 @@
"select-a-database-to-start": "选择数据库以开始",
"self": "SQL 编辑器",
"show-databases-without-query-permission": "显示没有查询权限的数据库",
+ "sync-in-progress": "正在同步",
"tab": {
"context-menu": {
"actions": {
@@ -2625,7 +2655,9 @@
"unmask-warning": "The query result may include unmasked sensitive data.",
"url-copied-to-clipboard": "URL 已复制到剪贴板",
"view-database-detail": "查看数据库详情",
+ "view-detail": "查看详情",
"view-issue": "查看工单",
+ "view-schema-text": "查看文本 Schema",
"web-socket": {
"errors": {
"description": "Auto Completion might be limited or disabled.",
diff --git a/frontend/src/store/modules/sqlEditor/uiState.test.ts b/frontend/src/store/modules/sqlEditor/uiState.test.ts
index 8df42c72e8..0b7fb5ebf5 100644
--- a/frontend/src/store/modules/sqlEditor/uiState.test.ts
+++ b/frontend/src/store/modules/sqlEditor/uiState.test.ts
@@ -45,7 +45,6 @@ describe("useSQLEditorUIStore", () => {
expect(store.asidePanelTab).toBe("WORKSHEET");
expect(store.showConnectionPanel).toBe(false);
expect(store.showAIPanel).toBe(false);
- expect(store.schemaViewer).toBeUndefined();
expect(store.pendingInsertAtCaret).toBeUndefined();
expect(store.highlightAccessGrantName).toBeUndefined();
});
diff --git a/frontend/src/store/modules/sqlEditor/uiState.ts b/frontend/src/store/modules/sqlEditor/uiState.ts
index 83f0ba756e..7113e1ba8a 100644
--- a/frontend/src/store/modules/sqlEditor/uiState.ts
+++ b/frontend/src/store/modules/sqlEditor/uiState.ts
@@ -1,7 +1,6 @@
import { useLocalStorage } from "@vueuse/core";
import { defineStore } from "pinia";
import { computed, ref } from "vue";
-import type { GetSchemaStringRequest_ObjectType } from "@/types/proto-es/v1/database_service_pb";
import { STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE } from "@/utils/storage-keys";
export type AsidePanelTab = "SCHEMA" | "WORKSHEET" | "HISTORY" | "ACCESS";
@@ -20,14 +19,6 @@ export const useSQLEditorUIStore = defineStore("sqlEditorUI", () => {
const asidePanelTab = ref<AsidePanelTab>("WORKSHEET");
const showConnectionPanel = ref(false);
const showAIPanel = ref(false);
- const schemaViewer = ref<
- | {
- schema?: string;
- object?: string;
- type?: GetSchemaStringRequest_ObjectType;
- }
- | undefined
- >(undefined);
const pendingInsertAtCaret = ref<string | undefined>();
const highlightAccessGrantName = ref<string | undefined>();
@@ -56,7 +47,6 @@ export const useSQLEditorUIStore = defineStore("sqlEditorUI", () => {
asidePanelTab,
showConnectionPanel,
showAIPanel,
- schemaViewer,
pendingInsertAtCaret,
highlightAccessGrantName,
editorPanelSize,
diff --git a/frontend/src/views/sql-editor/AsidePanel/ActionBar/ActionBar.vue b/frontend/src/views/sql-editor/AsidePanel/ActionBar/ActionBar.vue
deleted file mode 100644
index 455044d318..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/ActionBar/ActionBar.vue
+++ /dev/null
@@ -1,20 +0,0 @@
-<template>
- <div
- class="h-full flex flex-col items-stretch justify-between overflow-hidden text-sm p-1 shrink-0"
- >
- <div class="flex flex-col gap-y-1">
- <TabItem
- v-for="action in availableActions"
- :key="action.view"
- :action="action"
- />
- </div>
- </div>
-</template>
-
-<script setup lang="ts">
-import { useCurrentTabViewStateContext } from "../../EditorPanel/context/viewState.tsx";
-import TabItem from "./TabItem.vue";
-
-const { availableActions } = useCurrentTabViewStateContext();
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/ActionBar/TabItem.vue b/frontend/src/views/sql-editor/AsidePanel/ActionBar/TabItem.vue
deleted file mode 100644
index 14b784783b..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/ActionBar/TabItem.vue
+++ /dev/null
@@ -1,67 +0,0 @@
-<template>
- <NTooltip placement="right" :delay="300" :disabled="disabled">
- <template #trigger>
- <NButton
- :style="buttonStyle"
- v-bind="{ ...buttonProps, ...$attrs }"
- @click="handleClick"
- >
- <template #icon>
- <component :is="action.icon" :class="iconClass" />
- </template>
- </NButton>
- </template>
- <template #default>
- {{ action.title }}
- </template>
- </NTooltip>
-</template>
-
-<script setup lang="ts">
-import { NButton, NTooltip } from "naive-ui";
-import type { VNodeChild } from "vue";
-import { computed, toRef } from "vue";
-import { useConnectionOfCurrentSQLEditorTab } from "@/store";
-import type { EditorPanelView } from "@/types";
-import { extractDatabaseResourceName } from "@/utils";
-import { useActions } from "../../AsidePanel/SchemaPane/actions";
-import { useCurrentTabViewStateContext } from "../../EditorPanel/context/viewState.tsx";
-import { useButton } from "./common";
-
-const props = defineProps<{
- action: {
- view: EditorPanelView;
- title: string;
- icon: () => VNodeChild;
- };
- disabled?: boolean;
-}>();
-
-const active = computed(() => props.action.view === viewState.value?.view);
-const { viewState } = useCurrentTabViewStateContext();
-const { database } = useConnectionOfCurrentSQLEditorTab();
-
-const { props: buttonProps, style: buttonStyle } = useButton({
- active,
- disabled: toRef(props, "disabled"),
-});
-
-const iconClass = computed(() => {
- const classes = ["w-4", "h-4"];
- if (active.value) {
- classes.push("text-current!");
- } else {
- classes.push("text-main");
- }
- return classes;
-});
-
-const { openNewTab } = useActions();
-
-const handleClick = () => {
- openNewTab({
- title: `[${extractDatabaseResourceName(database.value.name).databaseName}] ${props.action.title}`,
- view: props.action.view,
- });
-};
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/ActionBar/common.ts b/frontend/src/views/sql-editor/AsidePanel/ActionBar/common.ts
deleted file mode 100644
index b033eb16ae..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/ActionBar/common.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import type { ButtonProps } from "naive-ui";
-import { computed, type MaybeRef, unref } from "vue";
-
-export const useButton = (options: {
- active: MaybeRef<boolean>;
- disabled: MaybeRef<boolean>;
-}) => {
- const props = computed(() => {
- const props: ButtonProps = {
- tag: "div",
- disabled: unref(options.disabled),
- size: "small",
- };
- if (unref(options.active)) {
- props.secondary = true;
- props.type = "primary";
- } else {
- props.quaternary = true;
- props.type = "default";
- }
- props.disabled = unref(options.disabled);
-
- return props;
- });
- const style = computed(() => {
- const parts: string[] = [];
-
- parts.push("--n-height: 32px");
- parts.push("--n-padding: 4px 8px");
- parts.push("--n-icon-size: 16px");
- return parts.join("; ");
- });
- return { props, style };
-};
diff --git a/frontend/src/views/sql-editor/AsidePanel/ActionBar/index.ts b/frontend/src/views/sql-editor/AsidePanel/ActionBar/index.ts
deleted file mode 100644
index ea25fe44bc..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/ActionBar/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import ActionBar from "./ActionBar.vue";
-
-export default ActionBar;
diff --git a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue b/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
deleted file mode 100644
index 9fe6d4e099..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/AsidePanel.vue
+++ /dev/null
@@ -1,127 +0,0 @@
-<template>
- <div
- ref="containerRef"
- class="h-full flex flex-row overflow-hidden"
- :data-width="containerWidth"
- >
- <div class="h-full border-r shrink-0">
- <ReactPageMount page="GutterBar" />
- </div>
- <div
- v-if="asidePanelTab === 'SCHEMA' && !isDisconnected"
- class="h-full border-r shrink-0"
- >
- <ActionBar />
- </div>
- <div class="h-full flex-1 flex flex-col overflow-hidden">
- <div class="flex flex-row items-center gap-x-1 px-1 py-1 border-b">
- <ProjectSelect
- style="width: 100%"
- class="project-select"
- :menu-props="{ class: 'project-select-menu' }"
- :value="project"
- :include-all="false"
- :clearable="false"
- :include-default-project="allowAccessDefaultProject"
- :loading="!projectContextReady"
- @update:value="handleSwitchProject($event as (string | undefined))"
- >
- <template #empty>
- <div class="text-sm text-control-placeholder flex flex-col gap-1">
- <p>
- {{ $t("sql-editor.no-project.not-member-of-any-projects") }}
- <RouterLink
- v-if="allowCreateProject"
- :to="{
- name: PROJECT_V1_ROUTE_DASHBOARD,
- hash: '#new',
- }"
- >
- {{ $t("sql-editor.no-project.go-to-create") }}
- </RouterLink>
- </p>
- <p v-if="!allowCreateProject">
- {{
- $t("sql-editor.no-project.contact-the-admin-to-grant-access")
- }}
- </p>
- </div>
- </template>
- </ProjectSelect>
- </div>
-
- <div class="flex-1 flex flex-row overflow-hidden">
- <div class="h-full flex-1 flex flex-col pt-1 overflow-hidden">
- <ReactPageMount
- v-if="asidePanelTab === 'WORKSHEET'"
- page="WorksheetPane"
- />
- <SchemaPane v-if="asidePanelTab === 'SCHEMA'" />
- <ReactPageMount
- v-if="asidePanelTab === 'HISTORY'"
- page="HistoryPane"
- />
- <ReactPageMount
- v-if="asidePanelTab === 'ACCESS'"
- page="AccessPane"
- />
- </div>
- </div>
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { useElementSize } from "@vueuse/core";
-import { storeToRefs } from "pinia";
-import { computed, ref } from "vue";
-import { ProjectSelect } from "@/components/v2";
-import ReactPageMount from "@/react/ReactPageMount.vue";
-import { PROJECT_V1_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";
-import {
- useActuatorV1Store,
- useSQLEditorStore,
- useSQLEditorTabStore,
-} from "@/store";
-import { defaultProject, isValidProjectName } from "@/types";
-import { hasProjectPermissionV2, hasWorkspacePermissionV2 } from "@/utils";
-import { useSQLEditorContext } from "../context";
-import ActionBar from "./ActionBar";
-import SchemaPane from "./SchemaPane";
-
-const editorStore = useSQLEditorStore();
-const actuatorStore = useActuatorV1Store();
-const { asidePanelTab, maybeSwitchProject } = useSQLEditorContext();
-const { isDisconnected } = storeToRefs(useSQLEditorTabStore());
-
-const { project, projectContextReady } = storeToRefs(editorStore);
-const containerRef = ref<HTMLDivElement>();
-const { width: containerWidth } = useElementSize(containerRef);
-
-const allowAccessDefaultProject = computed(() => {
- const name = actuatorStore.serverInfo?.defaultProject ?? "";
- return hasProjectPermissionV2(defaultProject(name), "bb.projects.get");
-});
-const allowCreateProject = computed(() => {
- return hasWorkspacePermissionV2("bb.projects.create");
-});
-
-const handleSwitchProject = (name: string | undefined) => {
- if (!name || !isValidProjectName(name)) {
- editorStore.setProject("");
- } else {
- maybeSwitchProject(name);
- }
-};
-</script>
-
-<style lang="postcss" scoped>
-.project-select :deep(.n-base-selection) {
- --n-height: 30px !important;
-}
-</style>
-<style lang="postcss">
-.project-select-menu .n-base-select-menu__empty {
- padding: 12px 16px !important;
-}
-</style>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/FlatTableList.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/FlatTableList.vue
deleted file mode 100644
index 0ad6e2f85f..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/FlatTableList.vue
+++ /dev/null
@@ -1,287 +0,0 @@
-<template>
- <div class="flat-table-list h-full flex flex-col">
- <!-- Virtual List -->
- <NVirtualList
- v-if="pagedTables.length > 0"
- :items="pagedTables"
- :item-size="28"
- :item-resizable="false"
- :items-style="{ paddingTop: '4px', paddingBottom: '4px' }"
- >
- <template
- #default="{ item, index }: { item: FlatTableItem; index: number }"
- >
- <div>
- <div
- class="table-item px-2 py-1 hover:bg-control-bg-hover cursor-pointer flex items-center justify-between text-sm"
- :class="{
- 'bg-link-hover font-medium': isSelected(item),
- }"
- @click="handleTableClick(item)"
- @dblclick="handleTableDoubleClick(item)"
- @contextmenu="handleContextMenu($event, item)"
- @mouseenter="handleMouseEnter($event, item)"
- @mouseleave="handleMouseLeave()"
- >
- <div class="flex items-center gap-1 truncate flex-1 min-w-0">
- <NIcon size="14" class="shrink-0">
- <TableIcon />
- </NIcon>
- <span class="truncate">
- <span v-if="item.schema" class="text-gray-500">
- {{ item.schema }}.
- </span>
- <span>{{ item.metadata.name }}</span>
- </span>
- </div>
- <div
- class="flex items-center gap-2 text-xs text-gray-500 shrink-0 ml-2"
- >
- <span> {{ item.metadata.columns.length }} cols </span>
- <NButton
- v-if="item.metadata.columns.length > 0"
- size="tiny"
- quaternary
- circle
- @click.stop="toggleTableExpansion(item)"
- >
- <template #icon>
- <NIcon :size="12">
- <ChevronRightIcon v-if="!expandedTables.has(item.key)" />
- <ChevronDownIcon v-else />
- </NIcon>
- </template>
- </NButton>
- </div>
- </div>
-
- <!-- Expanded Details -->
- <div
- v-if="expandedTables.has(item.key)"
- class="pl-4 pr-2 bg-gray-50 border-l-2 border-gray-200"
- >
- <!-- Columns Section -->
- <div v-if="item.metadata.columns.length > 0" class="py-1">
- <div class="text-xs font-medium text-gray-600 mb-1">
- {{ $t("database.columns") }}
- </div>
- <div
- v-for="column in item.metadata.columns"
- :key="column.name"
- class="flex flex-wrap items-center justify-between gap-1 py-0.5 text-xs pl-2"
- >
- <div class="flex items-center gap-1">
- <NIcon size="12" class="text-gray-400">
- <ColumnIcon />
- </NIcon>
- <span>{{ column.name }}</span>
- </div>
- <span class="text-gray-500">{{ column.type }}</span>
- </div>
- </div>
-
- <!-- Indexes Section -->
- <div
- v-if="item.metadata.indexes && item.metadata.indexes.length > 0"
- class="py-1 border-t border-gray-200"
- >
- <div class="text-xs font-medium text-gray-600 mb-1">
- {{ $t("database.indexes") }}
- </div>
- <div
- v-for="index in item.metadata.indexes"
- :key="index.name"
- class="flex flex-wrap items-center justify-between gap-1 py-0.5 text-xs pl-2"
- >
- <div class="flex items-center gap-1">
- <NIcon size="12" class="text-gray-400">
- <IndexIcon />
- </NIcon>
- <span>{{ index.name }}</span>
- </div>
- <span class="text-gray-500">
- {{ index.unique ? "UNIQUE" : "" }}
- {{ index.primary ? "PRIMARY" : "" }}
- </span>
- </div>
- </div>
- </div>
-
- <NButton
- v-if="
- index === pagedTables.length - 1 &&
- (pageIndex + 1) * PAGE_SIZE < filteredTables.length
- "
- size="tiny"
- quaternary
- class="w-full!"
- @click="() => pageIndex++"
- >
- {{ $t("common.load-more") }}
- </NButton>
- </div>
- </template>
- </NVirtualList>
-
- <NEmpty
- v-if="filteredTables.length === 0"
- class="mt-16"
- :description="search ? 'No tables found' : 'No tables in this database'"
- />
- </div>
-</template>
-
-<script setup lang="ts">
-import { ChevronDownIcon, ChevronRightIcon } from "lucide-vue-next";
-import { NButton, NEmpty, NIcon, NVirtualList } from "naive-ui";
-import { computed, nextTick, ref, watch } from "vue";
-import { ColumnIcon, IndexIcon, TableIcon } from "@/components/Icon";
-import type {
- DatabaseMetadata,
- TableMetadata,
-} from "@/types/proto-es/v1/database_service_pb";
-import { findAncestor } from "@/utils";
-import { useHoverStateContext } from "./HoverPanel";
-
-interface FlatTableItem {
- key: string;
- schema: string;
- metadata: TableMetadata;
-}
-
-const PAGE_SIZE = 500;
-
-const props = defineProps<{
- metadata: DatabaseMetadata;
- search?: string;
- database: string;
-}>();
-
-const emit = defineEmits<{
- select: [table: FlatTableItem];
- "select-all": [table: FlatTableItem];
- contextmenu: [event: MouseEvent, table: FlatTableItem];
-}>();
-
-// Use the existing hover state context
-const {
- state: hoverState,
- position: hoverPosition,
- update: updateHoverState,
-} = useHoverStateContext();
-
-const expandedTables = ref(new Set<string>());
-// Track selected table for flat list
-const selectedTableKey = ref<string>();
-const pageIndex = ref(0);
-
-// Flatten and filter all tables into a single array
-const filteredTables = computed(() => {
- const tables: FlatTableItem[] = [];
- const pattern = props.search?.trim().toLowerCase();
-
- if (!props.metadata?.schemas) return tables;
-
- for (const schema of props.metadata.schemas) {
- for (const table of schema.tables || []) {
- const item = {
- key: `${schema.name}/${table.name}`,
- schema: schema.name,
- metadata: table,
- };
- if (!pattern || item.key.toLowerCase().includes(pattern)) {
- tables.push(item);
- }
- }
- }
-
- return tables;
-});
-
-const pagedTables = computed(() =>
- filteredTables.value.slice(0, (pageIndex.value + 1) * PAGE_SIZE)
-);
-
-const isSelected = (item: FlatTableItem) => {
- return selectedTableKey.value === item.key;
-};
-
-const handleTableClick = (item: FlatTableItem) => {
- selectedTableKey.value = item.key;
- emit("select", item);
-};
-
-const handleTableDoubleClick = (item: FlatTableItem) => {
- selectedTableKey.value = item.key;
- emit("select-all", item);
-};
-
-const handleContextMenu = (event: MouseEvent, item: FlatTableItem) => {
- event.preventDefault();
- selectedTableKey.value = item.key;
- emit("contextmenu", event, item);
-};
-
-const toggleTableExpansion = (item: FlatTableItem) => {
- if (expandedTables.value.has(item.key)) {
- expandedTables.value.delete(item.key);
- } else {
- expandedTables.value.add(item.key);
- }
-};
-
-const handleMouseEnter = (event: MouseEvent, item: FlatTableItem) => {
- const target = {
- database: props.database,
- schema: item.schema,
- table: item.metadata.name,
- };
-
- // Use a small delay even when transitioning between nodes
- // to prevent excessive re-renders when moving quickly
- const delay = hoverState.value ? 150 : undefined;
- updateHoverState(target, "before", delay);
-
- nextTick().then(() => {
- // Find the table item element and position hover panel
- const wrapper = findAncestor(event.target as HTMLElement, ".table-item");
- if (!wrapper) {
- // Clear hover state if we can't find the wrapper
- updateHoverState(undefined, "after", 150);
- return;
- }
- const bounding = wrapper.getBoundingClientRect();
- hoverPosition.value.x = event.clientX;
- hoverPosition.value.y = bounding.bottom;
- });
-};
-
-const handleMouseLeave = () => {
- updateHoverState(undefined, "after");
-};
-
-// Focus search box on mount
-watch(
- [() => props.metadata, () => props.search],
- () => {
- // Reset search when metadata changes
- pageIndex.value = 0;
- expandedTables.value.clear();
- },
- { immediate: true }
-);
-</script>
-
-<style scoped>
-.flat-table-list :deep(.n-virtual-list) {
- --n-item-text-color: var(--n-text-color);
-}
-
-.table-item {
- transition: background-color 0.1s;
-}
-
-.table-item:hover {
- background-color: var(--n-close-color-hover);
-}
-</style>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/ColumnInfo.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/ColumnInfo.vue
deleted file mode 100644
index 1a4136187b..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/ColumnInfo.vue
+++ /dev/null
@@ -1,85 +0,0 @@
-<template>
- <div class="min-w-56 max-w-[18rem] gap-y-1">
- <InfoItem :title="$t('common.name')">
- {{ columnMetadata.name }}
- </InfoItem>
- <InfoItem :title="$t('common.type')">
- {{ columnMetadata.type }}
- </InfoItem>
- <InfoItem :title="$t('common.Default')">
- {{ getColumnDefaultValuePlaceholder(columnMetadata) }}
- </InfoItem>
- <InfoItem :title="$t('database.nullable')">
- <div class="inline-flex items-center justify-end">
- <CheckIcon v-if="columnMetadata.nullable" class="w-4 h-4" />
- <XIcon v-else class="w-4 h-4" />
- </div>
- </InfoItem>
- <InfoItem v-if="characterSet" :title="$t('db.character-set')">
- {{ characterSet }}
- </InfoItem>
- <InfoItem v-if="collation" :title="$t('db.collation')">
- {{ collation }}
- </InfoItem>
- <InfoItem v-if="columnMetadata.comment" :title="$t('database.comment')">
- {{ columnMetadata.comment }}
- </InfoItem>
- </div>
-</template>
-
-<script setup lang="ts">
-import { create } from "@bufbuild/protobuf";
-import { CheckIcon, XIcon } from "lucide-vue-next";
-import { computed } from "vue";
-import { getColumnDefaultValuePlaceholder } from "@/components/SchemaEditorLite";
-import { useDatabaseV1Store, useDBSchemaV1Store } from "@/store";
-import { Engine } from "@/types/proto-es/v1/common_pb";
-import { ColumnMetadataSchema } from "@/types/proto-es/v1/database_service_pb";
-import { getInstanceResource } from "@/utils";
-import InfoItem from "./InfoItem.vue";
-
-const props = defineProps<{
- database: string;
- schema?: string;
- table: string;
- column: string;
-}>();
-
-const dbSchema = useDBSchemaV1Store();
-const databaseStore = useDatabaseV1Store();
-
-const columnMetadata = computed(
- () =>
- dbSchema
- .getTableMetadata({
- database: props.database,
- schema: props.schema,
- table: props.table,
- })
- .columns.find((col) => col.name === props.column) ??
- create(ColumnMetadataSchema, {})
-);
-
-const instanceEngine = computed(
- () =>
- getInstanceResource(databaseStore.getDatabaseByName(props.database)).engine
-);
-
-const characterSet = computed(() => {
- if (
- [Engine.POSTGRES, Engine.CLICKHOUSE, Engine.SNOWFLAKE].includes(
- instanceEngine.value
- )
- ) {
- return columnMetadata.value.characterSet;
- }
- return "";
-});
-
-const collation = computed(() => {
- if ([Engine.CLICKHOUSE, Engine.SNOWFLAKE].includes(instanceEngine.value)) {
- return columnMetadata.value.collation;
- }
- return "";
-});
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/CommonText.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/CommonText.vue
deleted file mode 100644
index f3e1c92921..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/CommonText.vue
+++ /dev/null
@@ -1,11 +0,0 @@
-<template>
- <div class="max-w-[18rem] whitespace-pre-wrap break-all wrap-break-word">
- {{ content }}
- </div>
-</template>
-
-<script setup lang="ts">
-defineProps<{
- content: string;
-}>();
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/ExternalTableInfo.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/ExternalTableInfo.vue
deleted file mode 100644
index 0aa5549a71..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/ExternalTableInfo.vue
+++ /dev/null
@@ -1,35 +0,0 @@
-<template>
- <div class="min-w-56 max-w-[18rem] gap-y-1">
- <InfoItem :title="$t('common.name')">
- {{ externalTableMetadata.name }}
- </InfoItem>
- <InfoItem :title="$t('database.external-server-name')">
- {{ externalTableMetadata.externalServerName }}
- </InfoItem>
- <InfoItem :title="$t('database.external-database-name')">
- {{ externalTableMetadata.externalDatabaseName }}
- </InfoItem>
- </div>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { useDBSchemaV1Store } from "@/store";
-import InfoItem from "./InfoItem.vue";
-
-const props = defineProps<{
- database: string;
- schema?: string;
- externalTable: string;
-}>();
-
-const dbSchema = useDBSchemaV1Store();
-
-const externalTableMetadata = computed(() =>
- dbSchema.getExternalTableMetadata({
- database: props.database,
- schema: props.schema,
- externalTable: props.externalTable,
- })
-);
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/HoverPanel.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/HoverPanel.vue
deleted file mode 100644
index 24d0f4c851..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/HoverPanel.vue
+++ /dev/null
@@ -1,109 +0,0 @@
-<template>
- <div
- ref="popoverRef"
- v-zindexable="{ enabled: true }"
- class="fixed border border-gray-100 rounded-sm bg-white p-2 shadow-sm transition-[top] text-sm"
- :class="[show ? 'visible' : ' invisible pointer-events-none']"
- :style="{
- left: `${displayPosition.x}px`,
- top: `${displayPosition.y}px`,
- }"
- >
- <template v-if="state">
- <ColumnInfo
- v-if="state.column && state.table"
- :database="state.database"
- :schema="state.schema"
- :table="state.table"
- :column="state.column"
- />
- <TablePartitionInfo
- v-else-if="state.table && state.partition"
- :database="state.database"
- :schema="state.schema"
- :table="state.table"
- :partition="state.partition"
- />
- <TableInfo
- v-else-if="state.table"
- :database="state.database"
- :schema="state.schema"
- :table="state.table"
- />
- <ExternalTableInfo
- v-else-if="state.externalTable"
- :database="state.database"
- :schema="state.schema"
- :external-table="state.externalTable"
- />
- <ViewInfo
- v-else-if="state.view"
- :database="state.database"
- :schema="state.schema"
- :view="state.view"
- />
- </template>
- </div>
-</template>
-
-<script setup lang="ts">
-import { onClickOutside, useElementSize, useEventListener } from "@vueuse/core";
-import { zindexable as vZindexable } from "vdirs";
-import { computed, ref } from "vue";
-import type { Position } from "@/types";
-import { minmax } from "@/utils";
-import ColumnInfo from "./ColumnInfo.vue";
-import ExternalTableInfo from "./ExternalTableInfo.vue";
-import { useHoverStateContext } from "./hover-state";
-import TableInfo from "./TableInfo.vue";
-import TablePartitionInfo from "./TablePartitionInfo.vue";
-import ViewInfo from "./ViewInfo.vue";
-
-const props = defineProps<{
- offsetX: number;
- offsetY: number;
- margin: number;
-}>();
-
-const emit = defineEmits<{
- (event: "click-outside", e: MouseEvent): void;
-}>();
-
-const { state, position, update } = useHoverStateContext();
-
-const popoverRef = ref<HTMLDivElement>();
-onClickOutside(popoverRef, (e) => {
- emit("click-outside", e);
-});
-const { height: popoverHeight } = useElementSize(popoverRef, undefined, {
- box: "border-box",
-});
-
-const show = computed(() => {
- const show =
- state.value !== undefined &&
- position.value.x !== 0 &&
- position.value.y !== 0;
- return show;
-});
-
-const displayPosition = computed(() => {
- const p: Position = {
- x: position.value.x + props.offsetX,
- y: position.value.y + props.offsetY,
- };
- const yMin = props.margin;
- const yMax = window.innerHeight - popoverHeight.value - props.margin;
- p.y = minmax(p.y, yMin, yMax);
-
- return p;
-});
-
-useEventListener(popoverRef, "mouseenter", () => {
- // Keep the hover panel visible with a small delay to prevent flicker
- update(state.value, "before", 50);
-});
-useEventListener(popoverRef, "mouseleave", () => {
- update(undefined, "after");
-});
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/InfoItem.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/InfoItem.vue
deleted file mode 100644
index 9491b7b796..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/InfoItem.vue
+++ /dev/null
@@ -1,23 +0,0 @@
-<template>
- <div
- class="w-full grid grid-cols-2 gap-x-4 items-center"
- style="grid-template-columns: auto 1fr"
- >
- <div class="text-gray-500 font-medium whitespace-nowrap">
- <slot name="title">{{ title }}</slot>
- </div>
- <NPerformantEllipsis class="text-right flex! items-center justify-end">
- <span class="whitespace-nowrap flex items-center leading-[20px] h-[20px]">
- <slot name="default"></slot>
- </span>
- </NPerformantEllipsis>
- </div>
-</template>
-
-<script setup lang="ts">
-import { NPerformantEllipsis } from "naive-ui";
-
-defineProps<{
- title?: string;
-}>();
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/TableInfo.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/TableInfo.vue
deleted file mode 100644
index d72b4e47b7..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/TableInfo.vue
+++ /dev/null
@@ -1,78 +0,0 @@
-<template>
- <div class="min-w-56 max-w-[18rem] gap-y-1">
- <InfoItem :title="$t('common.name')">
- {{ tableMetadata.name }}
- </InfoItem>
- <InfoItem :title="$t('database.engine')">
- <RichEngineName :engine="instanceEngine" />
- </InfoItem>
- <InfoItem :title="$t('database.row-count-estimate')">
- {{ tableMetadata.rowCount }}
- </InfoItem>
- <InfoItem :title="$t('database.data-size')">
- {{ bytesToString(Number(tableMetadata.dataSize)) }}
- </InfoItem>
- <InfoItem v-if="indexSize" :title="$t('database.index-size')">
- {{ indexSize }}
- </InfoItem>
- <InfoItem v-if="collation" :title="$t('db.collation')">
- {{ collation }}
- </InfoItem>
- <InfoItem v-if="comment" :title="$t('database.comment')">
- {{ comment }}
- </InfoItem>
- </div>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { RichEngineName } from "@/components/v2";
-import { useDatabaseV1Store, useDBSchemaV1Store } from "@/store";
-import { Engine } from "@/types/proto-es/v1/common_pb";
-import { bytesToString, getInstanceResource } from "@/utils";
-import InfoItem from "./InfoItem.vue";
-
-const props = defineProps<{
- database: string;
- schema?: string;
- table: string;
-}>();
-
-const dbSchema = useDBSchemaV1Store();
-const databaseStore = useDatabaseV1Store();
-
-const instanceEngine = computed(
- () =>
- getInstanceResource(databaseStore.getDatabaseByName(props.database)).engine
-);
-
-const tableMetadata = computed(() =>
- dbSchema.getTableMetadata({
- database: props.database,
- schema: props.schema,
- table: props.table,
- })
-);
-
-const indexSize = computed(() => {
- if ([Engine.CLICKHOUSE, Engine.SNOWFLAKE].includes(instanceEngine.value)) {
- return "";
- }
- return bytesToString(Number(tableMetadata.value.indexSize));
-});
-
-const collation = computed(() => {
- if (
- [Engine.CLICKHOUSE, Engine.SNOWFLAKE, Engine.POSTGRES].includes(
- instanceEngine.value
- )
- ) {
- return "";
- }
- return tableMetadata.value.collation;
-});
-
-const comment = computed(() => {
- return tableMetadata.value.comment;
-});
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/TablePartitionInfo.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/TablePartitionInfo.vue
deleted file mode 100644
index 0015e5ece6..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/TablePartitionInfo.vue
+++ /dev/null
@@ -1,48 +0,0 @@
-<template>
- <div class="min-w-56 max-w-[18rem] gap-y-1">
- <InfoItem :title="$t('common.name')">
- {{ partitionMetadata.name }}
- </InfoItem>
- <InfoItem :title="$t('schema-editor.table-partition.type')">
- {{ TablePartitionMetadata_Type[partitionMetadata.type] }}
- </InfoItem>
- <InfoItem :title="$t('schema-editor.table-partition.expression')">
- <code>{{ partitionMetadata.expression }}</code>
- </InfoItem>
- <InfoItem :title="$t('schema-editor.table-partition.value')">
- {{ partitionMetadata.value }}
- </InfoItem>
- </div>
-</template>
-
-<script setup lang="ts">
-import { create } from "@bufbuild/protobuf";
-import { computed } from "vue";
-import { useDBSchemaV1Store } from "@/store";
-import {
- TablePartitionMetadata_Type,
- TablePartitionMetadataSchema,
-} from "@/types/proto-es/v1/database_service_pb";
-import InfoItem from "./InfoItem.vue";
-
-const props = defineProps<{
- database: string;
- schema?: string;
- table: string;
- partition: string;
-}>();
-
-const dbSchema = useDBSchemaV1Store();
-
-const partitionMetadata = computed(
- () =>
- dbSchema
- .getTableMetadata({
- database: props.database,
- schema: props.schema,
- table: props.table,
- })
- .partitions.find((p) => p.name === props.partition) ??
- create(TablePartitionMetadataSchema, {})
-);
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/ViewInfo.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/ViewInfo.vue
deleted file mode 100644
index 2510a424dc..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/ViewInfo.vue
+++ /dev/null
@@ -1,25 +0,0 @@
-<template>
- <CommonText :content="viewMetadata.comment" />
-</template>
-
-<script setup lang="tsx">
-import { computed } from "vue";
-import { useDBSchemaV1Store } from "@/store";
-import CommonText from "./CommonText.vue";
-
-const props = defineProps<{
- database: string;
- schema?: string;
- view: string;
-}>();
-
-const dbSchema = useDBSchemaV1Store();
-
-const viewMetadata = computed(() =>
- dbSchema.getViewMetadata({
- database: props.database,
- schema: props.schema,
- view: props.view,
- })
-);
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/hover-state.ts b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/hover-state.ts
deleted file mode 100644
index c74eeb6582..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/hover-state.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import {
- provideHoverStateContext as _provideHoverStateContext,
- useHoverStateContext as _useHoverStateContext,
-} from "../../../EditorCommon";
-
-export const KEY = "schema-pane";
-
-export type HoverState = {
- database: string;
- schema?: string;
- table?: string;
- externalTable?: string;
- view?: string;
- column?: string;
- partition?: string;
-};
-
-export const useHoverStateContext = () => {
- return _useHoverStateContext<HoverState>(KEY);
-};
-
-export const provideHoverStateContext = () => {
- return _provideHoverStateContext<HoverState>(KEY);
-};
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/index.ts b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/index.ts
deleted file mode 100644
index 05d40406b8..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/HoverPanel/index.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import HoverPanel from "./HoverPanel.vue";
-
-export * from "./hover-state";
-
-export { HoverPanel };
-export default HoverPanel;
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/SchemaPane.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/SchemaPane.vue
deleted file mode 100644
index a780a7b68f..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/SchemaPane.vue
+++ /dev/null
@@ -1,598 +0,0 @@
-<template>
- <div
- class="gap-y-1 h-full flex flex-col items-stretch relative overflow-hidden"
- >
- <div class="px-1 flex flex-row gap-1">
- <div class="flex-1 overflow-hidden">
- <SearchBox
- ref="searchBoxRef"
- v-model:value="searchPattern"
- :disabled="!currentTab"
- size="small"
- style="width: 100%; max-width: 100%"
- />
- </div>
- <div class="shrink-0 flex items-center">
- <SyncSchemaButton size="small" />
- </div>
- </div>
-
- <div
- ref="treeContainerElRef"
- class="schema-tree flex-1 px-1 pb-1 text-sm overflow-hidden select-none"
- :data-height="treeContainerHeight"
- >
- <MaskSpinner v-if="isFetchingMetadata" />
-
- <!-- Adaptive UI: Use tree for small DBs, flat list for large DBs -->
- <template v-else-if="metadata">
- <!-- For large databases (>1000 tables): Use flat list -->
- <FlatTableList
- v-if="totalTableCount > 1000"
- :metadata="metadata"
- :search="searchPattern"
- :database="database.name"
- @select="handleFlatListSelect"
- @select-all="handleFlatListSelectAll"
- @contextmenu="handleFlatListContextMenu"
- />
-
- <!-- For small databases: Use tree view -->
- <NTree
- v-else-if="tree"
- ref="treeRef"
- v-model:expanded-keys="expandedKeys"
- :selected-keys="selectedKeys"
- :block-line="true"
- :data="tree"
- :show-irrelevant-nodes="false"
- :pattern="mounted ? debouncedSearchPattern : ''"
- :virtual-scroll="true"
- :node-props="nodeProps"
- :theme-overrides="{ nodeHeight: '21px' }"
- :render-label="renderLabel"
- />
- <NEmpty v-else class="mt-16" />
- </template>
- <NEmpty v-else class="mt-16" />
- </div>
-
- <NDropdown
- v-if="!isFetchingMetadata"
- placement="bottom-start"
- trigger="manual"
- :x="dropdownPosition.x"
- :y="dropdownPosition.y"
- :options="dropdownOptions"
- :show="showDropdown"
- :on-clickoutside="handleDropdownClickoutside"
- @select="handleDropdownSelect"
- />
-
- <MaskSpinner v-if="isFetchingMetadata" class="bg-white/75!" />
-
- <BBModal :show="!!schemaViewer" @close="schemaViewer = undefined">
- <template v-if="schemaViewer" #title>
- <RichDatabaseName :database="database" />
- </template>
- <TableSchemaViewer
- v-if="schemaViewer"
- style="width: calc(100vw - 12rem); height: calc(100vh - 12rem)"
- v-bind="schemaViewer"
- :database="database"
- />
- </BBModal>
-
- <HoverPanel :offset-x="8" :offset-y="0" :margin="4" />
- </div>
-</template>
-
-<script setup lang="ts">
-import {
- computedAsync,
- refDebounced,
- useElementSize,
- useEventListener,
- useMounted,
-} from "@vueuse/core";
-import { head, uniq, without } from "lodash-es";
-import {
- NDropdown,
- NEmpty,
- NTree,
- type TreeInst,
- type TreeOption,
-} from "naive-ui";
-import { storeToRefs } from "pinia";
-import { computed, h, nextTick, ref, watch, watchEffect } from "vue";
-import { BBModal } from "@/bbkit";
-import MaskSpinner from "@/components/misc/MaskSpinner.vue";
-import TableSchemaViewer from "@/components/TableSchemaViewer.vue";
-import { RichDatabaseName, SearchBox } from "@/components/v2";
-import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDBSchemaV1Store,
- useSQLEditorTabStore,
-} from "@/store";
-import { isValidDatabaseName } from "@/types";
-import type { TableMetadata } from "@/types/proto-es/v1/database_service_pb";
-import {
- allEqual,
- extractDatabaseResourceName,
- findAncestor,
- isDescendantOf,
-} from "@/utils";
-import { useSQLEditorContext } from "../../context";
-import { useCurrentTabViewStateContext } from "../../EditorPanel";
-import { useActions, useDropdown } from "./actions";
-import { useClickEvents } from "./click";
-import FlatTableList from "./FlatTableList.vue";
-import HoverPanel, { provideHoverStateContext } from "./HoverPanel";
-import SyncSchemaButton from "./SyncSchemaButton.vue";
-import { Label } from "./TreeNode";
-import {
- buildDatabaseSchemaTree,
- ExpandableNodeTypes,
- type NodeTarget,
- type TreeNode,
-} from "./tree";
-
-const mounted = useMounted();
-const searchBoxRef = ref<InstanceType<typeof SearchBox>>();
-const treeRef = ref<TreeInst>();
-const treeContainerElRef = ref<HTMLElement>();
-const { height: treeContainerHeight } = useElementSize(
- treeContainerElRef,
- undefined,
- {
- box: "content-box",
- }
-);
-
-const { viewState: panelViewState } = useCurrentTabViewStateContext();
-const { schemaViewer } = useSQLEditorContext();
-const {
- show: showDropdown,
- context: dropdownContext,
- position: dropdownPosition,
- options: dropdownOptions,
- handleSelect: handleDropdownSelect,
- handleClickoutside: handleDropdownClickoutside,
-} = useDropdown();
-const { selectAllFromTableOrView } = useActions();
-const { currentTab } = storeToRefs(useSQLEditorTabStore());
-const { database } = useConnectionOfCurrentSQLEditorTab();
-
-// Simple search pattern that resets when tab changes
-const searchPattern = ref("");
-const debouncedSearchPattern = refDebounced(searchPattern, 200);
-
-// Reset search when tab changes
-watch(
- () => currentTab.value?.id,
- () => {
- searchPattern.value = "";
- }
-);
-const isFetchingMetadata = ref(false);
-const totalTableCount = ref(0);
-const metadata = computedAsync(
- async () => {
- const db = database.value;
- if (!isValidDatabaseName(db.name)) return null;
- const metadata = await useDBSchemaV1Store().getOrFetchDatabaseMetadata({
- database: db.name,
- });
- totalTableCount.value = metadata.schemas.reduce(
- (sum, schema) => sum + (schema.tables?.length || 0),
- 0
- );
- return metadata;
- },
- /* default */ null,
- {
- evaluating: isFetchingMetadata,
- }
-);
-const { events: nodeClickEvents, handleClick: handleNodeClick } =
- useClickEvents();
-const {
- state: hoverState,
- position: hoverPosition,
- update: updateHoverState,
-} = provideHoverStateContext();
-const tree = ref<TreeNode[]>();
-
-const expandedKeys = computed({
- get() {
- const treeState = currentTab.value?.treeState;
- if (!treeState) return [];
- if (treeState.database !== database.value.name) return [];
- return treeState.keys;
- },
- set(keys) {
- if (!currentTab.value) return;
- const treeState = currentTab.value.treeState;
- if (treeState.database !== database.value.name) return;
- treeState.keys = keys;
- },
-});
-
-const upsertExpandedKeys = (keys: string[]) => {
- const curr = expandedKeys.value;
- if (!curr) return;
- expandedKeys.value = uniq([...curr, ...keys]);
-};
-const removeExpandedKeys = (keys: string[]) => {
- const curr = expandedKeys.value;
- if (!curr) return;
- expandedKeys.value = without(curr, ...keys);
-};
-
-const defaultExpandedKeys = () => {
- if (!tree.value) return [];
- const keys: string[] = [];
- const collect = (node: TreeNode) => {
- keys.push(node.key);
- node.children?.forEach((child) => walk(child as TreeNode));
- };
- const walk = (node: TreeNode) => {
- const { type } = node.meta;
- if (type === "database" || type === "schema") {
- collect(node);
- } else if (type === "expandable-text") {
- const { mockType } = node.meta.target as NodeTarget<"expandable-text">;
- if (mockType === "table" || mockType === "view") {
- collect(node);
- }
- }
- };
- walk(tree.value[0]);
- return keys;
-};
-const nodeProps = ({ option }: { option: TreeOption }) => {
- const node = option as TreeNode;
- return {
- onclick(e: MouseEvent) {
- if (node.disabled) return;
-
- if (isDescendantOf(e.target as Element, ".n-tree-node-content")) {
- handleNodeClick(node);
- }
- },
- oncontextmenu(e: MouseEvent) {
- e.preventDefault();
- showDropdown.value = false;
- if (node && node.key) {
- dropdownContext.value = node;
- }
-
- nextTick().then(() => {
- showDropdown.value = true;
- dropdownPosition.value.x = e.clientX;
- dropdownPosition.value.y = e.clientY;
- });
- },
-
- onmouseenter(e: MouseEvent) {
- const { type } = node.meta;
- if (
- type === "table" ||
- type === "external-table" ||
- type === "column" ||
- type === "view" ||
- type === "partition-table"
- ) {
- const target = node.meta.target as NodeTarget<
- "table" | "external-table" | "column" | "view"
- >;
- // Use a small delay even when transitioning between nodes
- // to prevent excessive re-renders when moving quickly
- const delay = hoverState.value ? 150 : undefined;
- updateHoverState(target, "before", delay);
-
- nextTick().then(() => {
- // Find the node element and put the database panel to the bottom
- // of the node, near the cursor
- const wrapper = findAncestor(e.target as HTMLElement, ".n-tree-node");
- if (!wrapper) {
- // Clear hover state if we can't find the wrapper
- updateHoverState(undefined, "after", 150);
- return;
- }
- const bounding = wrapper.getBoundingClientRect();
- hoverPosition.value.x = e.clientX;
- hoverPosition.value.y = bounding.bottom;
- });
- }
- },
- onmouseleave() {
- updateHoverState(undefined, "after");
- },
- // attrs below for trouble-shooting
- "data-node-meta-type": node.meta.type,
- "data-node-key": node.key,
- };
-};
-
-// dynamic render the highlight keywords
-const renderLabel = ({ option }: { option: TreeOption }) => {
- const node = option as TreeNode;
- const keyword = searchPattern.value;
- return h(Label, { node, keyword });
-};
-
-const selectedKeys = computed(() => {
- const db = database.value;
- if (!isValidDatabaseName(db.name)) return [];
- const keys: string[] = [];
- const tab = currentTab.value;
- if (tab && tab.connection.schema !== undefined) {
- keys.push(`${db.name}/schemas/${tab.connection.schema}`);
- }
- if (!panelViewState.value || panelViewState.value.view === "CODE") {
- return keys;
- }
- const {
- schema,
- detail: {
- table,
- column,
- view,
- procedure,
- func,
- sequence,
- trigger,
- externalTable,
- package: pack,
- partition,
- index,
- foreignKey,
- },
- } = panelViewState.value;
-
- const parts = [db.name, `schemas/${schema}`];
- if (table) {
- parts.push(`tables/${table}`);
- if (column) {
- parts.push(`columns/${column}`);
- } else if (index) {
- parts.push(`indexes/${index}`);
- } else if (partition) {
- parts.push(`partitionTables/${partition}`);
- } else if (trigger) {
- parts.push(`triggers/${trigger}`);
- } else if (foreignKey) {
- parts.push(`foreignKeys/${foreignKey}`);
- }
- } else if (view) {
- parts.push(`views/${view}`);
- if (column) {
- parts.push(`columns/${column}`);
- }
- } else if (procedure) {
- parts.push(`procedures/${procedure}`);
- } else if (func) {
- parts.push(`functions/${func}`);
- } else if (sequence) {
- parts.push(`sequences/${sequence}`);
- } else if (externalTable) {
- parts.push(`externalTables/${externalTable}`);
- } else if (pack) {
- parts.push(`packages/${pack}`);
- }
-
- return [parts.join("/")];
-});
-watchEffect(() => {
- const key = head(selectedKeys.value);
- if (key) {
- treeRef.value?.scrollTo({ key });
- }
-});
-
-// bottom-up recursively
-const expandNode = (node: TreeNode) => {
- const keysToExpand: string[] = [];
- if (ExpandableNodeTypes.includes(node.meta.type)) {
- keysToExpand.push(node.key);
- }
- upsertExpandedKeys(keysToExpand);
-};
-const collapseNode = (node: TreeNode) => {
- removeExpandedKeys([node.key]);
-};
-const toggleNode = (node: TreeNode) => {
- if (expandedKeys.value.includes(node.key)) {
- collapseNode(node);
- } else {
- expandNode(node);
- }
-};
-
-const singleClick = (node: TreeNode) => {
- toggleNode(node);
- if (node.meta.type === "schema") {
- const tab = currentTab.value;
- if (tab) {
- tab.connection.schema = (node.meta.target as NodeTarget<"schema">).schema;
- return;
- }
- }
-};
-useEmitteryEventListener(nodeClickEvents, "single-click", ({ node }) => {
- singleClick(node);
-});
-useEmitteryEventListener(nodeClickEvents, "double-click", ({ node }) => {
- if (node.meta.type === "table" || node.meta.type === "view") {
- selectAllFromTableOrView(node);
- } else if (
- node.meta.type === "expandable-text" ||
- node.meta.type === "schema"
- ) {
- toggleNode(node);
- } else {
- singleClick(node);
- }
-});
-
-// Watch only the properties we actually need, not the entire tab object
-// This prevents re-renders on every keystroke in the editor
-watch(
- [
- isFetchingMetadata,
- metadata,
- () => currentTab.value?.id,
- () => currentTab.value?.connection.database,
- () => currentTab.value?.treeState.database,
- ],
- ([isFetchingMetadata, metadata, _, connectionDb, treeStateDb]) => {
- const cleanup = () => {
- tree.value = undefined;
- };
-
- const tab = currentTab.value;
- if (isFetchingMetadata || !metadata || !tab) {
- return cleanup();
- }
- if (
- !allEqual(
- extractDatabaseResourceName(metadata.name).database,
- connectionDb,
- database.value.name
- )
- ) {
- return cleanup();
- }
-
- if (totalTableCount.value <= 1000) {
- requestAnimationFrame(() => {
- tree.value = buildDatabaseSchemaTree(database.value, metadata);
- if (treeStateDb !== connectionDb && connectionDb) {
- // Set initial tree state for the tab when it firstly opens or its
- // connection has been changed
- tab.treeState.database = connectionDb;
- tab.treeState.keys = defaultExpandedKeys();
- }
- });
- }
- },
- {
- immediate: true,
- }
-);
-
-// Handlers for flat list events
-const handleFlatListSelect = (table: { schema?: string }) => {
- // Update connection schema if needed
- const tab = currentTab.value;
- if (tab && table.schema) {
- tab.connection.schema = table.schema;
- }
-};
-
-const handleFlatListSelectAll = (table: {
- key: string;
- schema: string;
- metadata: TableMetadata;
-}) => {
- // Execute SELECT * for the table
- if (table.metadata) {
- selectAllFromTableOrView({
- key: table.key,
- meta: {
- type: "table",
- target: {
- database: database.value.name,
- schema: table.schema,
- table: table.metadata.name,
- },
- },
- });
- }
-};
-
-const handleFlatListContextMenu = (
- event: MouseEvent,
- table: {
- key: string;
- schema: string;
- metadata: TableMetadata;
- }
-) => {
- dropdownContext.value = {
- key: table.key,
- meta: {
- type: "table",
- target: {
- database: database.value.name,
- schema: table.schema,
- table: table.metadata.name,
- },
- },
- };
-
- nextTick().then(() => {
- showDropdown.value = true;
- dropdownPosition.value.x = event.clientX;
- dropdownPosition.value.y = event.clientY;
- });
-};
-
-useEventListener(treeContainerElRef, "keydown", () => {
- searchBoxRef.value?.inputRef?.focus();
-});
-</script>
-
-<style lang="postcss" scoped>
-.schema-tree :deep(.n-tree .v-vl) {
- --n-node-content-height: 21px !important;
-}
-.schema-tree :deep(.n-tree-node-content) {
- padding-left: 0 !important;
- padding-right: 0 !important;
- font-size: 0.875rem;
- line-height: 1.25rem;
-}
-.schema-tree :deep(.n-tree-node-wrapper) {
- padding: 0;
-}
-.schema-tree :deep(.n-tree-node-indent) {
- width: 10px;
- height: 10px;
-}
-.schema-tree :deep(.n-tree-node-switcher) {
- width: 20px !important;
- height: 20px !important;
- align-self: center;
-}
-.schema-tree :deep(.n-tree-node-switcher--hide) {
- width: 0 !important;
-}
-.schema-tree :deep(.n-tree-node-content__prefix) {
- flex-shrink: 0;
- margin-right: 0.25rem !important;
-}
-.schema-tree.project
- :deep(.n-tree-node[data-node-type="project"] .n-tree-node-content__prefix) {
- display: none;
-}
-.schema-tree :deep(.n-tree-node-content__text) {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- margin-right: 0.25rem;
-}
-.schema-tree :deep(.n-tree-node--pending) {
- background-color: transparent !important;
-}
-.schema-tree :deep(.n-tree-node--pending:hover) {
- background-color: var(--n-node-color-hover) !important;
-}
-.schema-tree :deep(.n-tree-node--selected),
-.schema-tree :deep(.n-tree-node--selected:hover) {
- background-color: var(--n-node-color-active) !important;
- font-weight: 500;
-}
-</style>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/SyncSchemaButton.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/SyncSchemaButton.vue
deleted file mode 100644
index efdac3b37c..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/SyncSchemaButton.vue
+++ /dev/null
@@ -1,77 +0,0 @@
-<template>
- <NPopover :disabled="disabled" placement="bottom-start">
- <template #trigger>
- <NButton
- style="--n-padding: 0 5px"
- :disabled="disabled || isSyncing"
- v-bind="$attrs"
- @click="syncNow"
- >
- <template #icon>
- <RefreshCcwIcon
- class="w-4 h-4"
- :class="[isSyncing && 'animate-[spin_2s_linear_infinite]']"
- />
- </template>
- </NButton>
- </template>
- <template #default>
- <div class="flex flex-col gap-1">
- <i18n-t tag="div" keypath="sql-editor.last-synced">
- <template #time>
- <HumanizeDate
- :date="getDateForPbTimestampProtoEs(database.successfulSyncTime)"
- />
- </template>
- </i18n-t>
- <div v-if="!isSyncing">{{ $t("sql-editor.click-to-sync-now") }}</div>
- <div v-if="isSyncing">{{ $t("sql-editor.sync-in-progress") }}</div>
- </div>
- </template>
- </NPopover>
-</template>
-
-<script setup lang="ts">
-import { RefreshCcwIcon } from "lucide-vue-next";
-import { NButton, NPopover } from "naive-ui";
-import { computed, ref } from "vue";
-import HumanizeDate from "@/components/misc/HumanizeDate.vue";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDatabaseV1Store,
- useDBSchemaV1Store,
-} from "@/store";
-import { getDateForPbTimestampProtoEs, isValidDatabaseName } from "@/types";
-
-defineOptions({
- inheritAttrs: false,
-});
-
-const { database } = useConnectionOfCurrentSQLEditorTab();
-
-const disabled = computed(() => {
- return !isValidDatabaseName(database.value.name);
-});
-
-const isSyncing = ref(false);
-
-const syncNow = async () => {
- if (disabled.value) {
- return;
- }
- try {
- isSyncing.value = true;
- await useDatabaseV1Store().syncDatabase(
- database.value.name,
- /* refresh */ true
- );
-
- await useDBSchemaV1Store().getOrFetchDatabaseMetadata({
- database: database.value.name,
- skipCache: true,
- });
- } finally {
- isSyncing.value = false;
- }
-};
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/CheckNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/CheckNode.vue
deleted file mode 100644
index 05d42ad520..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/CheckNode.vue
+++ /dev/null
@@ -1,59 +0,0 @@
-<template>
- <CommonNode
- :text="target.check"
- :keyword="keyword"
- :highlight="true"
- :indent="0"
- >
- <template #icon>
- <CheckIcon class="w-3.5! h-3.5! text-gray-500" />
- </template>
- <template #suffix>
- <div
- class="flex items-center justify-end gap-1 overflow-hidden whitespace-nowrap shrink opacity-80 font-normal!"
- >
- <NTag
- size="small"
- class="text-size-adjust-none"
- style="--n-height: 16px; --n-padding: 0 3px; --n-font-size: 10px"
- >
- {{ checkMetadata?.expression }}
- </NTag>
- </div>
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { NTag } from "naive-ui";
-import { computed } from "vue";
-import { CheckIcon } from "@/components/Icon";
-import { useDBSchemaV1Store } from "@/store";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const dbSchema = useDBSchemaV1Store();
-const target = computed(() => (props.node as TreeNode<"check">).meta.target);
-
-const tableMetadata = computed(() => {
- if ("table" in target.value) {
- const { database, schema, table } = target.value;
- return dbSchema.getTableMetadata({ database, schema, table });
- }
- return undefined;
-});
-
-const checkMetadata = computed(() => {
- const { check } = target.value;
-
- if ("table" in target.value) {
- return tableMetadata.value?.checkConstraints.find((c) => c.name === check);
- }
- return undefined;
-});
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ColumnNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ColumnNode.vue
deleted file mode 100644
index a452eead6b..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ColumnNode.vue
+++ /dev/null
@@ -1,96 +0,0 @@
-<template>
- <CommonNode
- :text="target.column"
- :keyword="keyword"
- :highlight="true"
- :indent="0"
- >
- <template #icon>
- <PrimaryKeyIcon v-if="isPrimaryKey" class="w-4 h-4" />
- <IndexIcon v-else-if="isIndex" class="w-4! h-4! text-accent/80" />
- <ColumnIcon v-else class="w-4 h-4" />
- </template>
- <template #suffix>
- <div
- class="flex items-center justify-end gap-1 overflow-hidden whitespace-nowrap shrink opacity-80 font-normal!"
- >
- <NTag
- size="small"
- class="text-size-adjust-none"
- style="--n-height: 16px; --n-padding: 0 3px; --n-font-size: 10px"
- >
- {{ columnMetadata?.type }}
- </NTag>
- </div>
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { NTag } from "naive-ui";
-import { computed } from "vue";
-import { ColumnIcon, IndexIcon, PrimaryKeyIcon } from "@/components/Icon";
-import { useDBSchemaV1Store } from "@/store";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const dbSchema = useDBSchemaV1Store();
-const target = computed(() => (props.node as TreeNode<"column">).meta.target);
-
-const tableMetadata = computed(() => {
- if ("table" in target.value) {
- const { database, schema, table } = target.value;
- return dbSchema.getTableMetadata({ database, schema, table });
- }
- return undefined;
-});
-
-const columnMetadata = computed(() => {
- const { database, schema, column } = target.value;
- const schemaMetadata = dbSchema.getSchemaMetadata({ database, schema });
-
- if ("table" in target.value) {
- return tableMetadata.value?.columns.find((c) => c.name === column);
- } else if ("externalTable" in target.value) {
- const { externalTable } = target.value;
- return schemaMetadata?.externalTables
- .find((t) => t.name === externalTable)
- ?.columns.find((c) => c.name === column);
- } else if ("view" in target.value) {
- const { view } = target.value;
- return schemaMetadata?.views
- .find((v) => v.name === view)
- ?.columns.find((c) => c.name === column);
- }
- return undefined;
-});
-
-const isPrimaryKey = computed(() => {
- if ("table" in target.value) {
- const { column } = target.value;
- const pk = tableMetadata.value?.indexes.find((idx) => idx.primary);
- if (!pk) return false;
- return pk.expressions.includes(column);
- }
-
- return false;
-});
-
-const isIndex = computed(() => {
- if (isPrimaryKey.value) return false;
-
- if ("table" in target.value) {
- const { column } = target.value;
- return tableMetadata.value?.indexes.some((idx) =>
- idx.expressions.includes(column)
- );
- }
-
- return false;
-});
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/CommonNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/CommonNode.vue
deleted file mode 100644
index 468a7b04f7..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/CommonNode.vue
+++ /dev/null
@@ -1,41 +0,0 @@
-<template>
- <div class="flex items-center max-w-full overflow-hidden" v-bind="$attrs">
- <slot name="default">
- <span
- v-for="i in indent"
- :key="`indent-#${i}`"
- class="inline-block w-[20px] h-[20px] shrink-0 invisible"
- :data-indent="i"
- />
- <span
- v-if="!hideIcon"
- class="flex items-center justify-center shrink-0 w-[20px] h-[20px]"
- >
- <slot name="icon" />
- </span>
- <slot v-if="text" name="text">
- <HighlightLabelText
- v-if="highlight"
- :text="text"
- :keyword="keyword ?? ''"
- class="flex-1 truncate pl-[2px] min-w-16"
- />
- <span v-else class="pl-[2px]">{{ text }}</span>
- </slot>
- <slot v-else name="fallback-text" />
- <slot name="suffix" />
- </slot>
- </div>
-</template>
-
-<script setup lang="ts">
-import { HighlightLabelText } from "@/components/v2";
-
-defineProps<{
- text: string;
- indent?: number;
- keyword?: string;
- highlight?: boolean;
- hideIcon?: boolean;
-}>();
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/DatabaseNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/DatabaseNode.vue
deleted file mode 100644
index b9e9a8ca67..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/DatabaseNode.vue
+++ /dev/null
@@ -1,39 +0,0 @@
-<template>
- <CommonNode
- :text="databaseName"
- :keyword="keyword"
- :highlight="true"
- >
- <template #icon>
- <InstanceV1EngineIcon :instance="instanceResource" />
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { InstanceV1EngineIcon } from "@/components/v2";
-import { useDatabaseV1Store } from "@/store";
-import { extractDatabaseResourceName, getInstanceResource } from "@/utils";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const databaseStore = useDatabaseV1Store();
-
-const database = computed(() =>
- databaseStore.getDatabaseByName(
- (props.node as TreeNode<"database">).meta.target.database
- )
-);
-
-const databaseName = computed(
- () => extractDatabaseResourceName(database.value.name).databaseName
-);
-
-const instanceResource = computed(() => getInstanceResource(database.value));
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/DependencyColumnNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/DependencyColumnNode.vue
deleted file mode 100644
index 9cef4dbacd..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/DependencyColumnNode.vue
+++ /dev/null
@@ -1,30 +0,0 @@
-<template>
- <CommonNode :text="text" :keyword="keyword" :highlight="true" :indent="0">
- <template #icon>
- <ColumnIcon class="w-4 h-4" />
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { ColumnIcon } from "@/components/Icon";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const target = computed(
- () => (props.node as TreeNode<"dependency-column">).meta.target
-);
-
-const text = computed(() => {
- const { schema, table, column } = target.value.dependencyColumn;
- const parts = [table, column];
- if (schema) parts.unshift(schema);
- return parts.join(".");
-});
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/DummyNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/DummyNode.vue
deleted file mode 100644
index b7121ecfc9..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/DummyNode.vue
+++ /dev/null
@@ -1,34 +0,0 @@
-<template>
- <NPopover :disabled="!error">
- <template #trigger>
- <span class="text-control-placeholder ml-[2px]">{{ text }}</span>
- </template>
- <template #default>
- <div class="text-error max-w-[20rem] wrap-break-word break-all">
- {{ error }}
- </div>
- </template>
- </NPopover>
-</template>
-
-<script setup lang="ts">
-import { NPopover } from "naive-ui";
-import { computed } from "vue";
-import { useI18n } from "vue-i18n";
-import type { TreeNode } from "../tree";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const { t } = useI18n();
-
-const error = computed(() => {
- return (props.node as TreeNode<"error">).meta.target.error;
-});
-
-const text = computed(() => {
- return `<${error.value ? t("common.error") : t("common.empty")}>`;
-});
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ExternalTableNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ExternalTableNode.vue
deleted file mode 100644
index b2941b320b..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ExternalTableNode.vue
+++ /dev/null
@@ -1,23 +0,0 @@
-<template>
- <CommonNode :text="target.externalTable" :keyword="keyword" :highlight="true">
- <template #icon>
- <ExternalTableIcon class="w-4 h-4" />
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { ExternalTableIcon } from "@/components/Icon";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const target = computed(
- () => (props.node as TreeNode<"external-table">).meta.target
-);
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ForeignKeyNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ForeignKeyNode.vue
deleted file mode 100644
index b51c332abd..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ForeignKeyNode.vue
+++ /dev/null
@@ -1,28 +0,0 @@
-<template>
- <CommonNode
- :text="target.foreignKey"
- :keyword="keyword"
- :highlight="true"
- :indent="0"
- >
- <template #icon>
- <ForeignKeyIcon class="w-3.5! h-3.5! text-gray-500" />
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { ForeignKeyIcon } from "@/components/Icon";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const target = computed(
- () => (props.node as TreeNode<"foreign-key">).meta.target
-);
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/FunctionNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/FunctionNode.vue
deleted file mode 100644
index 210fc5dfcb..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/FunctionNode.vue
+++ /dev/null
@@ -1,37 +0,0 @@
-<template>
- <CommonNode
- :text="(functionMetadata?.signature || functionMetadata?.name) ?? ''"
- :keyword="keyword"
- :highlight="true"
- :indent="0"
- >
- <template #icon>
- <FunctionIcon class="w-4 h-4" />
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { FunctionIcon } from "@/components/Icon";
-import { useDBSchemaV1Store } from "@/store";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const dbSchema = useDBSchemaV1Store();
-
-const target = computed(() => (props.node as TreeNode<"function">).meta.target);
-
-const functionMetadata = computed(
- () =>
- dbSchema.getSchemaMetadata({
- database: target.value.database,
- schema: target.value.schema,
- })?.functions[target.value.position]
-);
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/IndexNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/IndexNode.vue
deleted file mode 100644
index 29003b588d..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/IndexNode.vue
+++ /dev/null
@@ -1,44 +0,0 @@
-<template>
- <CommonNode
- :text="target.index"
- :keyword="keyword"
- :highlight="true"
- :indent="0"
- >
- <template #icon>
- <PrimaryKeyIcon v-if="isPrimaryKey" class="w-4 h-4" />
- <IndexIcon v-else class="w-4! h-4! text-accent/80" />
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { IndexIcon, PrimaryKeyIcon } from "@/components/Icon";
-import { useDBSchemaV1Store } from "@/store";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const dbSchema = useDBSchemaV1Store();
-
-const target = computed(() => (props.node as TreeNode<"index">).meta.target);
-
-const indexMetadata = computed(() => {
- const { database, schema, table, index } = target.value;
- const tableMetadata = dbSchema.getTableMetadata({
- database,
- schema,
- table,
- });
- return tableMetadata.indexes.find((i) => i.name === index);
-});
-
-const isPrimaryKey = computed(() => {
- return indexMetadata.value?.primary;
-});
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/Label.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/Label.vue
deleted file mode 100644
index 9e7159240a..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/Label.vue
+++ /dev/null
@@ -1,86 +0,0 @@
-<template>
- <template v-if="type === 'database'">
- <DatabaseNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'schema'">
- <SchemaNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'table'">
- <TableNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'external-table'">
- <ExternalTableNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'column'">
- <ColumnNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'index'">
- <IndexNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'foreign-key'">
- <ForeignKeyNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'check'">
- <CheckNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'partition-table'">
- <PartitionTableNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'view'">
- <ViewNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'dependency-column'">
- <DependencyColumnNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'procedure'">
- <ProcedureNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'package'">
- <PackageNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'function'">
- <FunctionNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'sequence'">
- <SequenceNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'trigger'">
- <TriggerNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'expandable-text'">
- <TextNode :node="node" :keyword="keyword" />
- </template>
- <template v-if="type === 'error'">
- <DummyNode :node="node" :keyword="keyword" />
- </template>
-</template>
-
-<script lang="ts" setup>
-import { computed } from "vue";
-import type { TreeNode } from "../tree";
-import CheckNode from "./CheckNode.vue";
-import ColumnNode from "./ColumnNode.vue";
-import DatabaseNode from "./DatabaseNode.vue";
-import DependencyColumnNode from "./DependencyColumnNode.vue";
-import DummyNode from "./DummyNode.vue";
-import ExternalTableNode from "./ExternalTableNode.vue";
-import ForeignKeyNode from "./ForeignKeyNode.vue";
-import FunctionNode from "./FunctionNode.vue";
-import IndexNode from "./IndexNode.vue";
-import PackageNode from "./PackageNode.vue";
-import PartitionTableNode from "./PartitionTableNode.vue";
-import ProcedureNode from "./ProcedureNode.vue";
-import SchemaNode from "./SchemaNode.vue";
-import SequenceNode from "./SequenceNode.vue";
-import TableNode from "./TableNode.vue";
-import TextNode from "./TextNode.vue";
-import TriggerNode from "./TriggerNode.vue";
-import ViewNode from "./ViewNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const type = computed(() => props.node.meta.type);
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/PackageNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/PackageNode.vue
deleted file mode 100644
index 29c8f68931..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/PackageNode.vue
+++ /dev/null
@@ -1,26 +0,0 @@
-<template>
- <CommonNode
- :text="target.package"
- :keyword="keyword"
- :highlight="true"
- :indent="0"
- >
- <template #icon>
- <PackageIcon class="w-4 h-4" />
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { PackageIcon } from "@/components/Icon";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const target = computed(() => (props.node as TreeNode<"package">).meta.target);
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/PartitionTableNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/PartitionTableNode.vue
deleted file mode 100644
index 0f43591252..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/PartitionTableNode.vue
+++ /dev/null
@@ -1,28 +0,0 @@
-<template>
- <CommonNode
- :text="target.partition"
- :keyword="keyword"
- :highlight="true"
- :indent="0"
- >
- <template #icon>
- <TablePartitionIcon class="w-4 h-4" />
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { TablePartitionIcon } from "@/components/Icon";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const target = computed(
- () => (props.node as TreeNode<"partition-table">).meta.target
-);
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ProcedureNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ProcedureNode.vue
deleted file mode 100644
index f27d48d7b2..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ProcedureNode.vue
+++ /dev/null
@@ -1,39 +0,0 @@
-<template>
- <CommonNode
- :text="(procedureMetadata?.signature || procedureMetadata?.name) ?? ''"
- :keyword="keyword"
- :highlight="true"
- :indent="0"
- >
- <template #icon>
- <ProcedureIcon class="w-4 h-4" />
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { ProcedureIcon } from "@/components/Icon";
-import { useDBSchemaV1Store } from "@/store";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const dbSchema = useDBSchemaV1Store();
-
-const target = computed(
- () => (props.node as TreeNode<"procedure">).meta.target
-);
-
-const procedureMetadata = computed(
- () =>
- dbSchema.getSchemaMetadata({
- database: target.value.database,
- schema: target.value.schema,
- })?.procedures[target.value.position]
-);
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/SchemaNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/SchemaNode.vue
deleted file mode 100644
index 8c99daf1a1..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/SchemaNode.vue
+++ /dev/null
@@ -1,24 +0,0 @@
-<template>
- <CommonNode :text="target.schema" :keyword="keyword" :highlight="true">
- <template #icon>
- <SchemaIcon class="w-4 h-4" />
- </template>
- <template #fallback-text>
- {{ $t("db.schema.default") }}
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { SchemaIcon } from "@/components/Icon";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const target = computed(() => (props.node as TreeNode<"schema">).meta.target);
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/SequenceNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/SequenceNode.vue
deleted file mode 100644
index 813fba6ff9..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/SequenceNode.vue
+++ /dev/null
@@ -1,26 +0,0 @@
-<template>
- <CommonNode
- :text="target.sequence"
- :keyword="keyword"
- :highlight="true"
- :indent="0"
- >
- <template #icon>
- <SequenceIcon class="w-4 h-4 text-gray-500" />
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { SequenceIcon } from "@/components/Icon";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const target = computed(() => (props.node as TreeNode<"sequence">).meta.target);
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/TableNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/TableNode.vue
deleted file mode 100644
index 6a128e99f7..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/TableNode.vue
+++ /dev/null
@@ -1,21 +0,0 @@
-<template>
- <CommonNode :text="target.table" :keyword="keyword" :highlight="true">
- <template #icon>
- <TableIcon class="w-4 h-4" />
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { TableIcon } from "@/components/Icon";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const target = computed(() => (props.node as TreeNode<"table">).meta.target);
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/TextNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/TextNode.vue
deleted file mode 100644
index 63030d2f15..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/TextNode.vue
+++ /dev/null
@@ -1,40 +0,0 @@
-<template>
- <CommonNode :text="text" :highlight="false" :data-mock-type="type">
- <template v-if="render" #default>
- <component :is="render" />
- </template>
-
- <template #icon>
- <FolderIcon class="w-4 h-4 stroke-accent fill-accent/10" />
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { isFunction } from "lodash-es";
-import { FolderIcon } from "lucide-vue-next";
-import { computed } from "vue";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const target = computed(() => {
- return (props.node as TreeNode<"expandable-text">).meta.target;
-});
-
-const type = computed(() => {
- return target.value.mockType;
-});
-
-const text = computed(() => {
- const { text } = target.value;
- return isFunction(text) ? text() : text;
-});
-const render = computed(() => {
- return target.value.render;
-});
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/TriggerNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/TriggerNode.vue
deleted file mode 100644
index 10cc404bf2..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/TriggerNode.vue
+++ /dev/null
@@ -1,26 +0,0 @@
-<template>
- <CommonNode
- :text="target.trigger"
- :keyword="keyword"
- :highlight="true"
- :indent="0"
- >
- <template #icon>
- <TriggerIcon class="w-4 h-4 text-gray-500" />
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { TriggerIcon } from "@/components/Icon";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const target = computed(() => (props.node as TreeNode<"trigger">).meta.target);
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ViewNode.vue b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ViewNode.vue
deleted file mode 100644
index 53f7cb1921..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/ViewNode.vue
+++ /dev/null
@@ -1,26 +0,0 @@
-<template>
- <CommonNode
- :text="target.view"
- :keyword="keyword"
- :highlight="true"
- :indent="0"
- >
- <template #icon>
- <ViewIcon class="w-4 h-4" />
- </template>
- </CommonNode>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { ViewIcon } from "@/components/Icon";
-import type { TreeNode } from "../tree";
-import CommonNode from "./CommonNode.vue";
-
-const props = defineProps<{
- node: TreeNode;
- keyword: string;
-}>();
-
-const target = computed(() => (props.node as TreeNode<"view">).meta.target);
-</script>
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/index.ts b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/index.ts
deleted file mode 100644
index 448927e184..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/TreeNode/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import Label from "./Label.vue";
-
-export { Label };
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx
deleted file mode 100644
index 437eaf7ddc..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/actions.tsx
+++ /dev/null
@@ -1,640 +0,0 @@
-import { useClipboard } from "@vueuse/core";
-import { cloneDeep } from "lodash-es";
-import {
- CodeIcon,
- CopyIcon,
- ExternalLinkIcon,
- FileCodeIcon,
- FileDiffIcon,
- FileMinusIcon,
- FilePlusIcon,
- FileSearch2Icon,
- LinkIcon,
- SquarePenIcon,
-} from "lucide-vue-next";
-import { type DropdownOption } from "naive-ui";
-import { computed, nextTick, ref } from "vue";
-import { useRouter } from "vue-router";
-import { TableIcon } from "@/components/Icon";
-import formatSQL from "@/components/MonacoEditor/sqlFormatter";
-import { useExecuteSQL } from "@/composables/useExecuteSQL";
-import { t } from "@/plugins/i18n";
-import { SQL_EDITOR_DATABASE_MODULE } from "@/router/sqlEditor";
-import {
- pushNotification,
- useDatabaseV1Store,
- useDBSchemaV1Store,
- useSQLEditorTabStore,
-} from "@/store";
-import {
- DEFAULT_SQL_EDITOR_TAB_MODE,
- dialectOfEngineV1,
- type EditorPanelView,
- type EditorPanelViewState,
- languageOfEngineV1,
- type Position,
- type SQLEditorConnection,
- type SQLEditorTab,
- typeToView,
-} from "@/types";
-import { Engine } from "@/types/proto-es/v1/common_pb";
-import {
- type Database,
- GetSchemaStringRequest_ObjectType,
-} from "@/types/proto-es/v1/database_service_pb";
-import {
- defaultSQLEditorTab,
- extractDatabaseResourceName,
- extractInstanceResourceName,
- extractProjectResourceName,
- generateSimpleDeleteStatement,
- generateSimpleInsertStatement,
- generateSimpleSelectAllStatement,
- generateSimpleUpdateStatement,
- getInstanceResource,
- instanceV1HasAlterSchema,
- isSameSQLEditorConnection,
- sortByDictionary,
- supportGetStringSchema,
-} from "@/utils";
-import { type SQLEditorEvents, useSQLEditorContext } from "../../context";
-import { keyWithPosition } from "../../EditorCommon";
-import { useCurrentTabViewStateContext } from "../../EditorPanel";
-import type { NodeTarget, NodeType, TreeNode } from "./tree";
-import { readableTextForNodeTarget } from "./tree";
-
-type DropdownOptionWithTreeNode = DropdownOption & {
- onSelect?: () => void;
-};
-const SELECT_ALL_LIMIT = 50; // default pagesize of SQL Editor
-
-export const useActions = () => {
- const { updateViewState, viewState: currentTabViewState } =
- useCurrentTabViewStateContext();
- const databaseStore = useDatabaseV1Store();
-
- const selectAllFromTableOrView = async (node: TreeNode) => {
- const { target, type } = (node as TreeNode<"table" | "view">).meta;
- if (!targetSupportsGenerateSQL(target)) {
- return;
- }
-
- const schema = target.schema;
- const tableOrViewName = readableTextForNodeTarget(type, target);
- if (!tableOrViewName) {
- return;
- }
-
- const { database } = target;
- const db = databaseStore.getDatabaseByName(database);
- const engine = getInstanceResource(db).engine;
-
- const query = await formatCode(
- generateSimpleSelectAllStatement(
- engine,
- schema,
- tableOrViewName,
- SELECT_ALL_LIMIT
- ),
- engine
- );
- updateViewState({
- view: "CODE",
- });
- runQuery(db, schema, tableOrViewName, query);
- };
-
- const openNewTab = (params: {
- title: string;
- schema?: string;
- table?: string;
- view: EditorPanelView;
- }) => {
- const tabStore = useSQLEditorTabStore();
-
- let schema = params.schema;
- let table = params.table;
- if (currentTabViewState.value) {
- if (!schema) {
- schema = currentTabViewState.value.schema;
- }
- if (!table) {
- table = currentTabViewState.value.table;
- }
- }
-
- const fromTab = tabStore.currentTab;
- const clonedTab: SQLEditorTab = {
- ...defaultSQLEditorTab(),
- status: "CLEAN",
- title: params.title,
- };
- if (fromTab) {
- clonedTab.connection = cloneDeep(fromTab.connection);
- clonedTab.treeState = cloneDeep(fromTab.treeState);
- }
-
- const findExistedTab = tabStore.openTabList.find((tab) => {
- if (tab.status !== "CLEAN" || tab.id === fromTab?.id) {
- return false;
- }
- if (!isSameSQLEditorConnection(tab.connection, clonedTab.connection)) {
- return false;
- }
- const viewState = tab.viewState;
- if (
- viewState.view !== params.view ||
- (schema && viewState.schema !== schema)
- ) {
- return false;
- }
- return true;
- });
-
- if (findExistedTab) {
- tabStore.setCurrentTabId(findExistedTab.id);
- } else {
- tabStore.addTab(clonedTab);
- updateViewState({ view: params.view, schema, table });
- }
- };
-
- const viewDetail = async (node: TreeNode) => {
- const { type, target } = node.meta;
- const SUPPORTED_TYPES: NodeType[] = [
- "table",
- "view",
- "procedure",
- "function",
- "trigger",
- ] as const;
- if (!SUPPORTED_TYPES.includes(type)) {
- return;
- }
-
- const { schema } = target as NodeTarget<"schema">;
- const { table } = target as NodeTarget<"table">;
- openNewTab({
- title: "View detail",
- view: typeToView(type),
- schema: schema,
- table: table,
- });
- await nextTick();
-
- const detail: EditorPanelViewState["detail"] = {};
- let name = "";
- switch (type) {
- case "table":
- name = (target as NodeTarget<"table">).table;
- detail.table = name;
- break;
- case "view":
- name = (target as NodeTarget<"view">).view;
- detail.view = name;
- break;
- case "procedure":
- const { procedure, position } = target as NodeTarget<"procedure">;
- name = procedure;
- detail.procedure = keyWithPosition(procedure, position);
- break;
- case "function":
- const { function: func, position: funcPosition } =
- target as NodeTarget<"function">;
- name = func;
- detail.func = keyWithPosition(func, funcPosition);
- break;
- case "trigger":
- const { trigger, position: triggerPosition } =
- target as NodeTarget<"trigger">;
- name = trigger;
- detail.trigger = keyWithPosition(trigger, triggerPosition);
- break;
- }
-
- updateViewState({
- detail,
- });
- if (name) {
- useSQLEditorTabStore().updateCurrentTab({
- title: `Detail for ${type} ${name}`,
- });
- }
- };
-
- return { selectAllFromTableOrView, viewDetail, openNewTab };
-};
-
-export const useDropdown = () => {
- const router = useRouter();
- const dbSchema = useDBSchemaV1Store();
- const databaseStore = useDatabaseV1Store();
- const { availableActions } = useCurrentTabViewStateContext();
- const { events: editorEvents, schemaViewer } = useSQLEditorContext();
- const { selectAllFromTableOrView, viewDetail, openNewTab } = useActions();
-
- const show = ref(false);
- const position = ref<Position>({
- x: 0,
- y: 0,
- });
- const context = ref<TreeNode>();
-
- const options = computed((): DropdownOptionWithTreeNode[] => {
- const node = context.value;
- if (!node) {
- return [];
- }
- const { type, target } = node.meta;
- const { database, schema } = target as NodeTarget<"schema">;
-
- // Don't show any context menu actions for disabled nodes
- if (node.disabled || !database) {
- return [];
- }
-
- const db = databaseStore.getDatabaseByName(database);
-
- const items: DropdownOptionWithTreeNode[] = [];
- if (type === "schema") {
- for (const action of availableActions.value) {
- items.push({
- key: action.view,
- label: action.title,
- icon: action.icon,
- onSelect: () => {
- openNewTab({
- title: `[${extractDatabaseResourceName(db.name).databaseName}] ${action.title}`,
- view: action.view,
- schema,
- });
- },
- });
- }
- }
-
- if (type === "table" || type === "view") {
- const tableOrView = readableTextForNodeTarget(
- type,
- target as NodeTarget<"table" | "view">
- );
- items.push({
- key: "copy-name",
- label: t("sql-editor.copy-name"),
- icon: () => <CopyIcon class="w-4 h-4" />,
- onSelect: () => {
- const name = schema ? `${schema}.${tableOrView}` : tableOrView;
- copyToClipboard(name);
- },
- });
- if (type === "view") {
- const { view } = target as NodeTarget<"view">;
- if (supportGetStringSchema(getInstanceResource(db).engine)) {
- items.push({
- key: "view-schema-text",
- label: t("sql-editor.view-schema-text"),
- icon: () => <CodeIcon class="w-4 h-4" />,
- onSelect: () => {
- schemaViewer.value = {
- schema,
- object: view,
- type: GetSchemaStringRequest_ObjectType.VIEW,
- };
- },
- });
- }
- }
-
- if (type === "table") {
- const { table } = target as NodeTarget<"table">;
-
- items.push({
- key: "copy-all-column-names",
- label: t("sql-editor.copy-all-column-names"),
- icon: () => <CopyIcon class="w-4 h-4" />,
- onSelect: () => {
- const tableMetadata = dbSchema.getTableMetadata({
- database,
- schema,
- table,
- });
- const name = tableMetadata.columns
- .map((col) => col.name)
- .join(", ");
- copyToClipboard(name);
- },
- });
-
- if (supportGetStringSchema(getInstanceResource(db).engine)) {
- items.push({
- key: "view-schema-text",
- label: t("sql-editor.view-schema-text"),
- icon: () => <CodeIcon class="w-4 h-4" />,
- onSelect: () => {
- schemaViewer.value = {
- schema,
- object: table,
- type: GetSchemaStringRequest_ObjectType.TABLE,
- };
- },
- });
- }
-
- if (instanceV1HasAlterSchema(getInstanceResource(db))) {
- items.push({
- key: "edit-schema",
- label: t("database.edit-schema"),
- icon: () => <SquarePenIcon class="w-4 h-4" />,
- onSelect: () => {
- editorEvents.emit("alter-schema", {
- databaseName: db.name,
- schema: schema,
- table: table,
- });
- },
- });
- }
-
- items.push({
- key: "copy-url",
- label: t("sql-editor.copy-url"),
- icon: () => <LinkIcon class="w-4 h-4" />,
- onSelect: () => {
- const { instance, databaseName } = extractDatabaseResourceName(
- db.name
- );
- const route = router.resolve({
- name: SQL_EDITOR_DATABASE_MODULE,
- params: {
- project: extractProjectResourceName(db.project),
- instance: extractInstanceResourceName(instance),
- database: databaseName,
- },
- query: {
- table: table,
- schema: schema,
- },
- });
- const url = new URL(route.href, window.location.origin).href;
- copyToClipboard(url);
- },
- });
- }
- if (targetSupportsGenerateSQL(target)) {
- items.push({
- key: "preview-table-data",
- label: t("sql-editor.preview-table-data"),
- icon: () => <TableIcon class="w-4 h-4" />,
- onSelect: async () => {
- selectAllFromTableOrView(node);
- },
- });
- }
- const generateSQLChildren: DropdownOptionWithTreeNode[] = [];
-
- if (targetSupportsGenerateSQL(target)) {
- const engine = engineForTarget(target);
- generateSQLChildren.push({
- key: "generate-sql--select",
- label: "SELECT",
- icon: () => <FileSearch2Icon class="w-4 h-4" />,
- onSelect: async () => {
- const statement = await formatCode(
- generateSimpleSelectAllStatement(
- engine,
- schema,
- tableOrView,
- SELECT_ALL_LIMIT
- ),
- engine
- );
- applyContentToCurrentTabOrCopyToClipboard(statement, editorEvents);
- },
- });
- if (type === "table") {
- const { table } = target as NodeTarget<"table">;
- const tableMetadata = dbSchema.getTableMetadata({
- database,
- schema,
- table,
- });
- const columns = tableMetadata.columns.map((column) => column.name);
-
- generateSQLChildren.push({
- key: "generate-sql--insert",
- label: "INSERT",
- icon: () => <FilePlusIcon class="w-4 h-4" />,
- onSelect: async () => {
- const statement = await formatCode(
- generateSimpleInsertStatement(engine, schema, table, columns),
- engine
- );
- applyContentToCurrentTabOrCopyToClipboard(
- statement,
- editorEvents
- );
- },
- });
- generateSQLChildren.push({
- key: "generate-sql--update",
- label: "UPDATE",
- icon: () => <FileDiffIcon class="w-4 h-4" />,
- onSelect: async () => {
- const statement = await formatCode(
- generateSimpleUpdateStatement(engine, schema, table, columns),
- engine
- );
- applyContentToCurrentTabOrCopyToClipboard(
- statement,
- editorEvents
- );
- },
- });
- generateSQLChildren.push({
- key: "generate-sql--delete",
- label: "DELETE",
- icon: () => <FileMinusIcon class="w-4 h-4" />,
- onSelect: async () => {
- const statement = await formatCode(
- generateSimpleDeleteStatement(engine, schema, table),
- engine
- );
- applyContentToCurrentTabOrCopyToClipboard(
- statement,
- editorEvents
- );
- },
- });
- }
- }
- if (generateSQLChildren.length > 0) {
- items.push({
- key: "generate-sql",
- label: t("sql-editor.generate-sql"),
- icon: () => <FileCodeIcon class="w-4 h-4" />,
- children: generateSQLChildren,
- });
- }
- }
- if (
- type === "table" ||
- type === "view" ||
- type === "procedure" ||
- type === "function" ||
- type === "trigger"
- ) {
- items.push({
- key: "view-detail",
- label: t("sql-editor.view-detail"),
- icon: () => <ExternalLinkIcon class="w-4 h-4" />,
- onSelect: () => {
- viewDetail(node);
- },
- });
- }
- const ORDERS = [
- "copy-name",
- "copy-all-column-names",
- "copy-select-statement",
- "preview-table-data",
- "generate-sql",
- "view-schema-text",
- "view-detail",
- "edit-schema",
- "copy-url",
- ];
- sortByDictionary(items, ORDERS, (item) => item.key as string);
- return items;
- });
-
- const flattenOptions = computed(() => {
- return options.value.flatMap<DropdownOptionWithTreeNode>((item) => {
- if (item.children) {
- return [item, ...item.children] as DropdownOptionWithTreeNode[];
- }
- return item;
- });
- });
-
- const handleSelect = (key: string) => {
- const option = flattenOptions.value.find((item) => item.key === key);
- if (!option) {
- return;
- }
- if (typeof option.onSelect === "function") {
- option.onSelect();
- }
- show.value = false;
- };
-
- const handleClickoutside = () => {
- show.value = false;
- };
-
- return {
- show,
- position,
- context,
- options,
- handleSelect,
- handleClickoutside,
- selectAllFromTableOrView,
- };
-};
-
-const engineForTarget = (target: NodeTarget) => {
- const { database } = target as NodeTarget<"database">;
- return getInstanceResource(useDatabaseV1Store().getDatabaseByName(database))
- .engine;
-};
-
-const targetSupportsGenerateSQL = (target: NodeTarget) => {
- const engine = engineForTarget(target);
- if (engine === Engine.REDIS) {
- return false;
- }
- return true;
-};
-
-const applyContentToCurrentTabOrCopyToClipboard = async (
- content: string,
- editorEvents: SQLEditorEvents
-) => {
- const tabStore = useSQLEditorTabStore();
-
- const tab = tabStore.currentTab;
- if (!tab) {
- copyToClipboard(content);
- return;
- }
-
- editorEvents.emit("append-editor-content", {
- content: content,
- select: true,
- });
-};
-
-const copyToClipboard = (content: string) => {
- const { copy: copyTextToClipboard, isSupported } = useClipboard({
- legacy: true,
- });
- if (!isSupported.value) {
- return;
- }
- copyTextToClipboard(content).then(() => {
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.copied"),
- });
- });
-};
-
-const runQuery = async (
- database: Database,
- schema: string,
- tableOrViewName: string,
- statement: string
-) => {
- const tab = useSQLEditorTabStore().currentTab;
- if (!tab) {
- return;
- }
- if (tab.mode === "ADMIN") {
- useSQLEditorTabStore().updateCurrentTab({
- mode: DEFAULT_SQL_EDITOR_TAB_MODE,
- });
- }
-
- const { execute } = useExecuteSQL();
- const connection: SQLEditorConnection = {
- instance: extractDatabaseResourceName(database.name).instance,
- database: database.name,
- schema,
- table: tableOrViewName,
- };
- await nextTick();
- execute({
- statement,
- connection,
- explain: false,
- engine: getInstanceResource(database).engine,
- selection: tab.editorState.selection,
- });
-};
-
-const formatCode = async (code: string, engine: Engine) => {
- const lang = languageOfEngineV1(engine);
- if (lang !== "sql") {
- return code;
- }
- try {
- const result = await formatSQL(code, dialectOfEngineV1(engine));
- if (!result.error) {
- return result.data;
- }
- return code; // fallback;
- } catch {
- return code; // fallback
- }
-};
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/click.ts b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/click.ts
deleted file mode 100644
index 8598f2b0dc..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/click.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import Emittery from "emittery";
-import { ref } from "vue";
-import { type TreeNode } from "./tree";
-
-export const useClickEvents = () => {
- const DELAY = 250;
- const state = ref<{
- timeout: ReturnType<typeof setTimeout>;
- node: TreeNode;
- }>();
- const events = new Emittery<{
- "single-click": { node: TreeNode };
- "double-click": { node: TreeNode };
- }>();
-
- const clear = () => {
- if (!state.value) return;
- clearTimeout(state.value.timeout);
- state.value = undefined;
- };
- const queue = (node: TreeNode) => {
- state.value = {
- timeout: setTimeout(() => {
- events.emit("single-click", { node });
- clear();
- }, DELAY),
- node,
- };
- };
-
- const handleClick = (node: TreeNode) => {
- if (state.value && state.value.node.key === node.key) {
- events.emit("double-click", { node });
- clear();
- return;
- }
- clear();
- queue(node);
- };
-
- return { events, handleClick };
-};
diff --git a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/index.ts b/frontend/src/views/sql-editor/AsidePanel/SchemaPane/index.ts
deleted file mode 100644
index 0c3be82414..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/SchemaPane/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import SchemaPane from "./SchemaPane.vue";
-
-export default SchemaPane;
diff --git a/frontend/src/views/sql-editor/AsidePanel/index.ts b/frontend/src/views/sql-editor/AsidePanel/index.ts
deleted file mode 100644
index b86004546d..0000000000
--- a/frontend/src/views/sql-editor/AsidePanel/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import AsidePanel from "./AsidePanel.vue";
-
-export default AsidePanel;
diff --git a/frontend/src/views/sql-editor/SQLEditorHomePage.vue b/frontend/src/views/sql-editor/SQLEditorHomePage.vue
index d01a06f41a..712620bc98 100644
--- a/frontend/src/views/sql-editor/SQLEditorHomePage.vue
+++ b/frontend/src/views/sql-editor/SQLEditorHomePage.vue
@@ -23,7 +23,7 @@
width="80vw"
placement="left"
>
- <AsidePanel />
+ <ReactPageMount page="AsidePanel" container-class="h-full" />
</Drawer>
</teleport>
<NSplit
@@ -36,7 +36,7 @@
@update:size="size => state.sizebarSize = size"
>
<template #1>
- <AsidePanel />
+ <ReactPageMount page="AsidePanel" container-class="h-full" />
</template>
<template #2>
<div class="h-full relative flex flex-col">
@@ -92,7 +92,6 @@ import {
extractDatabaseResourceName,
extractProjectResourceName,
} from "@/utils";
-import AsidePanel from "./AsidePanel";
import { useSQLEditorContext } from "./context";
import EditorPanel from "./EditorPanel";
import { provideCurrentTabViewStateContext } from "./EditorPanel/context/viewState";
diff --git a/frontend/src/views/sql-editor/context.ts b/frontend/src/views/sql-editor/context.ts
index 5d342b016f..61ab6469d1 100644
--- a/frontend/src/views/sql-editor/context.ts
+++ b/frontend/src/views/sql-editor/context.ts
@@ -11,7 +11,6 @@ import {
useWorkSheetStore,
} from "@/store";
import type { SQLEditorTab } from "@/types";
-import type { GetSchemaStringRequest_ObjectType } from "@/types/proto-es/v1/database_service_pb";
import { isWorksheetWritableV1 } from "@/utils";
import type { SQLEditorEvents as SQLEditorEventsMap } from "./events";
import { sqlEditorEvents } from "./events";
@@ -37,14 +36,6 @@ export type SQLEditorContext = {
min: number;
max: number;
}>;
- schemaViewer: Ref<
- | {
- schema?: string;
- object?: string;
- type?: GetSchemaStringRequest_ObjectType;
- }
- | undefined
- >;
pendingInsertAtCaret: Ref<string | undefined>;
@@ -92,7 +83,6 @@ export const provideSQLEditorContext = () => {
asidePanelTab,
showConnectionPanel,
showAIPanel,
- schemaViewer,
pendingInsertAtCaret,
highlightAccessGrantName,
editorPanelSize,
@@ -103,7 +93,6 @@ export const provideSQLEditorContext = () => {
showConnectionPanel,
showAIPanel,
editorPanelSize,
- schemaViewer,
pendingInsertAtCaret,
highlightAccessGrantName,
events: sqlEditorEvents,