Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: migrate SQL Editor component from Vue to React (#20072)
ecmadao9e7bc98a50da
diff --git a/docs/superpowers/specs/2026-04-20-sql-editor-react-migration-stage-4-design.md b/docs/superpowers/specs/2026-04-20-sql-editor-react-migration-stage-4-design.mdnew file mode 100644index 0000000000..e00e2cde9b--- /dev/null+++ b/docs/superpowers/specs/2026-04-20-sql-editor-react-migration-stage-4-design.md@@ -0,0 +1,127 @@+# SQL Editor React Migration — Stage 4 Design++**Date:** 2026-04-20+**Author:** [email protected]+**Status:** Draft++## 1. Goal & non-goals++**Goal:** (a) Delete two dead Vue files (cleanup); (b) migrate `EditorCommon/AdminModeButton.vue` to React as a single-leaf spike to learn what blockers exist before committing to a multi-stage `EditorAction.vue` migration roadmap.++**Non-goals (Stage 4):**+- Migrating `EditorAction.vue`, `OpenAIButton`, `DatabaseChooser`, `SchemaChooser`, `ContainerChooser`, `QueryContextSettingPopover`, `SharePopover`, or any other EditorAction child.+- Building Vue-in-React mount infrastructure.+- Bridging the Emittery `events` bus.+- Bridging the AI plugin context.+- Decision on Q1 (top-down) vs Q2 (cascade-up) for Stage 5+ — that decision is informed by what we learn from this spike.++## 2. Cleanup tasks++- **Delete** `frontend/src/views/sql-editor/EditorCommon/DisconnectedIcon.vue` (3 lines, zero live callers — only present in the barrel).+- **Delete** `frontend/src/views/sql-editor/EditorCommon/ReadonlyDatasourceHint.vue` (66 lines, zero callers anywhere).+- **Update** `frontend/src/views/sql-editor/EditorCommon/index.ts` — remove the `DisconnectedIcon` import and named export.++Pre-deletion verification: `rg "DisconnectedIcon|ReadonlyDatasourceHint" frontend/src/` confirms zero live consumers (already verified — only the barrel and the files themselves).++## 3. Spike: migrate `AdminModeButton`++### 3.1 New React files++| File | Purpose |+|---|---|+| `frontend/src/react/components/sql-editor/AdminModeButton.tsx` | Function component. Props: `size?: "sm" \| "default"` (defaults to "default"; "sm" maps to shadcn Button's `size="sm"`) and `hideText?: boolean` (default false). Reads `allowAdmin`, `currentTab.mode`, and `isDisconnected` via `useVueState` from Pinia. Writes `tabStore.updateCurrentTab({ mode: "ADMIN" })` on click. Uses `WrenchIcon` from `lucide-react`. Renders nothing when `showButton` is false. |+| `frontend/src/react/components/sql-editor/AdminModeButton.test.tsx` | 4 vitest cases: hidden when `!allowAdmin`; hidden when current tab mode is not WORKSHEET; disabled when disconnected; click writes `mode: "ADMIN"`. |++### 3.2 Vue caller swap++`EditorAction.vue:54–65` currently:++```vue+<NPopover placement="bottom">+ <template #trigger>+ <AdminModeButton+ size="small"+ :hide-text="true"+ style="--n-padding: 0 5px"+ />+ </template>+ <template #default>+ <span>{{ $t("sql-editor.admin-mode.self") }}</span>+ </template>+</NPopover>+```++Swap to:++```vue+<ReactPageMount page="AdminModeButton" size="sm" :hideText="true" />+```++The Vue `<NPopover>` is removed; the React `AdminModeButton` will internally wrap its button with the React `Tooltip` primitive (label = `t("sql-editor.admin-mode.self")`) so the tooltip-on-hover behavior is preserved within the React leaf.++Drop the `import AdminModeButton from "./AdminModeButton.vue";` import from `EditorAction.vue`. Add `import ReactPageMount from "@/react/ReactPageMount.vue";` if not already present (it isn't yet for this file).++### 3.3 Vue file deletion — DEFERRED (spike learning)++Original assumption: `AdminModeButton.vue` had only one caller (`EditorAction.vue`), so the Vue file would be deletable after the swap. **Reality discovered during implementation:** the Vue component has 3 callers, not 1:++1. `EditorCommon/EditorAction.vue` — migrated to React in this stage.+2. `EditorCommon/ExecuteHint.vue:25,36` — uses `<AdminModeButton @enter="$emit('close')" />` (Vue caller, uses the `enter` emit which the React port doesn't yet expose).+3. `EditorPanel/ReadonlyModeNotSupported.vue:13` — `<AdminModeButton />` zero-prop usage (Vue caller).++The Vue `AdminModeButton.vue` is RETAINED for these 2 remaining Vue callers. The React version co-exists. This is the expected bottom-up migration pattern: shared leaves stay Vue until ALL callers are React, then the Vue version is deleted.++**Key spike learning:** Stage 5+ planning must `rg`-verify ALL callers of any candidate file BEFORE assuming it's a clean leaf migration. Multi-caller Vue children aren't deletable in a single stage.++### 3.4 i18n++`sql-editor.admin-mode.self` — verify in React locales. Add to all 5 locales if missing, using the Vue locale values byte-exact. If `admin-mode.exit` and other admin-mode keys are also unused in React but referenced by the broader EditorAction (still Vue), defer those — only this stage's React consumer matters now.++## 4. Verification++### 4.1 Per-leaf++- `pnpm --dir frontend fix && check && type-check && test` — all green.+- 4 new tests on `AdminModeButton.test.tsx`, all pass.+- React i18n consistency check passes (no missing/unused for `sql-editor.admin-mode.self`).++### 4.2 Manual UX (in dev server)++1. Open SQL Editor as a user with `allowAdmin` permission. In WORKSHEET mode, the admin-mode button (wrench icon) is visible in the action toolbar. In ADMIN mode (or any non-WORKSHEET mode), the button is hidden.+2. Open as a user without `allowAdmin` → button hidden in all modes.+3. Hover the button → tooltip "Admin mode" appears (label from `sql-editor.admin-mode.self`).+4. Click the button → tab switches to ADMIN mode (UI changes immediately).+5. When connection is lost (`isDisconnected=true`), the button renders disabled (visually muted, no click effect).++### 4.3 Side-by-side visual parity++The naive-ui `NButton type="warning" ghost` renders with a warning-orange ghost outline. The React shadcn `Button` lacks a "warning" variant out of the box. The React migration will use `variant="outline"` with a `className` override of `border-warning text-warning hover:bg-warning/5` for visual parity. Confirm visually during manual UX.++## 5. Out of scope (deferred)++- All other `EditorAction.vue` children (per §1 non-goals).+- Vue-in-React mount infrastructure (the spike doesn't need it).+- Emittery events bridge.+- AI plugin context bridge.++## 6. Stage 5 informed by this spike++After Stage 4, we'll have one Vue child of `EditorAction.vue` migrated. We use that to evaluate:+- Did visual parity feel right (NPopover → Tooltip)?+- Was the prop bridge fine for `size` and `hideText`?+- Did any unexpected dependency surface?+- Is there appetite for migrating each remaining child the same way (cascade-up, Q2), or would Q1's top-down approach now feel justified?++Stage 5 brainstorm picks the next leaf or the EditorAction shell itself with this information in hand.++## 7. Practical checklist++- [ ] `frontend/src/views/sql-editor/EditorCommon/DisconnectedIcon.vue` deleted.+- [ ] `frontend/src/views/sql-editor/EditorCommon/ReadonlyDatasourceHint.vue` deleted.+- [ ] `frontend/src/views/sql-editor/EditorCommon/index.ts` — `DisconnectedIcon` import + export removed.+- [ ] `sql-editor.admin-mode.self` added to React locales (if missing).+- [ ] `react/components/sql-editor/AdminModeButton.tsx` + 4 tests created.+- [ ] `EditorAction.vue` swapped: `<NPopover>...<AdminModeButton>...</NPopover>` → `<ReactPageMount page="AdminModeButton" size="sm" :hideText="true" />`. `AdminModeButton` import removed; `ReactPageMount` import added.+- [ ] `EditorCommon/AdminModeButton.vue` deleted after `rg` confirms zero remaining callers.+- [ ] `pnpm fix && check && type-check && test` all pass.+- [ ] Manual UX verified for the 5 states above.diff --git a/docs/superpowers/specs/2026-04-20-sql-editor-react-migration-stage-5-design.md b/docs/superpowers/specs/2026-04-20-sql-editor-react-migration-stage-5-design.mdnew file mode 100644index 0000000000..ba039a58d5--- /dev/null+++ b/docs/superpowers/specs/2026-04-20-sql-editor-react-migration-stage-5-design.md@@ -0,0 +1,112 @@+# SQL Editor React Migration — Stage 5 Design++**Date:** 2026-04-20+**Author:** [email protected]+**Status:** Draft++## 1. Goal & non-goals++**Goal:** Migrate the entire `<NButtonGroup>` of 3 connection choosers in `EditorAction.vue` to React as one unit: `DatabaseChooser`, `SchemaChooser`, `ContainerChooser`, plus their shared private primitive `ConnectChooser`. Single React mount preserves the visual button-group behavior; all 4 Vue files become deletable in this stage.++**Non-goals (Stage 5):**+- Migrating `EditorAction.vue` itself — it stays Vue; just one of its child slots is swapped.+- Migrating `OpenAIButton`, `QueryContextSettingPopover`, `SharePopover`, `SaveSheetModal`.+- Building Vue-in-React mount infrastructure.+- Bridging the Emittery `events` bus.+- Porting the custom `SchemaIcon.vue` and `DatabaseIcon.vue` Vue icons — use `lucide-react` substitutes (`Network` for SchemaIcon, `Database` for DatabaseIcon).++## 2. Architecture++`EditorAction.vue:125-129`'s `<NButtonGroup>` block:++```vue+<NButtonGroup>+ <DatabaseChooser />+ <SchemaChooser />+ <ContainerChooser />+</NButtonGroup>+```++Becomes a single React mount:++```vue+<ReactPageMount page="ChooserGroup" />+```++The React `ChooserGroup` component owns the visual grouping (flex + connected-border styling matching NButtonGroup's appearance) and renders 3 React children: `DatabaseChooser`, `SchemaChooser`, `ContainerChooser`. The shared `ConnectChooser` primitive is the styled chooser-button-with-popover used by SchemaChooser and ContainerChooser.++## 3. New React files++| File | Lines | Purpose |+|---|---|---|+| `react/components/sql-editor/ConnectChooser.tsx` | ~60 | Shared chooser primitive. Shadcn `Combobox` wrapped in a styled trigger button with `Network` icon. Props: `value`, `onChange`, `options`, `placeholder`, `isChosen`. Replaces NPopselect+NButton. Base UI's positioner handles auto-flip and viewport-aware sizing — drops the manual `useElementBounding` math. |+| `react/components/sql-editor/SchemaChooser.tsx` | ~50 | Wraps ConnectChooser. Reads `useConnectionOfCurrentSQLEditorTab` for instance/database, `useDBSchemaV1Store` for metadata, `useSQLEditorTabStore` for current tab. Computes `show = instanceAllowsSchemaScopedQuery(engine)`, options from `databaseMetadata.schemas`, value from `tab.connection.schema` with `"-1"` sentinel for unspecified. Watches `router.currentRoute.value.query.schema` to seed via `useEffect`. |+| `react/components/sql-editor/ContainerChooser.tsx` | ~55 | Same pattern as SchemaChooser but for tables. `show = engine === COSMOSDB`, options from `databaseMetadata.schemas[].tables`, value from `tab.connection.table`. Watches `router.currentRoute.value.query.table`. |+| `react/components/sql-editor/DatabaseChooser.tsx` | ~80 | The breadcrumb-style chooser. Reads multiple stores. Renders Environment > Instance > Database via React `EnvironmentLabel` (already exists) + `<img>` with `EngineIconPath` (existing pattern from TransferProjectSheet). Click sets `useSQLEditorUIStore().showConnectionPanel = true`. Has a tooltip popover for batch-mode indicator. Uses lucide `SquareStack` for batch icon, `ChevronRight` for separators, `Database` for the database icon. |+| `react/components/sql-editor/ChooserGroup.tsx` | ~30 | Flex wrapper with connected-border styling. Renders the 3 React choosers in sequence. The mount entry point referenced by `ReactPageMount`. |++Each gets a `*.test.tsx` file with focused vitest cases (3-6 tests per).++## 4. Vue caller swap++`EditorAction.vue:125-129` — replace the `<NButtonGroup>` block (5 lines) with `<ReactPageMount page="ChooserGroup" />` (1 line).++Imports to update at the top of `EditorAction.vue`:+- Remove `DatabaseChooser`, `SchemaChooser`, `ContainerChooser` Vue imports+- Remove `NButtonGroup` from the `naive-ui` named import (verify it's not used elsewhere — visual inspection of `EditorAction.vue` shows another `<NButtonGroup>` at line 23 wrapping the run-query button + popover; KEEP `NButtonGroup` in the import).+- `ReactPageMount` is already imported (added in Stage 4).++## 5. Vue file deletions++After the swap, these become orphaned (verified single-caller in audit):+- `EditorCommon/DatabaseChooser.vue`+- `EditorCommon/SchemaChooser.vue`+- `EditorCommon/ContainerChooser.vue`+- `EditorCommon/ConnectChooser.vue`++`rg`-verify zero remaining callers before deletion. Expected: only the React replacement files match.++## 6. i18n keys++Verify these in React locales; add any missing using values from Vue locales:+- `database.schema.select` (SchemaChooser placeholder)+- `database.schema.unspecified` (Schema/Container "all schemas" option)+- `db.schema.default` (default-schema fallback label)+- `database.table.select` (ContainerChooser placeholder)++DatabaseChooser also uses:+- `sql-editor.batch-query.batch` (batch-mode tooltip)+- `sql-editor.select-a-database-to-start` (placeholder when disconnected)++## 7. Verification++- `pnpm fix && check && type-check && test` all green+- New tests: ~20 across 5 component test files+- Manual UX: open SQL Editor, verify the 3-button toolbar group renders identically (visual inspection vs. Vue), schema/container choosers gate correctly per engine, database chooser breadcrumb renders correctly, click on database chooser opens connection panel, schema/table selection persists to tab connection state, route-query seeding still works.++## 8. Visual styling notes++- The Vue `NButtonGroup` produces a row of buttons with shared/joined borders. The React `ChooserGroup` should replicate this with `flex` + `[&>*:not(:first-child)]:border-l-0` + `[&>*:first-child]:rounded-r-none` etc., OR use a simpler `flex gap-0` and have each chooser button render with `rounded-none border-r-0` except the last. Pick whichever is cleaner during implementation.+- The Vue chooser button uses `type="primary" ghost` styling (accent border, accent text, transparent fill) similar to ConnectionHolder — reuse the same className pattern: `border-accent text-accent hover:bg-accent/5`.+- DatabaseChooser's "select a database" disconnected state has different styling — verify visually.++## 9. Out of scope (deferred)++- `SchemaIcon.vue` port to React — used by 6 callers, out of scope for this stage. Use lucide `Network` substitute.+- `DatabaseIcon.vue` port — used by ~20 callers. Use lucide `Database`.+- Migrating `EditorAction.vue` itself.+- Vue-in-React mount infrastructure.+- Emittery events bridge.++## 10. Practical checklist++- [ ] React `ConnectChooser.tsx` + test+- [ ] React `SchemaChooser.tsx` + test+- [ ] React `ContainerChooser.tsx` + test+- [ ] React `DatabaseChooser.tsx` + test+- [ ] React `ChooserGroup.tsx` + test (or smoke test only)+- [ ] i18n keys verified/added in 5 React locales+- [ ] `EditorAction.vue:125-129` swapped to `<ReactPageMount page="ChooserGroup" />`; Vue chooser imports removed+- [ ] 4 Vue files deleted after `rg` confirms no remaining callers+- [ ] `pnpm fix && check && type-check && test` all pass+- [ ] Manual UX parity verifieddiff --git a/docs/superpowers/specs/2026-04-20-sql-editor-react-migration-stage-6-design.md b/docs/superpowers/specs/2026-04-20-sql-editor-react-migration-stage-6-design.mdnew file mode 100644index 0000000000..956d7addb8--- /dev/null+++ b/docs/superpowers/specs/2026-04-20-sql-editor-react-migration-stage-6-design.md@@ -0,0 +1,188 @@+# SQL Editor React Migration — Stage 6 Design++**Date:** 2026-04-20+**Author:** [email protected]+**Status:** Draft++## 1. Goal & non-goals++**Goal:** Migrate `EditorCommon/QueryContextSettingPopover.vue` (194 lines) to React. Along the way: (a) build a new React `Popover` primitive that future migrations will reuse; (b) port `MaxRowCountSelect.vue` as a React shared component (the Vue version is retained because `DataExportButton.vue` still uses it).++**Non-goals (Stage 6):**+- Migrating `SaveSheetModal.vue` (Stage 7 — requires Emittery + async actions bridge).+- Migrating `SharePopover.vue` (Stage 8 — multi-caller pattern).+- Migrating `OpenAIButton` or any other EditorAction child.+- Deleting `MaxRowCountSelect.vue` — it's still used by `DataExportButton.vue`. Vue and React versions co-exist.+- Building Vue-in-React mount infrastructure.+- Bridging the Emittery `events` bus.++## 2. Architecture++Three new React files, one swap, one Vue file deletion:++| Action | File | Why |+|---|---|---|+| Create | `react/components/ui/popover.tsx` | New shadcn-style primitive wrapping Base UI Popover. First React Popover in the codebase; needed here, reusable for Stages 7+. |+| Create | `react/components/MaxRowCountSelect.tsx` | React version of Vue `MaxRowCountSelect.vue`. Vue version retained for DataExportButton. |+| Create | `react/components/sql-editor/QueryContextSettingPopover.tsx` | The Stage 6 primary target — replaces the Vue popover. |+| Modify | `views/sql-editor/EditorCommon/EditorAction.vue:49-51` | Swap `<QueryContextSettingPopover>` → `<ReactPageMount page="QueryContextSettingPopover" :disabled="..." />`. |+| Delete | `views/sql-editor/EditorCommon/QueryContextSettingPopover.vue` | Single caller (EditorAction), now swapped — safe to delete after verification. |++Each new React file gets a `*.test.tsx` with focused tests.++## 3. New React `Popover` primitive++### Design++Follow existing shadcn primitives (see `react/components/ui/dialog.tsx`, `dropdown-menu.tsx`). Wraps `@base-ui/react/popover`. Exposes compound parts:++```tsx+import { Popover as BasePopover } from "@base-ui/react/popover";+// Export:+export const Popover = BasePopover.Root;+export const PopoverTrigger = BasePopover.Trigger;+// PopoverContent wraps BasePopover.Portal + Positioner + Popup with project+// styling: rounded-sm, border, shadow, bg-main, layer-surface, etc.+// Mirror the existing Tooltip primitive's layer/portal/styling conventions.+```++Minimum API:++```tsx+<Popover>+ <PopoverTrigger>...</PopoverTrigger>+ <PopoverContent side="bottom-end" sideOffset={4}>+ ...+ </PopoverContent>+</Popover>+```++`side` supports `"top" | "bottom" | "left" | "right" | "bottom-end"` etc. via `side` + `align`. Rendered into the `overlay` layer via `getLayerRoot("overlay")` for proper z-index stacking (follows the AGENTS.md overlay layering policy).++### Test (`popover.test.tsx`)++Minimal: renders trigger; clicking trigger opens content; clicking outside closes content. 2-3 tests.++## 4. React `MaxRowCountSelect`++Mirrors Vue `MaxRowCountSelect.vue` (91 lines):++**Props:** `{ value: number; onChange: (value: number) => void; maximum: number; quaternary?: boolean; className?: string }`++**Shape:** button trigger with label `"{Result limit} {n rows}"` and chevron icon → Popover content with:+- List of predefined row-count options (1, 100, 500, 1000, 5000, 10000, 100000 filtered by `maximum`)+- Custom number input at the bottom for arbitrary values within range++Uses shadcn `Button` (variant controlled by `quaternary` prop — map to `ghost` when quaternary, else `outline`), new `Popover` primitive, shadcn `Input` (with `type="number"`), `ChevronRight` icon from `lucide-react`, i18n keys `sql-editor.result-limit.self`, `common.rows.n-rows`, `common.rows.self`.++**Test (`MaxRowCountSelect.test.tsx`):**+- Renders current value in trigger label+- Options list filtered by `maximum`+- Selecting a preset calls `onChange` with the number+- Custom number input respects min/max clamping via `minmax` util++## 5. React `QueryContextSettingPopover`++Mirrors Vue source (194 lines). Core responsibilities:++- **Visibility:** renders nothing when `currentTab.mode === "ADMIN"` (read via `useVueState`).+- **Trigger:** accent-bordered ghost button with `ChevronDown` icon.+- **Data source radio group:** reads instance's `dataSources`, renders "Automatic" + each data source. Admin-type data sources get tooltip-disabled behavior when `queryDataPolicy.allowAdminDataSource === false` AND read-only data sources exist. Selection writes `tab.connection.dataSourceId` (or unsets if "Automatic").+- **Redis cluster mode sub-group:** only when engine is Redis. Sub-group is disabled unless the selected data source's `redisType === CLUSTER`. Tooltip explains the disabled reason.+- **Max row count select:** bottom of popover, uses the new `MaxRowCountSelect` component, bound to `useSQLEditorStore().resultRowsLimit` via direct mutation.++**Props:** `{ disabled?: boolean }`++**Stores:** `useSQLEditorTabStore`, `useConnectionOfCurrentSQLEditorTab`, `useSQLEditorStore` — all at component top level.++**Utilities:** `getInstanceResource`, `readableDataSourceType` from `@/utils` (verify availability).++**Test (`QueryContextSettingPopover.test.tsx`):**+- Renders nothing when current tab is in ADMIN mode+- Renders nothing when `disabled=true` on the NPopover side — actually Vue renders the popover but disables it; React equivalent disables the trigger button when `disabled=true`+- Selecting a data source writes `tab.connection.dataSourceId`+- Selecting "Automatic" removes `dataSourceId`+- Redis sub-group only shown when engine is Redis+- `MaxRowCountSelect` selection updates `resultRowsLimit` on the store++## 6. EditorAction.vue swap++`EditorAction.vue:49-51`:++```vue+<QueryContextSettingPopover+ :disabled="!showQueryContextSettingPopover || !allowQuery"+/>+```++Becomes:++```vue+<ReactPageMount+ page="QueryContextSettingPopover"+ :disabled="!showQueryContextSettingPopover || !allowQuery"+/>+```++Remove the Vue import:+```ts+import QueryContextSettingPopover from "./QueryContextSettingPopover.vue";+```++`ReactPageMount` already imported (from Stage 4). The surrounding `NButtonGroup` (wrapping run-query button + this popover trigger) stays Vue.++**Visual concern:** the Vue `QueryContextSettingPopover` button is a direct sibling of the run-query button inside `NButtonGroup`, sharing borders. After the swap, the React trigger button is inside a ReactPageMount wrapper div, breaking the connected-border behavior (same issue that led to Stage 5's `ChooserGroup` decision).++**Decision:** accept the visual seam for Stage 6 — it's one button in isolation, less visually disruptive than the 3-chooser group. If the seam looks bad during manual UX, we can either (a) extend `ReactPageMount` to support `display: contents` wrapper, or (b) migrate the run-query button as well (expands Stage 6 scope — defer if possible).++## 7. Vue file deletion++After the swap:+- Delete `views/sql-editor/EditorCommon/QueryContextSettingPopover.vue` (single caller, now orphaned).+- **Retain** `views/sql-editor/AsidePanel/GutterBar/...` — already deleted in Stage 3.+- **Retain** `components/RoleGrantPanel/MaxRowCountSelect.vue` — still used by `DataExportButton.vue`.++Verify via `rg` before deletion.++## 8. i18n keys++Verify in React locales; add missing:+- `sql-editor.result-limit.self`+- `common.rows.n-rows` (pluralization key)+- `common.rows.self`+- `data-source.select-query-data-source`+- `data-source.automatic-query-data-source`+- `sql-editor.redis-command.self`+- `sql-editor.redis-command.single-node`+- `sql-editor.redis-command.all-nodes`+- `sql-editor.redis-command.only-for-cluster`+- `sql-editor.query-context.admin-data-source-is-disallowed-to-query`++## 9. Verification++- `pnpm fix && check && type-check && test` all green+- ~10 new tests+- Manual UX: open SQL Editor → see the chevron-down button next to run-query (no popover seams visible in toolbar)+- Click chevron-down → popover opens with data source radios + row count selector+- Select a non-default data source → query uses that data source (persists on tab.connection.dataSourceId)+- For Redis: sub-group appears; selecting cluster data source enables node-mode radios+- Change row limit → affects subsequent queries++## 10. Out of scope (deferred)++- Emittery bridge (Stage 7)+- Async actions bridge (Stage 7)+- SharePopover migration (Stage 8)+- OpenAIButton migration (Stage 9+)+- EditorAction.vue shell migration (final stage)++## 11. Practical checklist++- [ ] `react/components/ui/popover.tsx` + test created, exported from ui/+- [ ] `react/components/MaxRowCountSelect.tsx` + test+- [ ] `react/components/sql-editor/QueryContextSettingPopover.tsx` + test+- [ ] 10 i18n keys verified/added in 5 React locales+- [ ] `EditorAction.vue:49-51` swapped to `<ReactPageMount>`; QueryContextSettingPopover import removed+- [ ] `QueryContextSettingPopover.vue` deleted after `rg` confirms single caller+- [ ] `pnpm fix && check && type-check && test` all pass+- [ ] Manual UX parity verifieddiff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 1f8a631592..406b7e069b 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -993,8 +993,6 @@"no-extra-params-configured": "No extra connection parameters configured","no-params-yet-add-above": "No parameters configured yet. Add parameters using the form above.","no-password": "No password",- "no-read-only-data-source-warn-for-admin-dba": "The instance has not configured read-only connection, please consider adding one.",- "no-read-only-data-source-warn-for-developer": "The instance has not configured read-only connection, please ask your DBA to add one.","parameter-name-placeholder": "Parameter name","parameter-value-placeholder": "Parameter value","password-type": {@@ -2591,7 +2589,6 @@"copy-name": "Copy name","copy-selected-results": "Copy selected data by {action} or {button}","copy-url": "Copy URL",- "create-read-only-data-source": "Go to create","current-connection": "Current connection","download-as-file": "Download as {file}","duration-day": "{days} day",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex d0bd4194eb..21eff574a7 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -993,8 +993,6 @@"no-extra-params-configured": "No hay parámetros de conexión adicionales configurados","no-params-yet-add-above": "No hay parámetros configurados todavía. \nAgregue parámetros usando el formulario anterior.","no-password": "Sin contraseña",- "no-read-only-data-source-warn-for-admin-dba": "La instancia no ha configurado una conexión de solo lectura, por favor considere agregar una.",- "no-read-only-data-source-warn-for-developer": "La instancia no ha configurado una conexión de solo lectura, solicite a su DBA que agregue una.","parameter-name-placeholder": "Nombre de parámetro","parameter-value-placeholder": "Valor de parámetro","password-type": {@@ -2591,7 +2589,6 @@"copy-name": "Copiar nombre","copy-selected-results": "Copiar datos seleccionados por {action} o {button}","copy-url": "Copiar URL",- "create-read-only-data-source": "Ir a crear","current-connection": "Conexión actual","download-as-file": "Descargar como {file}","duration-day": "{days} day",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex e7182d09c3..65ac1caba6 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -993,8 +993,6 @@"no-extra-params-configured": "追加の接続パラメーターは構成されていません","no-params-yet-add-above": "まだ構成されていません。\n上記のフォームを使用してパラメーターを追加します。","no-password": "パスワードがありません",- "no-read-only-data-source-warn-for-admin-dba": "このインスタンスは読み取り専用接続で設定されていません。設定を検討してください。",- "no-read-only-data-source-warn-for-developer": "このインスタンスには読み取り専用接続が設定されていません。設定するように DBA に依頼してください。","parameter-name-placeholder": "パラメーター名","parameter-value-placeholder": "パラメーター値","password-type": {@@ -2591,7 +2589,6 @@"copy-name": "名前をコピーする","copy-selected-results": "選択したデータを{action}または{button}でコピーします","copy-url": "URLをコピー",- "create-read-only-data-source": "作成に行く","current-connection": "現在の接続","download-as-file": "{file} 形式でダウンロード","duration-day": "{days} day",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 98bd824826..22727dc2d3 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -993,8 +993,6 @@"no-extra-params-configured": "Không có thông số kết nối bổ sung được cấu hình","no-params-yet-add-above": "Chưa có thông số nào được cấu hình. \nThêm tham số bằng cách sử dụng biểu mẫu trên.","no-password": "Không có mật khẩu",- "no-read-only-data-source-warn-for-admin-dba": "Phiên bản chưa định cấu hình kết nối chỉ đọc, vui lòng xem xét thêm một kết nối.",- "no-read-only-data-source-warn-for-developer": "Phiên bản chưa được định cấu hình kết nối chỉ đọc, vui lòng yêu cầu DBA của bạn thêm một kết nối.","parameter-name-placeholder": "Tên tham số","parameter-value-placeholder": "Giá trị tham số","password-type": {@@ -2591,7 +2589,6 @@"copy-name": "Sao chép tên","copy-selected-results": "Sao chép dữ liệu đã chọn bằng {action} hoặc {button}","copy-url": "Sao chép URL",- "create-read-only-data-source": "Đi tới tạo","current-connection": "Kết nối hiện tại","download-as-file": "Tải xuống dưới dạng {file}","duration-day": "{days} day",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 9462080c84..8a8cfc83c2 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -993,8 +993,6 @@"no-extra-params-configured": "没有配置的额外连接参数","no-params-yet-add-above": "尚未配置参数。\n使用上面的形式添加参数。","no-password": "无密码",- "no-read-only-data-source-warn-for-admin-dba": "该实例没有配置只读连接,请考虑配置。",- "no-read-only-data-source-warn-for-developer": "该实例没有配置只读连接,请让您的 DBA 配置一个。","parameter-name-placeholder": "参数名称","parameter-value-placeholder": "参数值","password-type": {@@ -2591,7 +2589,6 @@"copy-name": "复制名称","copy-selected-results": "通过 {action} 或 {button} 来快速复制选定的数据","copy-url": "复制 URL",- "create-read-only-data-source": "前去创建","current-connection": "当前连接","download-as-file": "下载为 {file} 格式","duration-day": "{days} 天",diff --git a/frontend/src/react/components/DatabaseGroupForm.tsx b/frontend/src/react/components/DatabaseGroupForm.tsxindex 8d731153d8..4e6a2821a9 100644--- a/frontend/src/react/components/DatabaseGroupForm.tsx+++ b/frontend/src/react/components/DatabaseGroupForm.tsx@@ -247,7 +247,7 @@ export function DatabaseGroupForm({{!readonly && (<div className="sticky bottom-0 z-10">- <div className="flex justify-end w-full py-4 border-t border-block-border bg-background gap-x-3">+ <div className="flex justify-end w-full pt-4 pb-2 px-4 border-t border-block-border bg-background gap-x-3"><Button variant="outline" onClick={onDismiss}>{t("common.cancel")}</Button>diff --git a/frontend/src/react/components/MaxRowCountSelect.test.tsx b/frontend/src/react/components/MaxRowCountSelect.test.tsxnew file mode 100644index 0000000000..efbcc09dc9--- /dev/null+++ b/frontend/src/react/components/MaxRowCountSelect.test.tsx@@ -0,0 +1,165 @@+import type { ReactElement } from "react";+import { act } 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;++const mocks = vi.hoisted(() => ({+ useTranslation: vi.fn(() => ({+ t: (key: string, opts?: { n?: number }) =>+ opts?.n !== undefined ? `${key}:${opts.n}` : key,+ })),+ Popover: vi.fn(({ children }: { children: React.ReactNode }) => (+ <div data-testid="popover">{children}</div>+ )),+ PopoverTrigger: vi.fn(+ ({+ children,+ render,+ }: {+ children?: React.ReactNode;+ render?: React.ReactElement;+ }) => {+ if (render) {+ return <div data-testid="popover-trigger">{children}</div>;+ }+ return <div data-testid="popover-trigger">{children}</div>;+ }+ ),+ PopoverContent: vi.fn(({ children }: { children: React.ReactNode }) => (+ <div data-testid="popover-content">{children}</div>+ )),+ minmax: vi.fn((value: number, min: number, max: number) =>+ Math.min(Math.max(value, min), max)+ ),+}));++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/components/ui/popover", () => ({+ Popover: mocks.Popover,+ PopoverTrigger: mocks.PopoverTrigger,+ PopoverContent: mocks.PopoverContent,+}));++vi.mock("@/utils", () => ({+ minmax: mocks.minmax,+}));++let MaxRowCountSelect: typeof import("./MaxRowCountSelect").MaxRowCountSelect;++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();+ },+ };+};++beforeEach(async () => {+ vi.clearAllMocks();+ mocks.useTranslation.mockReturnValue({+ t: (key: string, opts?: { n?: number }) =>+ opts?.n !== undefined ? `${key}:${opts.n}` : key,+ });+ ({ MaxRowCountSelect } = await import("./MaxRowCountSelect"));+});++afterEach(() => {+ document.body.innerHTML = "";+});++describe("MaxRowCountSelect", () => {+ test("trigger renders current value label", () => {+ const { container, render, unmount } = renderIntoContainer(+ <MaxRowCountSelect+ value={1000}+ onChange={() => {}}+ maximum={Number.MAX_VALUE}+ />+ );+ render();+ // The trigger contains the translated key for n-rows with n=1000+ expect(container.textContent).toContain("common.rows.n-rows");+ unmount();+ });++ test("preset options are filtered by maximum", () => {+ const { container, render, unmount } = renderIntoContainer(+ <MaxRowCountSelect value={100} onChange={() => {}} maximum={500} />+ );+ render();+ // Should show 1, 100, 500 — not 1000, 5000, etc.+ const content = container.querySelector("[data-testid='popover-content']");+ const buttons = content?.querySelectorAll("button[type='button']") ?? [];+ const labels = Array.from(buttons).map((b) => b.textContent ?? "");+ // Filtered options: 1, 100, 500 (n-rows key with n)+ expect(labels.some((l) => l.includes(":1"))).toBe(true);+ expect(labels.some((l) => l.includes(":100"))).toBe(true);+ expect(labels.some((l) => l.includes(":500"))).toBe(true);+ // 1000 should NOT be present+ expect(labels.some((l) => l.includes(":1000"))).toBe(false);+ unmount();+ });++ test("clicking a preset option calls onChange with the value", () => {+ const onChange = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <MaxRowCountSelect+ value={100}+ onChange={onChange}+ maximum={Number.MAX_VALUE}+ />+ );+ render();+ // Click the button for 500+ const buttons = Array.from(+ container.querySelectorAll(+ "[data-testid='popover-content'] button[type='button']"+ )+ );+ const btn500 = buttons.find((b) => b.textContent?.includes(":500"));+ act(() => {+ (btn500 as HTMLButtonElement)?.click();+ });+ expect(onChange).toHaveBeenCalledWith(500);+ unmount();+ });++ test("custom number input applies minmax clamping", () => {+ const onChange = vi.fn();+ mocks.minmax.mockReturnValue(500);+ const { container, render, unmount } = renderIntoContainer(+ <MaxRowCountSelect value={100} onChange={onChange} maximum={500} />+ );+ render();+ const input = container.querySelector(+ "[data-testid='popover-content'] input[type='number']"+ ) as HTMLInputElement;+ expect(input).toBeTruthy();+ act(() => {+ Object.defineProperty(input, "value", { writable: true, value: "9999" });+ input.dispatchEvent(new Event("change", { bubbles: true }));+ });+ // minmax was called and onChange received the clamped value+ expect(mocks.minmax).toHaveBeenCalled();+ unmount();+ });+});diff --git a/frontend/src/react/components/MaxRowCountSelect.tsx b/frontend/src/react/components/MaxRowCountSelect.tsxnew file mode 100644index 0000000000..cff545e1c8--- /dev/null+++ b/frontend/src/react/components/MaxRowCountSelect.tsx@@ -0,0 +1,103 @@+import { first, last } from "lodash-es";+import { ChevronRight } from "lucide-react";+import { useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/react/components/ui/popover";+import { cn } from "@/react/lib/utils";+import { minmax } from "@/utils";++type MaxRowCountSelectProps = {+ readonly value: number;+ readonly onChange: (value: number) => void;+ readonly maximum: number;+ readonly quaternary?: boolean;+ readonly className?: string;+};++export function MaxRowCountSelect({+ value,+ onChange,+ maximum,+ quaternary = false,+ className,+}: MaxRowCountSelectProps) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);++ const rowCountOptions = useMemo(() => {+ const list = [1, 100, 500, 1000, 5000, 10000, 100000].filter(+ (num) => num <= maximum+ );+ if (maximum !== Number.MAX_VALUE && !list.includes(maximum)) {+ list.push(maximum);+ }+ return list;+ }, [maximum]);++ const handlePresetClick = (n: number) => {+ onChange(n);+ setOpen(false);+ };++ const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {+ const rawValue = Number(e.target.value);+ const clamped = minmax(+ Number.isNaN(rawValue) ? 0 : rawValue,+ first(rowCountOptions) ?? 1,+ last(rowCountOptions) ?? 100000+ );+ onChange(clamped);+ };++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger+ render={+ <Button+ variant={quaternary ? "ghost" : "outline"}+ size="sm"+ className={cn("justify-start", className)}+ />+ }+ >+ {t("sql-editor.result-limit.self")}{" "}+ {t("common.rows.n-rows", { n: value })}+ <ChevronRight className="size-4 ml-1" />+ </PopoverTrigger>+ <PopoverContent side="bottom" align="start" className="p-1 min-w-32">+ <div className="flex flex-col">+ {rowCountOptions.map((n) => (+ <button+ key={n}+ type="button"+ className={cn(+ "px-3 py-1.5 text-sm text-left rounded-xs cursor-pointer",+ "hover:bg-control-bg",+ n === value && "bg-control-bg font-medium"+ )}+ onClick={() => handlePresetClick(n)}+ >+ {t("common.rows.n-rows", { n })}+ </button>+ ))}+ <div className="flex items-center gap-1 px-3 py-1.5 border-t mt-1">+ <input+ type="number"+ className="w-20 border border-control-border rounded-xs px-2 py-0.5 text-sm"+ value={value}+ min={first(rowCountOptions) ?? 1}+ max={last(rowCountOptions) ?? 100000}+ onChange={handleInputChange}+ />+ <span className="text-sm">{t("common.rows.self")}</span>+ </div>+ </div>+ </PopoverContent>+ </Popover>+ );+}diff --git a/frontend/src/react/components/sql-editor/AdminModeButton.test.tsx b/frontend/src/react/components/sql-editor/AdminModeButton.test.tsxnew file mode 100644index 0000000000..7615b3057a--- /dev/null+++ b/frontend/src/react/components/sql-editor/AdminModeButton.test.tsx@@ -0,0 +1,134 @@+import type { ReactElement } from "react";+import { act } 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(() => ({+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ useSQLEditorStore: vi.fn(),+ useSQLEditorTabStore: vi.fn(),+}));++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useSQLEditorStore: mocks.useSQLEditorStore,+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,+}));++vi.mock("@/react/components/ui/tooltip", () => ({+ Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}));++let AdminModeButton: typeof import("./AdminModeButton").AdminModeButton;++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();+ },+ };+};++beforeEach(async () => {+ vi.clearAllMocks();+ // Default: allow admin, WORKSHEET mode, connected+ mocks.useSQLEditorStore.mockReturnValue({ allowAdmin: true });+ mocks.useSQLEditorTabStore.mockReturnValue({+ updateCurrentTab: vi.fn(),+ });+ mocks.useVueState.mockImplementation((getter) => getter());+ ({ AdminModeButton } = await import("./AdminModeButton"));+});++describe("AdminModeButton", () => {+ test("renders nothing when allowAdmin is false", () => {+ mocks.useSQLEditorStore.mockReturnValue({ allowAdmin: false });+ mocks.useVueState.mockImplementation((getter) => getter());+ // Need to also mock the tab state reads. Configure useVueState to return+ // appropriate values per call: allowAdmin=false, mode="WORKSHEET", isDisconnected=false+ let callIdx = 0;+ mocks.useVueState.mockImplementation(() => {+ const values = [false, "WORKSHEET", false];+ return values[callIdx++];+ });+ const { container, render, unmount } = renderIntoContainer(+ <AdminModeButton />+ );+ render();+ expect(container.querySelector("button")).toBeNull();+ unmount();+ });++ test("renders nothing when current tab mode is not WORKSHEET", () => {+ let callIdx = 0;+ mocks.useVueState.mockImplementation(() => {+ const values = [true, "ADMIN", false];+ return values[callIdx++];+ });+ const { container, render, unmount } = renderIntoContainer(+ <AdminModeButton />+ );+ render();+ expect(container.querySelector("button")).toBeNull();+ unmount();+ });++ test("renders disabled button when isDisconnected is true", () => {+ let callIdx = 0;+ mocks.useVueState.mockImplementation(() => {+ const values = [true, "WORKSHEET", true];+ return values[callIdx++];+ });+ const { container, render, unmount } = renderIntoContainer(+ <AdminModeButton />+ );+ render();+ const button = container.querySelector("button");+ expect(button).not.toBeNull();+ expect(button?.hasAttribute("disabled")).toBe(true);+ unmount();+ });++ test("click sets currentTab.mode to ADMIN", () => {+ const updateCurrentTab = vi.fn();+ mocks.useSQLEditorTabStore.mockReturnValue({ updateCurrentTab });+ let callIdx = 0;+ mocks.useVueState.mockImplementation(() => {+ const values = [true, "WORKSHEET", false];+ return values[callIdx++];+ });+ const { container, render, unmount } = renderIntoContainer(+ <AdminModeButton />+ );+ render();+ act(() => {+ container.querySelector("button")?.click();+ });+ expect(updateCurrentTab).toHaveBeenCalledWith({ mode: "ADMIN" });+ unmount();+ });+});diff --git a/frontend/src/react/components/sql-editor/AdminModeButton.tsx b/frontend/src/react/components/sql-editor/AdminModeButton.tsxnew file mode 100644index 0000000000..a41068b2e1--- /dev/null+++ b/frontend/src/react/components/sql-editor/AdminModeButton.tsx@@ -0,0 +1,58 @@+import { Wrench } from "lucide-react";+import { useTranslation } from "react-i18next";+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 { useSQLEditorStore, useSQLEditorTabStore } from "@/store";++type AdminModeButtonProps = {+ readonly size?: "sm" | "default";+ readonly hideText?: boolean;+};++/**+ * Replaces frontend/src/views/sql-editor/EditorCommon/AdminModeButton.vue.+ * Visible only when the user has admin permission AND the current tab is+ * in WORKSHEET mode. Clicking switches the tab to ADMIN mode.+ */+export function AdminModeButton({+ size = "default",+ hideText = false,+}: AdminModeButtonProps) {+ const { t } = useTranslation();+ const editorStore = useSQLEditorStore();+ const tabStore = useSQLEditorTabStore();++ const allowAdmin = useVueState(() => editorStore.allowAdmin);+ const currentTabMode = useVueState(() => tabStore.currentTab?.mode);+ const isDisconnected = useVueState(() => tabStore.isDisconnected);++ if (!allowAdmin || currentTabMode !== "WORKSHEET") {+ return null;+ }++ const label = t("sql-editor.admin-mode.self");++ const handleClick = () => {+ tabStore.updateCurrentTab({ mode: "ADMIN" });+ };++ return (+ <Tooltip content={label} side="bottom">+ <Button+ variant="outline"+ size={size}+ disabled={isDisconnected}+ onClick={handleClick}+ className={cn(+ "h-7 px-1.5 gap-1",+ "border-warning text-warning hover:bg-warning/5 hover:text-warning"+ )}+ >+ <Wrench className="size-4" />+ {!hideText && <span>{label}</span>}+ </Button>+ </Tooltip>+ );+}diff --git a/frontend/src/react/components/sql-editor/ChooserGroup.test.tsx b/frontend/src/react/components/sql-editor/ChooserGroup.test.tsxnew file mode 100644index 0000000000..5753a3f35c--- /dev/null+++ b/frontend/src/react/components/sql-editor/ChooserGroup.test.tsx@@ -0,0 +1,76 @@+import type { ReactElement } from "react";+import { act } 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;++vi.mock("./DatabaseChooser", () => ({+ DatabaseChooser: () => <div data-testid="database-chooser" />,+}));++vi.mock("./SchemaChooser", () => ({+ SchemaChooser: () => <div data-testid="schema-chooser" />,+}));++vi.mock("./ContainerChooser", () => ({+ ContainerChooser: () => <div data-testid="container-chooser" />,+}));++let ChooserGroup: typeof import("./ChooserGroup").ChooserGroup;++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();+ },+ };+};++beforeEach(async () => {+ vi.clearAllMocks();+ ({ ChooserGroup } = await import("./ChooserGroup"));+});++describe("ChooserGroup", () => {+ test("renders all three chooser components inside a flex wrapper", () => {+ const { container, render, unmount } = renderIntoContainer(+ <ChooserGroup />+ );+ render();+ expect(+ container.querySelector("[data-testid='database-chooser']")+ ).not.toBeNull();+ expect(+ container.querySelector("[data-testid='schema-chooser']")+ ).not.toBeNull();+ expect(+ container.querySelector("[data-testid='container-chooser']")+ ).not.toBeNull();+ unmount();+ });++ test("wraps choosers in a flex container", () => {+ const { container, render, unmount } = renderIntoContainer(+ <ChooserGroup />+ );+ render();+ const wrapper = container.firstElementChild as HTMLElement;+ expect(wrapper?.className).toContain("flex");+ unmount();+ });+});diff --git a/frontend/src/react/components/sql-editor/ChooserGroup.tsx b/frontend/src/react/components/sql-editor/ChooserGroup.tsxnew file mode 100644index 0000000000..1f9296a3b2--- /dev/null+++ b/frontend/src/react/components/sql-editor/ChooserGroup.tsx@@ -0,0 +1,18 @@+import { ContainerChooser } from "./ContainerChooser";+import { DatabaseChooser } from "./DatabaseChooser";+import { SchemaChooser } from "./SchemaChooser";++/**+ * Replaces the <NButtonGroup> wrapping the 3 connection choosers in+ * frontend/src/views/sql-editor/EditorCommon/EditorAction.vue (lines 125-129).+ * Mounted via <ReactPageMount page="ChooserGroup" /> from the Vue parent.+ */+export function ChooserGroup() {+ return (+ <div className="flex items-center">+ <DatabaseChooser />+ <SchemaChooser />+ <ContainerChooser />+ </div>+ );+}diff --git a/frontend/src/react/components/sql-editor/ConnectChooser.test.tsx b/frontend/src/react/components/sql-editor/ConnectChooser.test.tsxnew file mode 100644index 0000000000..658fa57f94--- /dev/null+++ b/frontend/src/react/components/sql-editor/ConnectChooser.test.tsx@@ -0,0 +1,164 @@+import type { ReactElement } from "react";+import { act } 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(() => ({+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),+ getLayerRoot: vi.fn(() => document.body),+}));++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/components/ui/layer", () => ({+ getLayerRoot: mocks.getLayerRoot,+ LAYER_SURFACE_CLASS: "layer-surface",+}));++vi.mock("@/react/components/ui/combobox-position", () => ({+ getPortalDropdownStyle: vi.fn(() => ({ top: 100, left: 0, width: 200 })),+ isPortalDropdownStyleEqual: vi.fn(() => true),+ shouldIgnorePortalDropdownScroll: vi.fn(() => false),+}));++vi.mock("@/react/components/ui/search-input", () => ({+ SearchInput: ({+ value,+ onChange,+ }: {+ value: string;+ onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;+ }) => <input data-testid="search" value={value} onChange={onChange} />,+}));++let ConnectChooser: typeof import("./ConnectChooser").ConnectChooser;++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 defaultOptions = [+ { value: "-1", label: "Unspecified" },+ { value: "public", label: "public" },+];++beforeEach(async () => {+ vi.clearAllMocks();+ ({ ConnectChooser } = await import("./ConnectChooser"));+});++describe("ConnectChooser", () => {+ test("renders placeholder text when isChosen=false", () => {+ const { container, render, unmount } = renderIntoContainer(+ <ConnectChooser+ value=""+ onChange={vi.fn()}+ options={defaultOptions}+ isChosen={false}+ placeholder="Select schema"+ />+ );+ render();+ expect(container.textContent).toContain("Select schema");+ unmount();+ });++ test("renders truncated value when isChosen=true", () => {+ const { container, render, unmount } = renderIntoContainer(+ <ConnectChooser+ value="public"+ onChange={vi.fn()}+ options={defaultOptions}+ isChosen={true}+ placeholder="Select schema"+ />+ );+ render();+ expect(container.textContent).toContain("public");+ unmount();+ });++ test("renders db.schema.default when isChosen=true but value is empty string", () => {+ const { container, render, unmount } = renderIntoContainer(+ <ConnectChooser+ value=""+ onChange={vi.fn()}+ options={defaultOptions}+ isChosen={true}+ placeholder="Select schema"+ />+ );+ render();+ // t() returns the key when mocked, so we get "db.schema.default"+ expect(container.textContent).toContain("db.schema.default");+ unmount();+ });++ test("Network icon is present in trigger", () => {+ const { container, render, unmount } = renderIntoContainer(+ <ConnectChooser+ value=""+ onChange={vi.fn()}+ options={defaultOptions}+ isChosen={false}+ placeholder="Select schema"+ />+ );+ render();+ const button = container.querySelector("button");+ expect(button).not.toBeNull();+ // Network icon renders as an svg+ expect(button?.querySelector("svg")).not.toBeNull();+ unmount();+ });++ test("onChange fires when an option is selected", () => {+ const onChange = vi.fn();+ const { container, render, unmount } = renderIntoContainer(+ <ConnectChooser+ value=""+ onChange={onChange}+ options={defaultOptions}+ isChosen={false}+ placeholder="Select schema"+ />+ );+ render();+ // Open the dropdown+ act(() => {+ container.querySelector("button")?.click();+ });+ // Find option buttons in the portal (document.body)+ const optionButtons = document.body.querySelectorAll(+ "button:not([aria-label])"+ );+ // Click first option+ act(() => {+ (optionButtons[0] as HTMLButtonElement)?.click();+ });+ expect(onChange).toHaveBeenCalled();+ unmount();+ });+});diff --git a/frontend/src/react/components/sql-editor/ConnectChooser.tsx b/frontend/src/react/components/sql-editor/ConnectChooser.tsxnew file mode 100644index 0000000000..5253af002c--- /dev/null+++ b/frontend/src/react/components/sql-editor/ConnectChooser.tsx@@ -0,0 +1,234 @@+import { Check, Network } from "lucide-react";+import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { createPortal } from "react-dom";+import { useTranslation } from "react-i18next";+import type { ComboboxOption } from "@/react/components/ui/combobox";+import {+ getPortalDropdownStyle,+ isPortalDropdownStyleEqual,+ shouldIgnorePortalDropdownScroll,+} from "@/react/components/ui/combobox-position";+import { getLayerRoot, LAYER_SURFACE_CLASS } from "@/react/components/ui/layer";+import { SearchInput } from "@/react/components/ui/search-input";+import { cn } from "@/react/lib/utils";++export type { ComboboxOption };++type ConnectChooserProps = {+ readonly value: string;+ readonly onChange: (value: string) => void;+ readonly options: ComboboxOption[];+ readonly isChosen: boolean;+ readonly placeholder: string;+};++/**+ * Replaces frontend/src/views/sql-editor/EditorCommon/ConnectChooser.vue.+ * Schema/Container chooser button used inside the SQL Editor toolbar's+ * NButtonGroup. Renders a chosen value (truncated) or a placeholder hint;+ * clicking opens a dropdown popover for selection.+ *+ * Note: uses a custom trigger button + portal dropdown rather than the+ * shared <Combobox> component, because <Combobox> does not expose a+ * renderTrigger prop for custom trigger styling.+ */+export function ConnectChooser({+ value,+ onChange,+ options,+ isChosen,+ placeholder,+}: ConnectChooserProps) {+ const { t } = useTranslation();+ const displayValue = value || t("db.schema.default");++ const [open, setOpen] = useState(false);+ const [search, setSearch] = useState("");+ const triggerRef = useRef<HTMLButtonElement>(null);+ const dropdownRef = useRef<HTMLDivElement>(null);+ const inputRef = useRef<HTMLInputElement>(null);+ const [dropdownStyle, setDropdownStyle] = useState<React.CSSProperties>({});++ const filteredOptions = useMemo(() => {+ if (!search) return options;+ const q = search.toLowerCase();+ return options.filter(+ (o) =>+ o.label.toLowerCase().includes(q) || o.value.toLowerCase().includes(q)+ );+ }, [options, search]);++ // Position dropdown in portal+ useLayoutEffect(() => {+ if (!open || !triggerRef.current) return;++ const updatePosition = () => {+ if (!triggerRef.current) return;+ const rect = triggerRef.current.getBoundingClientRect();+ const dropdownHeight = dropdownRef.current?.offsetHeight ?? 0;+ const nextStyle = getPortalDropdownStyle(+ rect,+ dropdownHeight,+ window.innerHeight+ );+ setDropdownStyle((prev) =>+ isPortalDropdownStyleEqual(prev, nextStyle) ? prev : nextStyle+ );+ };++ const handleScroll = (event: Event) => {+ if (shouldIgnorePortalDropdownScroll(event.target, dropdownRef.current)) {+ return;+ }+ updatePosition();+ };++ updatePosition();+ window.addEventListener("resize", updatePosition);+ window.addEventListener("scroll", handleScroll, true);+ return () => {+ window.removeEventListener("resize", updatePosition);+ window.removeEventListener("scroll", handleScroll, true);+ };+ }, [open]);++ // Click outside to close+ useEffect(() => {+ if (!open) return;+ const handler = (e: MouseEvent) => {+ const target = e.target as Node;+ if (triggerRef.current?.contains(target)) return;+ if (dropdownRef.current?.contains(target)) return;+ setOpen(false);+ setSearch("");+ };+ document.addEventListener("mousedown", handler);+ return () => document.removeEventListener("mousedown", handler);+ }, [open]);++ // Escape to close+ useEffect(() => {+ if (!open) return;+ const handler = (e: KeyboardEvent) => {+ if (e.key === "Escape") {+ setOpen(false);+ setSearch("");+ }+ };+ document.addEventListener("keydown", handler);+ return () => document.removeEventListener("keydown", handler);+ }, [open]);++ // Focus search input when opened+ useEffect(() => {+ if (open) {+ setTimeout(() => inputRef.current?.focus(), 10);+ }+ }, [open]);++ const handleSelect = useCallback(+ (optionValue: string) => {+ onChange(optionValue);+ setOpen(false);+ setSearch("");+ },+ [onChange]+ );++ const dropdownContent = (+ <div+ ref={dropdownRef}+ style={dropdownStyle}+ className={cn(+ "bg-background border border-control-border rounded-sm shadow-lg overflow-hidden",+ LAYER_SURFACE_CLASS+ )}+ >+ <SearchInput+ ref={inputRef}+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ wrapperClassName="m-2"+ className="h-7"+ />+ <div className="max-h-60 overflow-y-auto">+ {filteredOptions.length === 0 ? (+ <div className="px-3 py-6 text-sm text-control-placeholder text-center">+ —+ </div>+ ) : (+ filteredOptions.map((option) => {+ const isSelected = option.value === value;+ return (+ <button+ key={option.value}+ type="button"+ className={cn(+ "w-full text-left px-3 py-1.5 text-sm flex items-center gap-x-2 transition-colors",+ "hover:bg-control-bg",+ isSelected && "bg-accent/5"+ )}+ onClick={() => handleSelect(option.value)}+ >+ <span+ className={cn(+ "truncate flex-1",+ isSelected && "text-accent font-medium"+ )}+ >+ {option.label}+ </span>+ {isSelected && (+ <Check className="size-4 text-accent shrink-0" />+ )}+ </button>+ );+ })+ )}+ </div>+ </div>+ );++ return (+ <>+ <button+ ref={triggerRef}+ type="button"+ className={cn(+ "inline-flex items-center justify-end gap-1 px-2 h-8 text-sm",+ "border border-accent text-accent",+ "hover:bg-accent/5 focus:bg-accent/5",+ "rounded-none first:rounded-l-xs last:rounded-r-xs",+ "[&:not(:last-child)]:border-r-0",+ "transition-colors",+ isChosen ? "max-w-[12rem]" : "max-w-none"+ )}+ aria-label={placeholder}+ aria-expanded={open}+ onClick={() => setOpen((v) => !v)}+ >+ <Network+ className={cn(+ "size-4 shrink-0",+ isChosen ? "text-accent" : "text-control-placeholder"+ )}+ />+ {isChosen ? (+ <span className="truncate text-control">{displayValue}</span>+ ) : (+ <span className="text-control-placeholder whitespace-nowrap">+ {placeholder}+ </span>+ )}+ </button>+ {open && createPortal(dropdownContent, getLayerRoot("overlay"))}+ </>+ );+}diff --git a/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx b/frontend/src/react/components/sql-editor/ContainerChooser.test.tsxnew file mode 100644index 0000000000..ff04d8c005--- /dev/null+++ b/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx@@ -0,0 +1,196 @@+import type { ReactElement } from "react";+import { act } 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(() => ({+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ useSQLEditorTabStore: vi.fn(),+ useDBSchemaV1Store: vi.fn(),+ useConnectionOfCurrentSQLEditorTab: vi.fn(),+ router: {+ currentRoute: { value: { query: {} } },+ },+}));++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,+ useDBSchemaV1Store: mocks.useDBSchemaV1Store,+ useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,+}));++vi.mock("@/router", () => ({+ router: mocks.router,+}));++// Mock Engine enum+vi.mock("@/types/proto-es/v1/common_pb", () => ({+ Engine: { COSMOSDB: "COSMOSDB", MYSQL: "MYSQL" },+}));++vi.mock("./ConnectChooser", () => ({+ ConnectChooser: ({+ placeholder,+ options,+ isChosen,+ value,+ }: {+ placeholder: string;+ options: { value: string; label: string }[];+ isChosen: boolean;+ value: string;+ }) => (+ <div data-testid="connect-chooser">+ <span data-testid="placeholder">{placeholder}</span>+ <span data-testid="value">{value}</span>+ <span data-testid="is-chosen">{String(isChosen)}</span>+ {options.map((o) => (+ <span key={o.value} data-testid={`option-${o.value}`}>+ {o.label}+ </span>+ ))}+ </div>+ ),+}));++let ContainerChooser: typeof import("./ContainerChooser").ContainerChooser;++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 mockCosmosConnection = {+ instance: { value: { engine: "COSMOSDB" } },+ database: { value: { name: "instances/inst1/databases/cosmosdb" } },+};++const mockMySQLConnection = {+ instance: { value: { engine: "MYSQL" } },+ database: { value: { name: "instances/inst1/databases/db1" } },+};++beforeEach(async () => {+ vi.clearAllMocks();+ mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue(+ mockCosmosConnection+ );+ mocks.useSQLEditorTabStore.mockReturnValue({+ currentTab: { connection: { table: undefined } },+ });+ mocks.useDBSchemaV1Store.mockReturnValue({+ getDatabaseMetadata: vi.fn(() => ({+ schemas: [+ {+ name: "default",+ tables: [{ name: "container1" }, { name: "container2" }],+ },+ ],+ })),+ });+ mocks.useVueState.mockImplementation((getter) => getter());+ ({ ContainerChooser } = await import("./ContainerChooser"));+});++describe("ContainerChooser", () => {+ test("renders nothing when engine is not COSMOSDB", () => {+ mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue(+ mockMySQLConnection+ );+ const { container, render, unmount } = renderIntoContainer(+ <ContainerChooser />+ );+ render();+ expect(+ container.querySelector("[data-testid='connect-chooser']")+ ).toBeNull();+ unmount();+ });++ test("renders ConnectChooser when engine is COSMOSDB", () => {+ const { container, render, unmount } = renderIntoContainer(+ <ContainerChooser />+ );+ render();+ expect(+ container.querySelector("[data-testid='connect-chooser']")+ ).not.toBeNull();+ unmount();+ });++ test("options include unspecified entry and all table names", () => {+ const { container, render, unmount } = renderIntoContainer(+ <ContainerChooser />+ );+ render();+ // Unspecified option+ expect(container.querySelector("[data-testid='option--1']")).not.toBeNull();+ // Table names from mock+ expect(+ container.querySelector("[data-testid='option-container1']")+ ).not.toBeNull();+ expect(+ container.querySelector("[data-testid='option-container2']")+ ).not.toBeNull();+ unmount();+ });++ test("is not chosen when no table is selected", () => {+ const { container, render, unmount } = renderIntoContainer(+ <ContainerChooser />+ );+ render();+ expect(+ container.querySelector("[data-testid='is-chosen']")?.textContent+ ).toBe("false");+ unmount();+ });++ test("is chosen when a table is selected", () => {+ const tab = { connection: { table: "container1" } };+ mocks.useSQLEditorTabStore.mockReturnValue({ currentTab: tab });+ let callIdx = 0;+ mocks.useVueState.mockImplementation((getter) => {+ callIdx++;+ // 1: engine, 2: databaseName, 3: tabTable, 4: schemas, 5: queryParam+ if (callIdx === 3) return "container1";+ return getter();+ });+ const { container, render, unmount } = renderIntoContainer(+ <ContainerChooser />+ );+ render();+ expect(+ container.querySelector("[data-testid='is-chosen']")?.textContent+ ).toBe("true");+ unmount();+ });+});diff --git a/frontend/src/react/components/sql-editor/ContainerChooser.tsx b/frontend/src/react/components/sql-editor/ContainerChooser.tsxnew file mode 100644index 0000000000..26d5c49175--- /dev/null+++ b/frontend/src/react/components/sql-editor/ContainerChooser.tsx@@ -0,0 +1,86 @@+import { useEffect, useMemo } from "react";+import { useTranslation } from "react-i18next";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import {+ useConnectionOfCurrentSQLEditorTab,+ useDBSchemaV1Store,+ useSQLEditorTabStore,+} from "@/store";+import { Engine } from "@/types/proto-es/v1/common_pb";+import { ConnectChooser } from "./ConnectChooser";++const OptionValueUnspecified = "-1";++/**+ * Replaces frontend/src/views/sql-editor/EditorCommon/ContainerChooser.vue.+ * Visible only for CosmosDB databases (container = table in CosmosDB).+ * Selected container persists to the current tab's connection.table.+ */+export function ContainerChooser() {+ const { t } = useTranslation();+ const tabStore = useSQLEditorTabStore();+ const dbSchemaStore = useDBSchemaV1Store();+ const connection = useConnectionOfCurrentSQLEditorTab();++ const engine = useVueState(() => connection.instance.value.engine);+ const databaseName = useVueState(() => connection.database.value.name);+ const tabTable = useVueState(() => tabStore.currentTab?.connection.table);+ const schemas = useVueState(+ () => dbSchemaStore.getDatabaseMetadata(databaseName).schemas+ );++ const show = engine === Engine.COSMOSDB;++ const options = useMemo(() => {+ const opts = [+ {+ value: OptionValueUnspecified,+ label: t("database.schema.unspecified"),+ },+ ];+ for (const schema of schemas) {+ for (const table of schema.tables) {+ opts.push({ value: table.name, label: table.name });+ }+ }+ return opts;+ }, [schemas, t]);++ const value = tabTable === undefined ? OptionValueUnspecified : tabTable;+ const isChosen = value !== OptionValueUnspecified;++ const handleChange = (next: string) => {+ if (!tabStore.currentTab) return;+ tabStore.currentTab.connection.table =+ next === OptionValueUnspecified ? undefined : next;+ };++ // Seed from URL query parameter on mount and whenever the query param OR+ // the active tab changes. Mirrors Vue's watchEffect, which implicitly+ // tracked both `route.query.table` and `tab.value` (the latter via the+ // setter's reactive reads) so that switching to a new tab with the URL+ // query still present re-seeded the new tab's connection.table.+ const queryParam = useVueState(+ () => router.currentRoute.value.query.table as string | undefined+ );+ const currentTabId = useVueState(() => tabStore.currentTab?.id);+ // biome-ignore lint/correctness/useExhaustiveDependencies: handleChange is+ // defined inline and reads the live tabStore; omitting it is intentional+ // so the effect re-runs only on queryParam or tab switch.+ useEffect(() => {+ if (queryParam) handleChange(queryParam);+ }, [queryParam, currentTabId]);++ if (!show) return null;++ return (+ <ConnectChooser+ value={value}+ onChange={handleChange}+ options={options}+ isChosen={isChosen}+ placeholder={t("database.table.select")}+ />+ );+}diff --git a/frontend/src/react/components/sql-editor/DatabaseChooser.test.tsx b/frontend/src/react/components/sql-editor/DatabaseChooser.test.tsxnew file mode 100644index 0000000000..150041c24a--- /dev/null+++ b/frontend/src/react/components/sql-editor/DatabaseChooser.test.tsx@@ -0,0 +1,175 @@+import type { ReactElement } from "react";+import { act } 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(() => ({+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ useSQLEditorTabStore: vi.fn(),+ useSQLEditorStore: vi.fn(),+ useSQLEditorUIStore: vi.fn(),+ useConnectionOfCurrentSQLEditorTab: vi.fn(),+ isValidInstanceName: vi.fn(),+ isValidDatabaseName: vi.fn(),+ extractDatabaseResourceName: vi.fn(),+ getDatabaseEnvironment: vi.fn(),+ getInstanceResource: vi.fn(),+ EngineIconPath: {} as Record<string, string>,+}));++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,+ useSQLEditorStore: mocks.useSQLEditorStore,+ useSQLEditorUIStore: mocks.useSQLEditorUIStore,+ useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,+}));++vi.mock("@/types", () => ({+ isValidInstanceName: mocks.isValidInstanceName,+ isValidDatabaseName: mocks.isValidDatabaseName,+}));++vi.mock("@/utils", () => ({+ extractDatabaseResourceName: mocks.extractDatabaseResourceName,+ getDatabaseEnvironment: mocks.getDatabaseEnvironment,+ getInstanceResource: mocks.getInstanceResource,+}));++vi.mock("@/components/InstanceForm/constants", () => ({+ EngineIconPath: mocks.EngineIconPath,+}));++vi.mock("@/react/components/EnvironmentLabel", () => ({+ EnvironmentLabel: ({ environmentName }: { environmentName: string }) => (+ <span data-testid="env-label">{environmentName}</span>+ ),+}));++vi.mock("@/react/components/ui/tooltip", () => ({+ Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}));++let DatabaseChooser: typeof import("./DatabaseChooser").DatabaseChooser;++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 mockDatabase = { name: "instances/inst1/databases/mydb", engine: 0 };+const mockInstance = {+ name: "instances/inst1",+ title: "My Instance",+ engine: 0,+};+const mockEnvironment = { name: "environments/prod" };++beforeEach(async () => {+ vi.clearAllMocks();+ mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue({+ database: { value: mockDatabase },+ instance: { value: mockInstance },+ });+ mocks.useSQLEditorTabStore.mockReturnValue({+ currentTab: { id: "tab1" },+ isInBatchMode: false,+ });+ mocks.useSQLEditorStore.mockReturnValue({ projectContextReady: true });+ mocks.useSQLEditorUIStore.mockReturnValue({ showConnectionPanel: false });+ mocks.isValidInstanceName.mockReturnValue(true);+ mocks.isValidDatabaseName.mockReturnValue(true);+ mocks.getInstanceResource.mockReturnValue(mockInstance);+ mocks.getDatabaseEnvironment.mockReturnValue(mockEnvironment);+ mocks.extractDatabaseResourceName.mockReturnValue({ databaseName: "mydb" });+ mocks.useVueState.mockImplementation((getter) => getter());+ ({ DatabaseChooser } = await import("./DatabaseChooser"));+});++describe("DatabaseChooser", () => {+ test("renders placeholder when no valid connection", () => {+ mocks.isValidInstanceName.mockReturnValue(false);+ mocks.isValidDatabaseName.mockReturnValue(false);+ const { container, render, unmount } = renderIntoContainer(+ <DatabaseChooser />+ );+ render();+ expect(container.textContent).toContain(+ "sql-editor.select-a-database-to-start"+ );+ unmount();+ });++ test("renders breadcrumb with env label and instance title and database name when connected", () => {+ const { container, render, unmount } = renderIntoContainer(+ <DatabaseChooser />+ );+ render();+ expect(container.querySelector("[data-testid='env-label']")).not.toBeNull();+ expect(container.textContent).toContain("My Instance");+ expect(container.textContent).toContain("mydb");+ unmount();+ });++ test("button is disabled when disabled prop is true", () => {+ const { container, render, unmount } = renderIntoContainer(+ <DatabaseChooser disabled={true} />+ );+ render();+ const button = container.querySelector("button");+ expect(button?.hasAttribute("disabled")).toBe(true);+ unmount();+ });++ test("button is disabled when projectContextReady is false", () => {+ mocks.useSQLEditorStore.mockReturnValue({ projectContextReady: false });+ const { container, render, unmount } = renderIntoContainer(+ <DatabaseChooser />+ );+ render();+ const button = container.querySelector("button");+ expect(button?.hasAttribute("disabled")).toBe(true);+ unmount();+ });++ test("click sets showConnectionPanel to true on UI store", () => {+ const uiStore = { showConnectionPanel: false };+ mocks.useSQLEditorUIStore.mockReturnValue(uiStore);+ const { container, render, unmount } = renderIntoContainer(+ <DatabaseChooser />+ );+ render();+ act(() => {+ container.querySelector("button")?.click();+ });+ expect(uiStore.showConnectionPanel).toBe(true);+ unmount();+ });+});diff --git a/frontend/src/react/components/sql-editor/DatabaseChooser.tsx b/frontend/src/react/components/sql-editor/DatabaseChooser.tsxnew file mode 100644index 0000000000..7dc0e3c947--- /dev/null+++ b/frontend/src/react/components/sql-editor/DatabaseChooser.tsx@@ -0,0 +1,100 @@+import { ChevronRight, Database, SquareStack } from "lucide-react";+import { useTranslation } from "react-i18next";+import { EngineIconPath } from "@/components/InstanceForm/constants";+import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";+import { Tooltip } from "@/react/components/ui/tooltip";+import { useVueState } from "@/react/hooks/useVueState";+import { cn } from "@/react/lib/utils";+import {+ useConnectionOfCurrentSQLEditorTab,+ useSQLEditorStore,+ useSQLEditorTabStore,+ useSQLEditorUIStore,+} from "@/store";+import { isValidDatabaseName, isValidInstanceName } from "@/types";+import {+ extractDatabaseResourceName,+ getDatabaseEnvironment,+ getInstanceResource,+} from "@/utils";++type DatabaseChooserProps = {+ readonly disabled?: boolean;+};++/**+ * Replaces frontend/src/views/sql-editor/EditorCommon/DatabaseChooser.vue.+ * Breadcrumb-style chooser showing the current connection+ * (Environment > Instance > Database). Click opens the connection panel.+ */+export function DatabaseChooser({ disabled = false }: DatabaseChooserProps) {+ const { t } = useTranslation();+ const tabStore = useSQLEditorTabStore();+ const editorStore = useSQLEditorStore();+ const uiStore = useSQLEditorUIStore();+ const connection = useConnectionOfCurrentSQLEditorTab();++ const currentTab = useVueState(() => tabStore.currentTab);+ const isInBatchMode = useVueState(() => tabStore.isInBatchMode);+ const projectContextReady = useVueState(+ () => editorStore.projectContextReady+ );+ const database = useVueState(() => connection.database.value);++ const instance = getInstanceResource(database);+ const environment = getDatabaseEnvironment(database);+ const databaseName = extractDatabaseResourceName(database.name).databaseName;++ const isConnected =+ !!currentTab &&+ isValidInstanceName(instance.name) &&+ isValidDatabaseName(database.name);++ const handleClick = () => {+ uiStore.showConnectionPanel = true;+ };++ return (+ <button+ type="button"+ disabled={disabled || !projectContextReady}+ onClick={handleClick}+ className={cn(+ "inline-flex items-center justify-end gap-1 px-2 h-8 text-sm",+ "border border-accent text-accent",+ "hover:bg-accent/5 focus:bg-accent/5",+ "rounded-none first:rounded-l-xs last:rounded-r-xs",+ "[&:not(:last-child)]:border-r-0",+ "disabled:opacity-50 disabled:cursor-not-allowed",+ "transition-colors overflow-hidden"+ )}+ >+ {isConnected ? (+ <div className="flex flex-row items-center text-control truncate">+ {isInBatchMode && (+ <Tooltip content={t("sql-editor.batch-query.batch")}>+ <SquareStack className="size-4 mr-1 text-accent" />+ </Tooltip>+ )}+ <EnvironmentLabel environmentName={environment.name} />+ <ChevronRight className="size-4 shrink-0 text-control-light" />+ <div className="flex items-center gap-1">+ <img+ className="size-4 shrink-0"+ src={EngineIconPath[instance.engine]}+ alt=""+ />+ <span className="truncate">{instance.title}</span>+ </div>+ <ChevronRight className="size-4 shrink-0 text-control-light" />+ <div className="flex items-center gap-1 truncate">+ <Database className="size-4 shrink-0" />+ <span className="truncate">{databaseName}</span>+ </div>+ </div>+ ) : (+ <span>{t("sql-editor.select-a-database-to-start")}</span>+ )}+ </button>+ );+}diff --git a/frontend/src/react/components/sql-editor/QueryContextSettingPopover.test.tsx b/frontend/src/react/components/sql-editor/QueryContextSettingPopover.test.tsxnew file mode 100644index 0000000000..5fff8facaf--- /dev/null+++ b/frontend/src/react/components/sql-editor/QueryContextSettingPopover.test.tsx@@ -0,0 +1,262 @@+import type { ReactElement } from "react";+import { act } 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;++const mocks = vi.hoisted(() => ({+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ useSQLEditorTabStore: vi.fn(),+ useSQLEditorStore: vi.fn(),+ useConnectionOfCurrentSQLEditorTab: vi.fn(),+ getInstanceResource: vi.fn(),+ readableDataSourceType: vi.fn((type: number) => `type-${type}`),+ orderBy: vi.fn((arr: unknown[]) => arr),+}));++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,+ useSQLEditorStore: mocks.useSQLEditorStore,+ useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,+}));++vi.mock("@/utils", () => ({+ getInstanceResource: mocks.getInstanceResource,+ readableDataSourceType: mocks.readableDataSourceType,+}));++vi.mock("lodash-es", () => ({+ orderBy: mocks.orderBy,+}));++// Inline Popover and Tooltip so the popover content renders synchronously+vi.mock("@/react/components/ui/popover", () => ({+ Popover: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="popover">{children}</div>+ ),+ PopoverTrigger: ({+ children,+ render: renderEl,+ }: {+ children?: React.ReactNode;+ render?: React.ReactElement;+ }) => (+ <div data-testid="popover-trigger">+ {renderEl ? renderEl : null}+ {children}+ </div>+ ),+ PopoverContent: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="popover-content">{children}</div>+ ),+}));++vi.mock("@/react/components/ui/tooltip", () => ({+ Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}));++vi.mock("@/react/components/MaxRowCountSelect", () => ({+ MaxRowCountSelect: ({+ value,+ onChange,+ }: {+ value: number;+ onChange: (n: number) => void;+ }) => (+ <div data-testid="max-row-count-select">+ <button type="button" onClick={() => onChange(500)} data-value={value}>+ row-count+ </button>+ </div>+ ),+}));++let QueryContextSettingPopover: typeof import("./QueryContextSettingPopover").QueryContextSettingPopover;++const mockInstance = {+ engine: 0, // Not REDIS (Engine.REDIS = 8)+ dataSources: [+ {+ id: "ds-admin",+ type: 0 /* ADMIN */,+ username: "admin-user",+ redisType: 0,+ },+ { id: "ds-ro", type: 1 /* READ_ONLY */, username: "ro-user", redisType: 0 },+ ],+};++const mockConnection = {+ database: "instances/inst1/databases/mydb",+ instance: "instances/inst1",+};++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();+ },+ };+};++beforeEach(async () => {+ vi.clearAllMocks();++ mocks.useTranslation.mockReturnValue({ t: (key: string) => key });+ mocks.getInstanceResource.mockReturnValue(mockInstance);+ mocks.orderBy.mockImplementation((arr: unknown[]) => arr);++ mocks.useSQLEditorTabStore.mockReturnValue({+ currentTab: { mode: "WORKSHEET" },+ updateCurrentTab: vi.fn(),+ });+ mocks.useSQLEditorStore.mockReturnValue({+ resultRowsLimit: 1000,+ redisCommandOption: 0,+ queryDataPolicy: {+ allowAdminDataSource: true,+ maximumResultRows: Number.MAX_VALUE,+ },+ });+ mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue({+ database: { value: { name: "instances/inst1/databases/mydb" } },+ connection: { value: mockConnection },+ });++ mocks.useVueState.mockImplementation((getter: () => unknown) => getter());++ ({ QueryContextSettingPopover } = await import(+ "./QueryContextSettingPopover"+ ));+});++afterEach(() => {+ document.body.innerHTML = "";+});++describe("QueryContextSettingPopover", () => {+ test("returns null when current tab mode is ADMIN", () => {+ mocks.useSQLEditorTabStore.mockReturnValue({+ currentTab: { mode: "ADMIN" },+ updateCurrentTab: vi.fn(),+ });+ const { container, render, unmount } = renderIntoContainer(+ <QueryContextSettingPopover />+ );+ render();+ expect(container.querySelector("[data-testid='popover']")).toBeNull();+ unmount();+ });++ test("renders trigger button with ChevronDown when mode is not ADMIN", () => {+ const { container, render, unmount } = renderIntoContainer(+ <QueryContextSettingPopover />+ );+ render();+ expect(container.querySelector("[data-testid='popover']")).not.toBeNull();+ // The SVG icon (ChevronDown) should be present somewhere in the trigger+ expect(container.querySelector("svg")).not.toBeNull();+ unmount();+ });++ test("renders data source options from instance.dataSources", () => {+ const { container, render, unmount } = renderIntoContainer(+ <QueryContextSettingPopover />+ );+ render();+ const content = container.querySelector("[data-testid='popover-content']");+ // Should have radio inputs for each data source + automatic+ const radios = content?.querySelectorAll("input[type='radio']") ?? [];+ // automatic + 2 data sources = 3+ expect(radios.length).toBeGreaterThanOrEqual(3);+ unmount();+ });++ test("clicking a data source label calls tabStore.updateCurrentTab with updated connection", () => {+ const updateCurrentTab = vi.fn();+ mocks.useSQLEditorTabStore.mockReturnValue({+ currentTab: { mode: "WORKSHEET" },+ updateCurrentTab,+ });+ const { container, render, unmount } = renderIntoContainer(+ <QueryContextSettingPopover />+ );+ render();+ const content = container.querySelector("[data-testid='popover-content']");+ const labels = Array.from(content?.querySelectorAll("label") ?? []);+ // Second label is first real data source (ds-admin), first is "Automatic"+ const dsLabel = labels[1] as HTMLLabelElement;+ act(() => {+ // React synthetic events fire from direct click; native click triggers the label+ // which causes the radio's onChange to fire via React's synthetic event delegation.+ dsLabel.click();+ });+ expect(updateCurrentTab).toHaveBeenCalled();+ unmount();+ });++ test("Redis sub-group does not render when engine is not REDIS", () => {+ const { container, render, unmount } = renderIntoContainer(+ <QueryContextSettingPopover />+ );+ render();+ const content = container.querySelector("[data-testid='popover-content']");+ const redisRadios =+ content?.querySelectorAll("input[name='redis-command']") ?? [];+ expect(redisRadios.length).toBe(0);+ unmount();+ });++ test("Redis sub-group renders when engine is REDIS", () => {+ // Engine.REDIS = 8 (from common_pb.d.ts)+ mocks.getInstanceResource.mockReturnValue({+ ...mockInstance,+ engine: 8,+ });+ const { container, render, unmount } = renderIntoContainer(+ <QueryContextSettingPopover />+ );+ render();+ const content = container.querySelector("[data-testid='popover-content']");+ const redisRadios =+ content?.querySelectorAll("input[name='redis-command']") ?? [];+ expect(redisRadios.length).toBe(2);+ unmount();+ });++ test("MaxRowCountSelect renders inside popover content", () => {+ const { container, render, unmount } = renderIntoContainer(+ <QueryContextSettingPopover />+ );+ render();+ const content = container.querySelector("[data-testid='popover-content']");+ expect(+ content?.querySelector("[data-testid='max-row-count-select']")+ ).not.toBeNull();+ unmount();+ });+});diff --git a/frontend/src/react/components/sql-editor/QueryContextSettingPopover.tsx b/frontend/src/react/components/sql-editor/QueryContextSettingPopover.tsxnew file mode 100644index 0000000000..f2d37a4383--- /dev/null+++ b/frontend/src/react/components/sql-editor/QueryContextSettingPopover.tsx@@ -0,0 +1,247 @@+import { orderBy } from "lodash-es";+import { ChevronDown } from "lucide-react";+import { useMemo } from "react";+import { useTranslation } from "react-i18next";+import { MaxRowCountSelect } from "@/react/components/MaxRowCountSelect";+import { Button } from "@/react/components/ui/button";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/react/components/ui/popover";+import { Tooltip } from "@/react/components/ui/tooltip";+import { useVueState } from "@/react/hooks/useVueState";+import { cn } from "@/react/lib/utils";+import {+ useConnectionOfCurrentSQLEditorTab,+ useSQLEditorStore,+ useSQLEditorTabStore,+} from "@/store";+import { Engine } from "@/types/proto-es/v1/common_pb";+import type { DataSource } from "@/types/proto-es/v1/instance_service_pb";+import {+ DataSource_RedisType,+ DataSourceType,+} from "@/types/proto-es/v1/instance_service_pb";+import { QueryOption_RedisRunCommandsOn } from "@/types/proto-es/v1/sql_service_pb";+import { getInstanceResource, readableDataSourceType } from "@/utils";++type Props = {+ readonly disabled?: boolean;+};++/**+ * Replaces frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue.+ * Popover for selecting query data source, Redis command mode, and max row count.+ */+export function QueryContextSettingPopover({ disabled = false }: Props) {+ const { t } = useTranslation();+ const tabStore = useSQLEditorTabStore();+ const editorStore = useSQLEditorStore();+ const connection = useConnectionOfCurrentSQLEditorTab();++ const currentTabMode = useVueState(() => tabStore.currentTab?.mode);+ const database = useVueState(() => connection.database.value);+ const connectionRef = useVueState(() => connection.connection.value);+ const resultRowsLimit = useVueState(() => editorStore.resultRowsLimit);+ const redisCommandOption = useVueState(() => editorStore.redisCommandOption);+ const queryDataPolicy = useVueState(() => editorStore.queryDataPolicy);++ const show = currentTabMode !== "ADMIN";++ const instance = useMemo(() => getInstanceResource(database), [database]);++ const showRedisConfig = useMemo(+ () => instance.engine === Engine.REDIS,+ [instance]+ );++ const selectedDataSourceId = useMemo(+ () => connectionRef?.dataSourceId ?? "",+ [connectionRef]+ );++ const dataSources = useMemo(+ () => orderBy(instance.dataSources, "type"),+ [instance]+ );++ const selectedDataSource = useMemo(+ () => instance.dataSources.find((ds) => ds.id === selectedDataSourceId),+ [instance, selectedDataSourceId]+ );++ const dataSourceUnaccessibleReason = (+ dataSource: DataSource+ ): string | undefined => {+ if (!queryDataPolicy || queryDataPolicy.allowAdminDataSource) {+ return undefined;+ }+ if (dataSource.type !== DataSourceType.ADMIN) {+ return undefined;+ }+ const readOnlyDataSources = dataSources.filter(+ (ds) => ds.type === DataSourceType.READ_ONLY+ );+ if (readOnlyDataSources.length === 0) {+ return undefined;+ }+ return t(+ "sql-editor.query-context.admin-data-source-is-disallowed-to-query"+ );+ };++ const onDataSourceSelected = (dataSourceId: string) => {+ if (!connectionRef) return;+ const nextConnection = { ...connectionRef };+ if (dataSourceId) {+ nextConnection.dataSourceId = dataSourceId;+ } else {+ delete nextConnection.dataSourceId;+ }+ tabStore.updateCurrentTab({ connection: nextConnection });+ };++ if (!show) return null;++ return (+ <Popover>+ <PopoverTrigger+ render={+ <Button+ variant="default"+ size="sm"+ disabled={disabled}+ className={cn("h-7 px-1 gap-0", "rounded-none rounded-r-xs")}+ />+ }+ >+ <ChevronDown className="size-4" />+ </PopoverTrigger>+ <PopoverContent side="bottom" align="end">+ <div className="flex flex-col gap-1">+ {/* Data source radio group */}+ <div>+ <p className="mb-1 textinfolabel">+ {t("data-source.select-query-data-source")}+ </p>+ <div className="max-w-44 flex flex-col gap-1">+ <label className="flex items-center gap-2 cursor-pointer">+ <input+ type="radio"+ name="data-source"+ checked={selectedDataSourceId === ""}+ onChange={() => onDataSourceSelected("")}+ />+ <span>{t("data-source.automatic-query-data-source")}</span>+ </label>+ {dataSources.map((ds) => {+ const reason = dataSourceUnaccessibleReason(ds);+ const radio = (+ <label className="flex items-center gap-2 cursor-pointer">+ <input+ type="radio"+ name="data-source"+ checked={selectedDataSourceId === ds.id}+ disabled={Boolean(reason)}+ onChange={() => onDataSourceSelected(ds.id)}+ />+ <div className="max-w-36 flex items-center">+ <span className="text-xs opacity-60 shrink-0">+ {readableDataSourceType(ds.type)}+ </span>+ <span className="ml-1 truncate">{ds.username}</span>+ </div>+ </label>+ );+ return reason ? (+ <Tooltip key={ds.id} content={reason} side="right">+ {radio}+ </Tooltip>+ ) : (+ <div key={ds.id}>{radio}</div>+ );+ })}+ </div>+ </div>++ {/* Redis cluster config */}+ {showRedisConfig && (+ <Tooltip+ content={+ selectedDataSource?.redisType === DataSource_RedisType.CLUSTER+ ? null+ : t("sql-editor.redis-command.only-for-cluster")+ }+ side="right"+ >+ <div className="border-t pt-1">+ <p className="mb-1 textinfolabel">+ {t("sql-editor.redis-command.self")}+ </p>+ <div+ className="max-w-44 flex flex-col gap-1"+ aria-disabled={+ selectedDataSource?.redisType !==+ DataSource_RedisType.CLUSTER+ }+ >+ <label className="flex items-center gap-2 cursor-pointer">+ <input+ type="radio"+ name="redis-command"+ disabled={+ selectedDataSource?.redisType !==+ DataSource_RedisType.CLUSTER+ }+ checked={+ redisCommandOption ===+ QueryOption_RedisRunCommandsOn.SINGLE_NODE+ }+ onChange={() => {+ editorStore.redisCommandOption =+ QueryOption_RedisRunCommandsOn.SINGLE_NODE;+ }}+ />+ <span>{t("sql-editor.redis-command.single-node")}</span>+ </label>+ <label className="flex items-center gap-2 cursor-pointer">+ <input+ type="radio"+ name="redis-command"+ disabled={+ selectedDataSource?.redisType !==+ DataSource_RedisType.CLUSTER+ }+ checked={+ redisCommandOption ===+ QueryOption_RedisRunCommandsOn.ALL_NODES+ }+ onChange={() => {+ editorStore.redisCommandOption =+ QueryOption_RedisRunCommandsOn.ALL_NODES;+ }}+ />+ <span>{t("sql-editor.redis-command.all-nodes")}</span>+ </label>+ </div>+ </div>+ </Tooltip>+ )}++ {/* Max row count */}+ <div className="border-t pt-1">+ <MaxRowCountSelect+ value={resultRowsLimit ?? 1000}+ onChange={(n) => {+ editorStore.resultRowsLimit = n;+ }}+ maximum={queryDataPolicy?.maximumResultRows ?? Number.MAX_VALUE}+ quaternary+ />+ </div>+ </div>+ </PopoverContent>+ </Popover>+ );+}diff --git a/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx b/frontend/src/react/components/sql-editor/SchemaChooser.test.tsxnew file mode 100644index 0000000000..a904c03a75--- /dev/null+++ b/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx@@ -0,0 +1,177 @@+import type { ReactElement } from "react";+import { act } 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(() => ({+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ useSQLEditorTabStore: vi.fn(),+ useDBSchemaV1Store: vi.fn(),+ useConnectionOfCurrentSQLEditorTab: vi.fn(),+ instanceAllowsSchemaScopedQuery: vi.fn(),+ router: {+ currentRoute: { value: { query: {} } },+ },+}));++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/hooks/useVueState", () => ({+ useVueState: mocks.useVueState,+}));++vi.mock("@/store", () => ({+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,+ useDBSchemaV1Store: mocks.useDBSchemaV1Store,+ useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,+}));++vi.mock("@/utils", () => ({+ instanceAllowsSchemaScopedQuery: mocks.instanceAllowsSchemaScopedQuery,+}));++vi.mock("@/router", () => ({+ router: mocks.router,+}));++vi.mock("./ConnectChooser", () => ({+ ConnectChooser: ({+ placeholder,+ options,+ isChosen,+ value,+ }: {+ placeholder: string;+ options: { value: string; label: string }[];+ isChosen: boolean;+ value: string;+ }) => (+ <div data-testid="connect-chooser">+ <span data-testid="placeholder">{placeholder}</span>+ <span data-testid="value">{value}</span>+ <span data-testid="is-chosen">{String(isChosen)}</span>+ {options.map((o) => (+ <span key={o.value} data-testid={`option-${o.value}`}>+ {o.label}+ </span>+ ))}+ </div>+ ),+}));++let SchemaChooser: typeof import("./SchemaChooser").SchemaChooser;++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 mockConnection = {+ instance: { value: { engine: "MYSQL" } },+ database: { value: { name: "instances/inst1/databases/db1" } },+};++beforeEach(async () => {+ vi.clearAllMocks();+ mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue(mockConnection);+ mocks.useSQLEditorTabStore.mockReturnValue({+ currentTab: { connection: { schema: undefined } },+ });+ mocks.useDBSchemaV1Store.mockReturnValue({+ getDatabaseMetadata: vi.fn(() => ({+ schemas: [{ name: "public" }, { name: "private" }],+ })),+ });+ mocks.useVueState.mockImplementation((getter) => getter());+ mocks.instanceAllowsSchemaScopedQuery.mockReturnValue(true);+ ({ SchemaChooser } = await import("./SchemaChooser"));+});++describe("SchemaChooser", () => {+ test("renders nothing when engine does not allow schema-scoped queries", () => {+ mocks.instanceAllowsSchemaScopedQuery.mockReturnValue(false);+ const { container, render, unmount } = renderIntoContainer(+ <SchemaChooser />+ );+ render();+ expect(+ container.querySelector("[data-testid='connect-chooser']")+ ).toBeNull();+ unmount();+ });++ test("renders ConnectChooser when engine supports schemas", () => {+ mocks.instanceAllowsSchemaScopedQuery.mockReturnValue(true);+ const { container, render, unmount } = renderIntoContainer(+ <SchemaChooser />+ );+ render();+ expect(+ container.querySelector("[data-testid='connect-chooser']")+ ).not.toBeNull();+ unmount();+ });++ test("options include unspecified entry and each schema name", () => {+ const { container, render, unmount } = renderIntoContainer(+ <SchemaChooser />+ );+ render();+ // Unspecified option+ expect(container.querySelector("[data-testid='option--1']")).not.toBeNull();+ // Schema names from mock+ expect(+ container.querySelector("[data-testid='option-public']")+ ).not.toBeNull();+ expect(+ container.querySelector("[data-testid='option-private']")+ ).not.toBeNull();+ unmount();+ });++ test("selecting unspecified sets tab.connection.schema to undefined", () => {+ const tab = { connection: { schema: "public" } };+ mocks.useSQLEditorTabStore.mockReturnValue({ currentTab: tab });++ // Import fresh copy with updated mock+ let callIdx = 0;+ mocks.useVueState.mockImplementation((getter) => {+ callIdx++;+ // 1: engine, 2: databaseName, 3: tabSchema, 4: schemas, 5: queryParam+ if (callIdx === 3) return "public";+ return getter();+ });++ const { container, render, unmount } = renderIntoContainer(+ <SchemaChooser />+ );+ render();+ // Value should be "public" (non-unspecified)+ expect(+ container.querySelector("[data-testid='is-chosen']")?.textContent+ ).toBe("true");+ unmount();+ });+});diff --git a/frontend/src/react/components/sql-editor/SchemaChooser.tsx b/frontend/src/react/components/sql-editor/SchemaChooser.tsxnew file mode 100644index 0000000000..cb13fd977f--- /dev/null+++ b/frontend/src/react/components/sql-editor/SchemaChooser.tsx@@ -0,0 +1,86 @@+import { useEffect, useMemo } from "react";+import { useTranslation } from "react-i18next";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import {+ useConnectionOfCurrentSQLEditorTab,+ useDBSchemaV1Store,+ useSQLEditorTabStore,+} from "@/store";+import { instanceAllowsSchemaScopedQuery } from "@/utils";+import { ConnectChooser } from "./ConnectChooser";++const SchemaOptionValueUnspecified = "-1";++/**+ * Replaces frontend/src/views/sql-editor/EditorCommon/SchemaChooser.vue.+ * Visible only for engines that support schema-scoped queries.+ * Selected schema persists to the current tab's connection.schema.+ */+export function SchemaChooser() {+ const { t } = useTranslation();+ const tabStore = useSQLEditorTabStore();+ const dbSchemaStore = useDBSchemaV1Store();+ const connection = useConnectionOfCurrentSQLEditorTab();++ const engine = useVueState(() => connection.instance.value.engine);+ const databaseName = useVueState(() => connection.database.value.name);+ const tabSchema = useVueState(() => tabStore.currentTab?.connection.schema);+ const schemas = useVueState(+ () => dbSchemaStore.getDatabaseMetadata(databaseName).schemas+ );++ const show = instanceAllowsSchemaScopedQuery(engine);++ const options = useMemo(() => {+ const opts = schemas.map((schema) => ({+ value: schema.name,+ label: schema.name || t("db.schema.default"),+ }));+ return [+ {+ value: SchemaOptionValueUnspecified,+ label: t("database.schema.unspecified"),+ },+ ...opts,+ ];+ }, [schemas, t]);++ const value =+ tabSchema === undefined ? SchemaOptionValueUnspecified : tabSchema;+ const isChosen = value !== SchemaOptionValueUnspecified;++ const handleChange = (next: string) => {+ if (!tabStore.currentTab) return;+ tabStore.currentTab.connection.schema =+ next === SchemaOptionValueUnspecified ? undefined : next;+ };++ // Seed from URL query parameter on mount and whenever the query param OR+ // the active tab changes. Mirrors Vue's watchEffect, which implicitly+ // tracked both `route.query.schema` and `tab.value` (the latter via the+ // setter's reactive reads) so that switching to a new tab with the URL+ // query still present re-seeded the new tab's connection.schema.+ const queryParam = useVueState(+ () => router.currentRoute.value.query.schema as string | undefined+ );+ const currentTabId = useVueState(() => tabStore.currentTab?.id);+ // biome-ignore lint/correctness/useExhaustiveDependencies: handleChange is+ // defined inline and reads the live tabStore; omitting it is intentional+ // so the effect re-runs only on queryParam or tab switch.+ useEffect(() => {+ if (queryParam) handleChange(queryParam);+ }, [queryParam, currentTabId]);++ if (!show) return null;++ return (+ <ConnectChooser+ value={value}+ onChange={handleChange}+ options={options}+ isChosen={isChosen}+ placeholder={t("database.schema.select")}+ />+ );+}diff --git a/frontend/src/react/components/ui/popover.test.tsx b/frontend/src/react/components/ui/popover.test.tsxnew file mode 100644index 0000000000..eaa77a6af3--- /dev/null+++ b/frontend/src/react/components/ui/popover.test.tsx@@ -0,0 +1,102 @@+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, test } from "vitest";+import { Popover, PopoverContent, PopoverTrigger } from "./popover";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++describe("Popover", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ });++ test("renders trigger in container", async () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);++ await act(async () => {+ root.render(+ <Popover>+ <PopoverTrigger>+ <button type="button">Open</button>+ </PopoverTrigger>+ <PopoverContent>Popover body</PopoverContent>+ </Popover>+ );+ });++ expect(container.querySelector("button")?.textContent).toBe("Open");++ await act(async () => {+ root.unmount();+ });+ });++ test("clicking trigger opens popover content in overlay layer", async () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);++ await act(async () => {+ root.render(+ <Popover>+ <PopoverTrigger>+ <button type="button">Open</button>+ </PopoverTrigger>+ {/* Popover content renders via portal into bb-react-layer-overlay.+ We query document.body since the popup lives outside `container`. */}+ <PopoverContent>Popover body</PopoverContent>+ </Popover>+ );+ });++ const trigger = container.querySelector("button");+ expect(trigger).toBeInstanceOf(HTMLButtonElement);++ await act(async () => {+ trigger?.click();+ });++ expect(document.body.textContent).toContain("Popover body");++ await act(async () => {+ root.unmount();+ });+ });++ test("controlled popover only shows content when open=true", async () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);++ function ControlledPopover({ open }: { open: boolean }) {+ return (+ <Popover open={open}>+ <PopoverTrigger>+ <button type="button">Open</button>+ </PopoverTrigger>+ <PopoverContent>Controlled content</PopoverContent>+ </Popover>+ );+ }++ await act(async () => {+ root.render(<ControlledPopover open={false} />);+ });++ expect(document.body.textContent).not.toContain("Controlled content");++ await act(async () => {+ root.render(<ControlledPopover open={true} />);+ });++ expect(document.body.textContent).toContain("Controlled content");++ await act(async () => {+ root.unmount();+ });+ });+});diff --git a/frontend/src/react/components/ui/popover.tsx b/frontend/src/react/components/ui/popover.tsxnew file mode 100644index 0000000000..20398a837a--- /dev/null+++ b/frontend/src/react/components/ui/popover.tsx@@ -0,0 +1,50 @@+import { Popover as BasePopover } from "@base-ui/react/popover";+import type { ComponentProps } from "react";+import { cn } from "@/react/lib/utils";+import { getLayerRoot, LAYER_SURFACE_CLASS } from "./layer";++// ---- Root ----+const Popover = BasePopover.Root;++// ---- Trigger ----+const PopoverTrigger = BasePopover.Trigger;++// ---- Portal + Positioner + Popup ----+function PopoverContent({+ className,+ children,+ side = "bottom",+ align = "end",+ sideOffset = 4,+ ref,+ ...props+}: ComponentProps<typeof BasePopover.Popup> & {+ side?: ComponentProps<typeof BasePopover.Positioner>["side"];+ align?: ComponentProps<typeof BasePopover.Positioner>["align"];+ sideOffset?: ComponentProps<typeof BasePopover.Positioner>["sideOffset"];+}) {+ return (+ <BasePopover.Portal container={getLayerRoot("overlay")}>+ <BasePopover.Positioner+ side={side}+ align={align}+ sideOffset={sideOffset}+ className={LAYER_SURFACE_CLASS}+ >+ <BasePopover.Popup+ ref={ref}+ className={cn(+ "rounded-sm border border-control-border bg-background p-3 shadow-md text-sm text-control",+ "focus:outline-hidden",+ className+ )}+ {...props}+ >+ {children}+ </BasePopover.Popup>+ </BasePopover.Positioner>+ </BasePopover.Portal>+ );+}++export { Popover, PopoverTrigger, PopoverContent };diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex ce82c146b9..e088ada0c3 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -284,6 +284,10 @@"self": "Role"},"rollback": "Rollback",+ "rows": {+ "n-rows": "{{n}} rows",+ "self": "rows"+ },"rows-per-page": "Rows per page","run": "Run","save": "Save",@@ -499,6 +503,7 @@"custom-approval.issue-review.rejected-issue": "rejected issue","data-source": {"additional-node-addresses": "Additional Node Addresses",+ "automatic-query-data-source": "Automatic","connection-string-schema": "Connection String Schema","connection-type": "Connection Type","delete-read-only-data-source": "Delete read-only data source",@@ -514,6 +519,7 @@"read-replica-host": "Read-replica Host","read-replica-port": "Read-replica Port","replica-set": "Replica Set",+ "select-query-data-source": "Select query data source","snowflake-keypair-tip": "Key-pair authentication","ssh": {"host": "Server",@@ -614,6 +620,10 @@"partitioned": "Partitioned","row-count-est": "Row count est.","row-count-estimate": "Row count estimate",+ "schema": {+ "select": "Select schema",+ "unspecified": "Unspecified"+ },"select": "Select database","selected-n-databases": "{{n}} database(s) selected","successfully-transferred-databases": "Successfully transferred databases",@@ -643,6 +653,9 @@"sync-schema-button": "Sync Schema","sync-status": "Sync status","sync-status-failed": "Sync failed",+ "table": {+ "select": "Select table"+ },"transfer-project": "Transfer Project","unassign": "Unassign","unassign-alert-description": "The selected databases will be removed from the project",@@ -2190,13 +2203,32 @@"activate-access": "Activate","activate-confirm": "Are you sure you want to activate this access grant?","add-a-new-instance": "Add new instance",+ "admin-mode": {+ "self": "Admin mode"+ },+ "batch-query": {+ "batch": "Batch"+ },"connect-to-a-database": "Connect to database","expired": "Expired","format-sql": "Format SQL","grant-type-unmask": "Unmask","jit": "Just-In-Time Access",+ "query-context": {+ "admin-data-source-is-disallowed-to-query": "Admin data source is disallowed to query."+ },+ "redis-command": {+ "all-nodes": "All nodes",+ "only-for-cluster": "Only available for cluster connection",+ "self": "Run redis command on",+ "single-node": "Single node"+ },+ "result-limit": {+ "self": "Result limit"+ },"revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?",+ "select-a-database-to-start": "Select a database to start","self": "SQL Editor","unmask-warning": "The query result may include unmasked sensitive data.","view-issue": "View Issue",diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex dc3cc5dbcd..12501907ec 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -284,6 +284,10 @@"self": "Rol"},"rollback": "Retroceder",+ "rows": {+ "n-rows": "{{n}} filas",+ "self": "filas"+ },"rows-per-page": "Filas por página","run": "Run","save": "Guardar",@@ -499,6 +503,7 @@"custom-approval.issue-review.rejected-issue": "rejected issue","data-source": {"additional-node-addresses": "Direcciones de nodos adicionales",+ "automatic-query-data-source": "Automática","connection-string-schema": "Esquema de cadena de conexión","connection-type": "Tipo de conección","delete-read-only-data-source": "Eliminar origen de datos de solo lectura",@@ -514,6 +519,7 @@"read-replica-host": "Anfitrión de réplica de lectura","read-replica-port": "Puerto de réplica de lectura","replica-set": "Conjunto de réplicas",+ "select-query-data-source": "Seleccionar fuente de datos de consulta","snowflake-keypair-tip": "Autenticación de par de claves","ssh": {"host": "Anfitrión",@@ -614,6 +620,10 @@"partitioned": "Particionado","row-count-est": "Conteo estimado de filas","row-count-estimate": "Estimación de la cantidad de filas",+ "schema": {+ "select": "Seleccionar esquema",+ "unspecified": "No especificado"+ },"select": "Seleccionar base de datos","selected-n-databases": "{{n}} base(s) de datos seleccionada(s)","successfully-transferred-databases": "Bases de datos transferidas exitosamente",@@ -643,6 +653,9 @@"sync-schema-button": "Sincronizar esquema","sync-status": "Estado de sincronización","sync-status-failed": "Sincronización fallida",+ "table": {+ "select": "Seleccionar tabla"+ },"transfer-project": "Transferir proyecto","unassign": "Desasignar","unassign-alert-description": "Las bases de datos seleccionadas serán eliminadas del proyecto",@@ -2190,13 +2203,32 @@"activate-access": "Activate","activate-confirm": "Are you sure you want to activate this access grant?","add-a-new-instance": "Agregar nueva instancia",+ "admin-mode": {+ "self": "Modo administrador"+ },+ "batch-query": {+ "batch": "Lote"+ },"connect-to-a-database": "Conectar a base de datos","expired": "Expired","format-sql": "Format SQL","grant-type-unmask": "Unmask","jit": "Just-In-Time Access",+ "query-context": {+ "admin-data-source-is-disallowed-to-query": "No se permite realizar consultas a la fuente de datos del administrador."+ },+ "redis-command": {+ "all-nodes": "Todos los nodos",+ "only-for-cluster": "Sólo disponible para conexión de clúster",+ "self": "Ejecute el comando redis en",+ "single-node": "Nodo único"+ },+ "result-limit": {+ "self": "Límite de resultados"+ },"revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?",+ "select-a-database-to-start": "Seleccione una base de datos para comenzar","self": "Editor de SQL","unmask-warning": "The query result may include unmasked sensitive data.","view-issue": "View Issue",diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex 950a6ae6f5..809dcbae3a 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -284,6 +284,10 @@"self": "ロール"},"rollback": "ロールバック",+ "rows": {+ "n-rows": "{{n}} 行",+ "self": "行"+ },"rows-per-page": "ページあたりの行数","run": "Run","save": "保存",@@ -499,6 +503,7 @@"custom-approval.issue-review.rejected-issue": "rejected issue","data-source": {"additional-node-addresses": "追加のノードアドレス",+ "automatic-query-data-source": "自動","connection-string-schema": "接続文字列モード","connection-type": "接続タイプ","delete-read-only-data-source": "読み取り専用データソースを削除する",@@ -514,6 +519,7 @@"read-replica-host": "リードレプリカホスト","read-replica-port": "リードレプリカポート","replica-set": "レプリカセット",+ "select-query-data-source": "クエリデータソースの選択","snowflake-keypair-tip": "キーペア認証","ssh": {"host": "サーバ",@@ -614,6 +620,10 @@"partitioned": "パーティション","row-count-est": "推定行数","row-count-estimate": "推定行数",+ "schema": {+ "select": "スキーマの選択",+ "unspecified": "不特定"+ },"select": "データベースの選択","selected-n-databases": "{{n}} 個のデータベースが選択されました","successfully-transferred-databases": "データベースの転送に成功しました",@@ -643,6 +653,9 @@"sync-schema-button": "スキーマを同期","sync-status": "同期ステータス","sync-status-failed": "同期に失敗しました",+ "table": {+ "select": "テーブルを選択"+ },"transfer-project": "プロジェクトの転送","unassign": "割り当てを解除する","unassign-alert-description": "選択したデータベースがプロジェクトから削除されます",@@ -2190,13 +2203,32 @@"activate-access": "Activate","activate-confirm": "Are you sure you want to activate this access grant?","add-a-new-instance": "新しいインスタンスを追加",+ "admin-mode": {+ "self": "管理者モード"+ },+ "batch-query": {+ "batch": "バッチ"+ },"connect-to-a-database": "データベースに接続","expired": "Expired","format-sql": "Format SQL","grant-type-unmask": "Unmask","jit": "Just-In-Time Access",+ "query-context": {+ "admin-data-source-is-disallowed-to-query": "管理者データ ソースはクエリできません。"+ },+ "redis-command": {+ "all-nodes": "すべてのノード",+ "only-for-cluster": "クラスタ接続のみ使用可能",+ "self": "redisコマンドを実行する",+ "single-node": "単一ノード"+ },+ "result-limit": {+ "self": "結果の制限"+ },"revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?",+ "select-a-database-to-start": "開始するにはデータベースを選択してください","self": "SQLエディタ","unmask-warning": "The query result may include unmasked sensitive data.","view-issue": "View Issue",diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex dc3487274d..d0e1f29a1b 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -284,6 +284,10 @@"self": "Vai trò"},"rollback": "Hoàn tác",+ "rows": {+ "n-rows": "{{n}} dòng",+ "self": "dòng"+ },"rows-per-page": "Số dòng mỗi trang","run": "Run","save": "Lưu",@@ -499,6 +503,7 @@"custom-approval.issue-review.rejected-issue": "rejected issue","data-source": {"additional-node-addresses": "Địa chỉ nút bổ sung",+ "automatic-query-data-source": "Tự động","connection-string-schema": "Lược đồ chuỗi kết nối","connection-type": "Loại kết nối","delete-read-only-data-source": "Xóa nguồn dữ liệu chỉ đọc",@@ -514,6 +519,7 @@"read-replica-host": "Máy chủ bản sao đọc","read-replica-port": "Cổng bản sao đọc","replica-set": "Bộ bản sao",+ "select-query-data-source": "Chọn nguồn dữ liệu truy vấn","snowflake-keypair-tip": "Xác thực cặp khóa","ssh": {"host": "Máy chủ",@@ -614,6 +620,10 @@"partitioned": "Đã phân vùng","row-count-est": "Ước tính số hàng","row-count-estimate": "Ước tính số hàng",+ "schema": {+ "select": "Chọn lược đồ",+ "unspecified": "Không xác định"+ },"select": "Chọn cơ sở dữ liệu","selected-n-databases": "Đã chọn {{n}} cơ sở dữ liệu","successfully-transferred-databases": "Chuyển cơ sở dữ liệu thành công",@@ -643,6 +653,9 @@"sync-schema-button": "Đồng bộ lược đồ","sync-status": "Trạng thái đồng bộ","sync-status-failed": "Đồng bộ thất bại",+ "table": {+ "select": "Chọn bảng"+ },"transfer-project": "Chuyển dự án","unassign": "Hủy gán","unassign-alert-description": "Các cơ sở dữ liệu đã chọn sẽ bị xóa khỏi dự án",@@ -2190,13 +2203,32 @@"activate-access": "Activate","activate-confirm": "Are you sure you want to activate this access grant?","add-a-new-instance": "Thêm phiên bản mới",+ "admin-mode": {+ "self": "Chế độ quản trị"+ },+ "batch-query": {+ "batch": "Hàng loạt"+ },"connect-to-a-database": "Kết nối cơ sở dữ liệu","expired": "Expired","format-sql": "Format SQL","grant-type-unmask": "Unmask","jit": "Just-In-Time Access",+ "query-context": {+ "admin-data-source-is-disallowed-to-query": "Nguồn dữ liệu quản trị không được phép truy vấn."+ },+ "redis-command": {+ "all-nodes": "Tất cả các nút",+ "only-for-cluster": "Chỉ khả dụng cho kết nối cụm",+ "self": "Chạy lệnh redis trên",+ "single-node": "Nút đơn"+ },+ "result-limit": {+ "self": "Giới hạn kết quả"+ },"revoke-access": "Revoke","revoke-confirm": "Are you sure you want to revoke this access grant?",+ "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","unmask-warning": "The query result may include unmasked sensitive data.","view-issue": "View Issue",diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex 22fa73ef25..df2c61ad85 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -284,6 +284,10 @@"self": "角色"},"rollback": "回滚",+ "rows": {+ "n-rows": "{{n}} 行",+ "self": "行"+ },"rows-per-page": "每页行数","run": "Run","save": "保存",@@ -499,6 +503,7 @@"custom-approval.issue-review.rejected-issue": "rejected issue","data-source": {"additional-node-addresses": "附加节点地址",+ "automatic-query-data-source": "自动","connection-string-schema": "连接串模式","connection-type": "连接类型","delete-read-only-data-source": "删除只读数据源",@@ -514,6 +519,7 @@"read-replica-host": "只读副本 Host","read-replica-port": "只读副本端口","replica-set": "副本集",+ "select-query-data-source": "选择查询数据源","snowflake-keypair-tip": "密钥对认证","ssh": {"host": "服务器",@@ -614,6 +620,10 @@"partitioned": "分区","row-count-est": "估算行数","row-count-estimate": "估计行数",+ "schema": {+ "select": "选择 schema",+ "unspecified": "未指定"+ },"select": "选择数据库","selected-n-databases": "已选择 {{n}} 个数据库","successfully-transferred-databases": "成功转移数据库",@@ -643,6 +653,9 @@"sync-schema-button": "同步 Schema","sync-status": "同步状态","sync-status-failed": "同步失败",+ "table": {+ "select": "选择表"+ },"transfer-project": "转移项目","unassign": "取消分配","unassign-alert-description": "选定的数据库将从项目中移除",@@ -2190,13 +2203,32 @@"activate-access": "激活","activate-confirm": "确定要激活此访问授权吗?","add-a-new-instance": "添加新实例",+ "admin-mode": {+ "self": "管理员模式"+ },+ "batch-query": {+ "batch": "批量"+ },"connect-to-a-database": "连接数据库","expired": "已过期","format-sql": "格式化 SQL","grant-type-unmask": "脱敏豁免","jit": "即时访问",+ "query-context": {+ "admin-data-source-is-disallowed-to-query": "禁止查询主数据源。"+ },+ "redis-command": {+ "all-nodes": "所有节点",+ "only-for-cluster": "仅适用于集群连接",+ "self": "运行 redis 命令",+ "single-node": "单节点"+ },+ "result-limit": {+ "self": "结果限制"+ },"revoke-access": "撤销","revoke-confirm": "确定要撤销此访问授权吗?",+ "select-a-database-to-start": "选择数据库以开始","self": "SQL 编辑器","unmask-warning": "The query result may include unmasked sensitive data.","view-issue": "查看工单",diff --git a/frontend/src/views/sql-editor/EditorCommon/ConnectChooser.vue b/frontend/src/views/sql-editor/EditorCommon/ConnectChooser.vuedeleted file mode 100644index 4410bc1135..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ConnectChooser.vue+++ /dev/null@@ -1,127 +0,0 @@-<template>- <NPopselect- :value="value"- :options="options"- :show-checkmark="true"- :virtual-scroll="true"- :style="overridePopoverPaneStyle"- placement="bottom-end"- trigger="click"- class="schema-chooser-pane"- @update:show="handleToggleShow"- @update:value="handleSelect"- >- <template #header>- <div class="font-medium">- {{ placeholder }}- </div>- </template>- <NButton- ref="buttonRef"- size="small"- ghost- type="primary"- style="- display: inline-flex;- justify-content: end;- overflow: hidden;- --n-padding: 0 7px 0 5px;- --n-icon-margin: 6px 2px 6px 0;- --n-color-hover: rgb(var(--color-accent) / 0.05);- --n-color-pressed: rgb(var(--color-accent) / 0.05);- --n-color-focus: rgb(var(--color-accent) / 0.05);- "- :style="{- maxWidth: isChosen ? '12rem' : 'unset',- }"- >- <template #icon>- <SchemaIcon- class="w-4 h-4"- :class="isChosen ? 'text-main' : 'text-control-placeholder'"- />- </template>- <span v-if="isChosen" class="truncate text-main">- {{ value || $t("db.schema.default") }}- </span>- <span v-else class="text-control-placeholder whitespace-nowrap">- {{ placeholder }}- </span>- </NButton>- </NPopselect>-</template>--<script setup lang="tsx">-import { useElementBounding } from "@vueuse/core";-import { NButton, NPopselect, type SelectOption } from "naive-ui";-import { computed, nextTick, ref, watch } from "vue";-import { SchemaIcon } from "@/components/Icon";--defineProps<{- value: string;- isChosen: boolean;- placeholder: string;- options: SelectOption[];-}>();--const emit = defineEmits<{- (event: "update:value", value: string): void;-}>();--const popoverPaneRef = ref<HTMLDivElement>();-const popoverPaneBounding = useElementBounding(popoverPaneRef);-const popoverPaneDimensions = ref({- minWidth: 0,- maxHeight: 0,-});--const overridePopoverPaneStyle = computed(() => {- const style: Record<string, string> = {};- const { maxHeight, minWidth } = popoverPaneDimensions.value;- if (maxHeight > 0) {- style["--n-height"] = `${maxHeight}px`;- }- if (minWidth > 0) {- style["min-width"] = `${minWidth}px`;- }- style["maxWidth"] = "20rem";- return style;-});--const handleSelect = async (value: string) => {- emit("update:value", value);-};--const handleToggleShow = async (show: boolean) => {- if (!show) return;- await nextTick();-- const pane = document.querySelector(".schema-chooser-pane") as HTMLDivElement;- popoverPaneRef.value = pane;-};--// Calculate the max-height of the pane-// to prevent it to be too long to overflow the bottom of the screen-watch(popoverPaneBounding.top, (top) => {- if (!top) {- // Cannot calculate max-height- popoverPaneDimensions.value.maxHeight = 0;- return;- }- const safeZone = 20;- const MAX_HEIGHT = 320;- popoverPaneDimensions.value.maxHeight = Math.min(- window.innerHeight - top - safeZone,- MAX_HEIGHT- );-});--// Calculate the width of the pane-// to prevent its height varies when scrolling-watch(popoverPaneBounding.width, (width) => {- if (!width) return;- if (width > popoverPaneDimensions.value.minWidth) {- popoverPaneDimensions.value.minWidth = width;- }-});-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ContainerChooser.vue b/frontend/src/views/sql-editor/EditorCommon/ContainerChooser.vuedeleted file mode 100644index 65ca7cbc57..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ContainerChooser.vue+++ /dev/null@@ -1,79 +0,0 @@-<template>- <ConnectChooser- v-if="show"- v-model:value="chosenContainer"- :options="options"- :is-chosen="isChosen"- :placeholder="$t('database.table.select')"- />-</template>--<script lang="tsx" setup>-import { type SelectOption } from "naive-ui";-import { storeToRefs } from "pinia";-import { computed, watchEffect } from "vue";-import { useI18n } from "vue-i18n";-import { useRoute } from "vue-router";-import {- useConnectionOfCurrentSQLEditorTab,- useDBSchemaV1Store,- useSQLEditorTabStore,-} from "@/store";-import { Engine } from "@/types/proto-es/v1/common_pb";-import ConnectChooser from "./ConnectChooser.vue";--const OptionValueUnspecified = "-1";--const { t } = useI18n();-const route = useRoute();-const { currentTab: tab } = storeToRefs(useSQLEditorTabStore());-const { database, instance } = useConnectionOfCurrentSQLEditorTab();-const show = computed(() => {- return instance.value.engine === Engine.COSMOSDB;-});--const databaseMetadata = computed(() => {- return useDBSchemaV1Store().getDatabaseMetadata(database.value.name);-});-const options = computed(() => {- const selectOptions: SelectOption[] = [- {- value: OptionValueUnspecified,- label: t("database.schema.unspecified"),- },- ];-- for (const schema of databaseMetadata.value.schemas) {- for (const table of schema.tables) {- selectOptions.push({- value: table.name,- label: table.name,- });- }- }- return selectOptions;-});--const chosenContainer = computed<string>({- get() {- const table = tab.value?.connection.table;- if (table === undefined) return OptionValueUnspecified;- return table;- },- set(value) {- if (!tab.value) return;- tab.value.connection.table =- value === OptionValueUnspecified ? undefined : value;- },-});--watchEffect(() => {- if (route.query.table) {- chosenContainer.value = route.query.table as string;- }-});--const isChosen = computed(() => {- return chosenContainer.value !== OptionValueUnspecified;-});-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/DatabaseChooser.vue b/frontend/src/views/sql-editor/EditorCommon/DatabaseChooser.vuedeleted file mode 100644index 409d591242..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/DatabaseChooser.vue+++ /dev/null@@ -1,104 +0,0 @@-<template>- <NButton- :disabled="disabled || !projectContextReady"- type="primary"- size="small"- ghost- style="- justify-content: end;- --n-padding: 0 8px;- --n-color-hover: rgb(var(--color-accent) / 0.05);- --n-color-pressed: rgb(var(--color-accent) / 0.05);- --n-color-focus: rgb(var(--color-accent) / 0.05);- "- @click="changeConnection"- >- <div- v-if="- currentTab &&- isValidInstanceName(instance.name) &&- isValidDatabaseName(database.name)- "- class="flex flex-row items-center text-main"- >- <NPopover v-if="isInBatchMode" placement="bottom">- <template #trigger>- <SquareStackIcon class="w-4 h-4 mr-1 text-accent" />- </template>- <template #default>- {{ $t("sql-editor.batch-query.batch") }}- </template>- </NPopover>- <EnvironmentV1Name- :environment="environment"- :link="false"- />- <ChevronRightIcon class="shrink-0 h-4 w-4 text-control-light" />- <div class="flex items-center gap-1">- <InstanceV1EngineIcon- :instance="instance"- show-status- class="shrink-0"- />- <span>{{ instance.title }}</span>- </div>- <ChevronRightIcon class="shrink-0 h-4 w-4 text-control-light" />- <div class="flex items-center gap-1">- <DatabaseIcon class="shrink-0" />- <span>{{ databaseName }}</span>- </div>- </div>- <template v-else>- {{ $t("sql-editor.select-a-database-to-start") }}- </template>- </NButton>-</template>--<script lang="ts" setup>-import { ChevronRightIcon, SquareStackIcon } from "lucide-vue-next";-import { NButton, NPopover } from "naive-ui";-import { storeToRefs } from "pinia";-import { computed } from "vue";-import { DatabaseIcon } from "@/components/Icon";-import { EnvironmentV1Name, InstanceV1EngineIcon } from "@/components/v2";-import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorStore,- useSQLEditorTabStore,-} from "@/store";-import { isValidDatabaseName, isValidInstanceName } from "@/types";-import {- extractDatabaseResourceName,- getDatabaseEnvironment,- getInstanceResource,-} from "@/utils";-import { useSQLEditorContext } from "../context";--const { currentTab, isInBatchMode } = storeToRefs(useSQLEditorTabStore());-const { showConnectionPanel } = useSQLEditorContext();-const { projectContextReady } = storeToRefs(useSQLEditorStore());--const { database } = useConnectionOfCurrentSQLEditorTab();--const instance = computed(() => getInstanceResource(database.value));-const environment = computed(() => getDatabaseEnvironment(database.value));-const databaseName = computed(- () => extractDatabaseResourceName(database.value.name).databaseName-);--const changeConnection = () => {- showConnectionPanel.value = true;-};--defineProps<{- disabled?: boolean;-}>();-</script>--<style lang="postcss" scoped>-:deep(.n-button__content) {- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;-}-</style>diff --git a/frontend/src/views/sql-editor/EditorCommon/DisconnectedIcon.vue b/frontend/src/views/sql-editor/EditorCommon/DisconnectedIcon.vuedeleted file mode 100644index dd396e2321..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/DisconnectedIcon.vue+++ /dev/null@@ -1,3 +0,0 @@-<template>- <octicon:unlink-16 class="w-3.5 h-3.5 text-control opacity-50" />-</template>diff --git a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vueindex 6701920cea..eae8cb5b9a 100644--- a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue+++ b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue@@ -46,23 +46,13 @@{{ queryTip }}</span></NTooltip>- <QueryContextSettingPopover+ <ReactPageMount+ page="QueryContextSettingPopover":disabled="!showQueryContextSettingPopover || !allowQuery"/></NButtonGroup>- <NPopover placement="bottom">- <template #trigger>- <AdminModeButton- size="small"- :hide-text="true"- style="--n-padding: 0 5px"- />- </template>- <template #default>- <span>{{ $t("sql-editor.admin-mode.self") }}</span>- </template>- </NPopover>+ <ReactPageMount page="AdminModeButton" size="sm" :hideText="true" /><template v-if="showSheetsFeature"><NPopover placement="bottom">@@ -122,11 +112,7 @@<divclass="action-right gap-x-2 flex overflow-x-auto sm:overflow-x-hidden sm:justify-end items-center">- <NButtonGroup>- <DatabaseChooser />- <SchemaChooser />- <ContainerChooser />- </NButtonGroup>+ <ReactPageMount page="ChooserGroup" /><OpenAIButtonsize="small"@@ -154,6 +140,7 @@ import { storeToRefs } from "pinia";import { computed, reactive } from "vue";import { useI18n } from "vue-i18n";import { FeatureModal } from "@/components/FeatureGuard";+import ReactPageMount from "@/react/ReactPageMount.vue";import {useConnectionOfCurrentSQLEditorTab,useSQLEditorStore,@@ -170,12 +157,7 @@ import { Engine } from "@/types/proto-es/v1/common_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import { isWorksheetWritableV1, keyboardShortcutStr } from "@/utils";import { useSQLEditorContext } from "../context";-import AdminModeButton from "./AdminModeButton.vue";-import ContainerChooser from "./ContainerChooser.vue";-import DatabaseChooser from "./DatabaseChooser.vue";import OpenAIButton from "./OpenAIButton";-import QueryContextSettingPopover from "./QueryContextSettingPopover.vue";-import SchemaChooser from "./SchemaChooser.vue";import SharePopover from "./SharePopover.vue";interface LocalState {diff --git a/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue b/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vuedeleted file mode 100644index 222288442b..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/QueryContextSettingPopover.vue+++ /dev/null@@ -1,194 +0,0 @@-<template>- <NPopover- v-if="show"- placement="bottom-end"- trigger="click"- :disabled="disabled"- >- <template #trigger>- <NButton- :disabled="disabled"- type="primary"- size="small"- style="--n-padding: 0 0.25rem"- >- <template #icon>- <ChevronDown />- </template>- </NButton>- </template>- <template #default>- <div class="flex flex-col gap-1">- <div>- <p class="mb-1 textinfolabel">- {{ $t("data-source.select-query-data-source") }}- </p>- <NRadioGroup- class="max-w-44"- :value="selectedDataSourceId"- @update:value="onDataSourceSelected"- >- <NRadio class="w-full" value="">- {{ $t("data-source.automatic-query-data-source") }}- </NRadio>- <NTooltip- v-for="ds in dataSources"- :key="ds.id"- :disabled="!Boolean(dataSourceUnaccessibleReason(ds))"- >- <template #trigger>- <NRadio- class="w-full"- :value="ds.id"- :disabled="Boolean(dataSourceUnaccessibleReason(ds))"- >- <div- class="max-w-36 flex flex-row justify-start items-center"- >- <span class="text-xs opacity-60 shrink-0">{{- readableDataSourceType(ds.type)- }}</span>- <span class="ml-1 truncate">{{ ds.username }}</span>- </div>- </NRadio>- </template>- <p class="text-nowrap">- {{ dataSourceUnaccessibleReason(ds) }}- </p>- </NTooltip>- </NRadioGroup>- </div>- <NTooltip- v-if="showRedisConfig"- :disabled="- selectedDataSource?.redisType === DataSource_RedisType.CLUSTER- "- >- <template #trigger>- <div class="border-t pt-1" style="">- <p class="mb-1 textinfolabel">- {{ $t("sql-editor.redis-command.self") }}- </p>- <NRadioGroup- :disabled="- selectedDataSource?.redisType !== DataSource_RedisType.CLUSTER- "- v-model:value="redisCommandOption"- class="max-w-44"- >- <NRadio :value="QueryOption_RedisRunCommandsOn.SINGLE_NODE">- {{ $t("sql-editor.redis-command.single-node") }}- </NRadio>- <NRadio :value="QueryOption_RedisRunCommandsOn.ALL_NODES">- {{ $t("sql-editor.redis-command.all-nodes") }}- </NRadio>- </NRadioGroup>- </div>- </template>- {{ $t("sql-editor.redis-command.only-for-cluster") }}- </NTooltip>- <div class="border-t pt-1">- <MaxRowCountSelect- v-model:value="resultRowsLimit"- :quaternary="true"- :maximum="queryDataPolicy.maximumResultRows"- />- </div>- </div>- </template>- </NPopover>-</template>--<script lang="ts" setup>-import { orderBy } from "lodash-es";-import { ChevronDown } from "lucide-vue-next";-import { NButton, NPopover, NRadio, NRadioGroup, NTooltip } from "naive-ui";-import { storeToRefs } from "pinia";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import MaxRowCountSelect from "@/components/RoleGrantPanel/MaxRowCountSelect.vue";-import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorStore,- useSQLEditorTabStore,-} from "@/store";-import { Engine } from "@/types/proto-es/v1/common_pb";-import type { DataSource } from "@/types/proto-es/v1/instance_service_pb";-import {- DataSource_RedisType,- DataSourceType,-} from "@/types/proto-es/v1/instance_service_pb";-import { QueryOption_RedisRunCommandsOn } from "@/types/proto-es/v1/sql_service_pb";-import { getInstanceResource, readableDataSourceType } from "@/utils";--defineProps<{- disabled?: boolean;-}>();--const { t } = useI18n();-const tabStore = useSQLEditorTabStore();-const { connection, database } = useConnectionOfCurrentSQLEditorTab();--const { redisCommandOption, resultRowsLimit, queryDataPolicy } = storeToRefs(- useSQLEditorStore()-);--const show = computed(() => {- return tabStore.currentTab?.mode !== "ADMIN";-});--const showRedisConfig = computed(() => {- if (!database.value) {- return false;- }- const instance = getInstanceResource(database.value);- return instance.engine === Engine.REDIS;-});--const selectedDataSourceId = computed(() => {- return connection.value.dataSourceId ?? "";-});--const selectedDataSource = computed(() => {- const instance = getInstanceResource(database.value);- return instance.dataSources.find(- (ds) => ds.id === selectedDataSourceId.value- );-});--const dataSources = computed(() => {- return orderBy(getInstanceResource(database.value).dataSources, "type");-});--const dataSourceUnaccessibleReason = (- dataSource: DataSource-): string | undefined => {- if (queryDataPolicy.value.allowAdminDataSource) {- return undefined;- }- if (dataSource.type !== DataSourceType.ADMIN) {- return undefined;- }-- const readOnlyDataSources = dataSources.value.filter(- (ds) => ds.type === DataSourceType.READ_ONLY- );- if (readOnlyDataSources.length === 0) {- return undefined;- }-- return t("sql-editor.query-context.admin-data-source-is-disallowed-to-query");-};--const onDataSourceSelected = (dataSourceId?: string) => {- const nextConnection = { ...connection.value };- if (dataSourceId) {- nextConnection.dataSourceId = dataSourceId;- } else {- delete nextConnection.dataSourceId;- }- tabStore.updateCurrentTab({- connection: nextConnection,- });-};-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/ReadonlyDatasourceHint.vue b/frontend/src/views/sql-editor/EditorCommon/ReadonlyDatasourceHint.vuedeleted file mode 100644index 6ad5d4f9aa..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/ReadonlyDatasourceHint.vue+++ /dev/null@@ -1,65 +0,0 @@-<template>- <NPopover v-if="showReadonlyDatasourceHint" trigger="hover">- <template #trigger>- <TriangleAlertIcon- class="h-4 w-4 shrink-0 text-warning"- v-bind="$attrs"- />- </template>- <p class="py-1">- <template v-if="allowManageInstance">- {{ $t("instance.no-read-only-data-source-warn-for-admin-dba") }}- <span- class="underline text-accent cursor-pointer hover:opacity-80"- @click="gotoInstanceDetailPage"- >- {{ $t("sql-editor.create-read-only-data-source") }}- </span>- </template>- <template v-else>- {{ $t("instance.no-read-only-data-source-warn-for-developer") }}- </template>- </p>- </NPopover>-</template>--<script setup lang="ts">-import { TriangleAlertIcon } from "lucide-vue-next";-import { NPopover } from "naive-ui";-import { computed } from "vue";-import { useSQLEditorTabStore } from "@/store";-import { isValidInstanceName } from "@/types";-import type { InstanceResource } from "@/types/proto-es/v1/instance_service_pb";-import { DataSourceType } from "@/types/proto-es/v1/instance_service_pb";-import { hasWorkspacePermissionV2 } from "@/utils";--const props = defineProps<{- instance: InstanceResource;-}>();--const tabStore = useSQLEditorTabStore();--const allowManageInstance = computed(() => {- return hasWorkspacePermissionV2("bb.instances.update");-});--const hasReadonlyDataSource = computed(() => {- return (- props.instance.dataSources.findIndex(- (ds) => ds.type === DataSourceType.READ_ONLY- ) !== -1- );-});--const showReadonlyDatasourceHint = computed(() => {- return (- tabStore.currentTab?.mode === "WORKSHEET" &&- isValidInstanceName(props.instance.name) &&- !hasReadonlyDataSource.value- );-});--const gotoInstanceDetailPage = () => {- window.open(`/${props.instance.name}`);-};-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/SchemaChooser.vue b/frontend/src/views/sql-editor/EditorCommon/SchemaChooser.vuedeleted file mode 100644index e665bac9f0..0000000000--- a/frontend/src/views/sql-editor/EditorCommon/SchemaChooser.vue+++ /dev/null@@ -1,74 +0,0 @@-<template>- <ConnectChooser- v-if="show"- v-model:value="chosenSchema"- :options="options"- :is-chosen="isChosen"- :placeholder="$t('database.schema.select')"- />-</template>--<script setup lang="ts">-import { type SelectOption } from "naive-ui";-import { storeToRefs } from "pinia";-import { computed, watchEffect } from "vue";-import { useI18n } from "vue-i18n";-import { useRoute } from "vue-router";-import {- useConnectionOfCurrentSQLEditorTab,- useDBSchemaV1Store,- useSQLEditorTabStore,-} from "@/store";-import { instanceAllowsSchemaScopedQuery } from "@/utils";-import ConnectChooser from "./ConnectChooser.vue";--const SchemaOptionValueUnspecified = "-1";--const { t } = useI18n();-const route = useRoute();-const { currentTab: tab } = storeToRefs(useSQLEditorTabStore());-const { database, instance } = useConnectionOfCurrentSQLEditorTab();-const show = computed(() => {- return instanceAllowsSchemaScopedQuery(instance.value.engine);-});--const databaseMetadata = computed(() => {- return useDBSchemaV1Store().getDatabaseMetadata(database.value.name);-});-const options = computed(() => {- const options = databaseMetadata.value.schemas.map<SelectOption>(- (schema) => ({- value: schema.name,- label: schema.name || t("db.schema.default"),- })- );- options.unshift({- value: SchemaOptionValueUnspecified,- label: t("database.schema.unspecified"),- });- return options;-});--const chosenSchema = computed<string>({- get() {- const schema = tab.value?.connection.schema;- if (schema === undefined) return SchemaOptionValueUnspecified;- return schema;- },- set(value) {- if (!tab.value) return;- tab.value.connection.schema =- value === SchemaOptionValueUnspecified ? undefined : value;- },-});--watchEffect(() => {- if (route.query.schema) {- chosenSchema.value = route.query.schema as string;- }-});--const isChosen = computed(() => {- return chosenSchema.value !== SchemaOptionValueUnspecified;-});-</script>diff --git a/frontend/src/views/sql-editor/EditorCommon/index.ts b/frontend/src/views/sql-editor/EditorCommon/index.tsindex d31005d463..b382da7b0d 100644--- a/frontend/src/views/sql-editor/EditorCommon/index.ts+++ b/frontend/src/views/sql-editor/EditorCommon/index.ts@@ -1,4 +1,3 @@-import DisconnectedIcon from "./DisconnectedIcon.vue";import EditorAction from "./EditorAction.vue";import ExecutingHintModal from "./ExecutingHintModal.vue";import OpenAIButton from "./OpenAIButton/OpenAIButton.vue";@@ -13,7 +12,6 @@ export {SaveSheetModal,SharePopover,ResultViewV1,- DisconnectedIcon,SheetConnectionIcon,OpenAIButton,};diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vueindex f173890e14..ff17220c88 100644--- a/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue@@ -9,7 +9,7 @@class="py-2 px-2 w-full flex flex-row gap-x-2 justify-between items-center"><div class="flex items-center justify-start gap-2">- <DatabaseChooser :disabled="true" />+ <ReactPageMount page="DatabaseChooser" :disabled="true" /><SchemaSelectToolbar simple /></div></div>@@ -57,6 +57,7 @@ import { watch } from "vue";import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";import { useExecuteSQL } from "@/composables/useExecuteSQL";import { useAIContext } from "@/plugins/ai/logic";+import ReactPageMount from "@/react/ReactPageMount.vue";import {useConnectionOfCurrentSQLEditorTab,useDatabaseV1Store,@@ -71,7 +72,6 @@ import {nextAnimationFrame,type VueClass,} from "@/utils";-import DatabaseChooser from "@/views/sql-editor/EditorCommon/DatabaseChooser.vue";import { useCurrentTabViewStateContext } from "../context/viewState.tsx";import { SchemaSelectToolbar } from "./common";import DiagramPanel from "./DiagramPanel";