Skip to content

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

chore: optimize cosmos db select container (#21117)

ecmadao2360a2c066ff
diff --git a/frontend/src/components/ui/combobox-position.test.ts b/frontend/src/components/ui/combobox-position.test.ts
index a11de564fd..923883a5dc 100644
--- a/frontend/src/components/ui/combobox-position.test.ts
+++ b/frontend/src/components/ui/combobox-position.test.ts
@@ -46,6 +46,30 @@ describe("getPortalDropdownStyle", () => {
});
});
+ test("clamps a minimum-width dropdown inside the viewport", () => {
+ expect(
+ getPortalDropdownStyle(
+ {
+ top: 120,
+ left: 760,
+ width: 96,
+ bottom: 156,
+ },
+ 240,
+ 800,
+ {
+ minWidth: 192,
+ viewportWidth: 920,
+ }
+ )
+ ).toEqual({
+ position: "fixed",
+ left: 724,
+ width: 192,
+ top: 160,
+ });
+ });
+
test("ignores scroll events that originate from the dropdown itself", () => {
const dropdown = document.createElement("div");
const optionList = document.createElement("div");
diff --git a/frontend/src/components/ui/combobox-position.ts b/frontend/src/components/ui/combobox-position.ts
index 1ebd2fcb9c..0d809adc4e 100644
--- a/frontend/src/components/ui/combobox-position.ts
+++ b/frontend/src/components/ui/combobox-position.ts
@@ -10,17 +10,39 @@ function shouldIgnorePortalDropdownScroll(
function getPortalDropdownStyle(
triggerRect: Pick<DOMRect, "top" | "left" | "width" | "bottom">,
dropdownHeight: number,
- viewportHeight: number
+ viewportHeight: number,
+ options?: {
+ minWidth?: number;
+ viewportWidth?: number;
+ }
): React.CSSProperties {
const availableBelow = viewportHeight - triggerRect.bottom - DROPDOWN_OFFSET;
const availableAbove = triggerRect.top - DROPDOWN_OFFSET;
const shouldOpenUpward =
availableBelow < dropdownHeight && availableAbove > availableBelow;
+ const maxWidth =
+ options?.viewportWidth === undefined
+ ? undefined
+ : Math.max(0, options.viewportWidth - DROPDOWN_OFFSET * 2);
+ const width = Math.min(
+ Math.max(triggerRect.width, options?.minWidth ?? 0),
+ maxWidth ?? Number.POSITIVE_INFINITY
+ );
+ const left =
+ options?.viewportWidth === undefined
+ ? triggerRect.left
+ : Math.max(
+ DROPDOWN_OFFSET,
+ Math.min(
+ triggerRect.left,
+ options.viewportWidth - width - DROPDOWN_OFFSET
+ )
+ );
return {
position: "fixed",
- left: triggerRect.left,
- width: triggerRect.width,
+ left,
+ width,
...(shouldOpenUpward
? { bottom: viewportHeight - triggerRect.top + DROPDOWN_OFFSET }
: { top: triggerRect.bottom + DROPDOWN_OFFSET }),
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 657ebb627d..e7ea728cde 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -677,6 +677,10 @@
"column": "Column",
"columns": "Columns",
"comment": "Comment",
+ "container": {
+ "select": "Select container",
+ "unspecified": "Unspecified"
+ },
"create-database": "Create database",
"data-size": "Data size",
"edit-environment": "Edit Environment",
@@ -773,10 +777,6 @@
"sync-schema-button": "Sync Schema",
"sync-status": "Sync status",
"sync-status-failed": "Sync failed",
- "table": {
- "select": "Select table",
- "select-tip": "Please select a table to start."
- },
"transfer-project": "Transfer Project",
"unassign": "Unassign",
"unassign-alert-description": "The selected databases will be removed from the project",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 572a4fe41e..bc8f286c0b 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -677,6 +677,10 @@
"column": "Columna",
"columns": "Columnas",
"comment": "Comentario",
+ "container": {
+ "select": "Seleccionar contenedor",
+ "unspecified": "Sin especificar"
+ },
"create-database": "Crear base de datos",
"data-size": "Tamaño de datos",
"edit-environment": "Editar entorno",
@@ -773,10 +777,6 @@
"sync-schema-button": "Sincronizar esquema",
"sync-status": "Estado de sincronización",
"sync-status-failed": "Sincronización fallida",
- "table": {
- "select": "Seleccionar tabla",
- "select-tip": "Seleccione una mesa para comenzar."
- },
"transfer-project": "Transferir proyecto",
"unassign": "Desasignar",
"unassign-alert-description": "Las bases de datos seleccionadas serán eliminadas del proyecto",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index b7e95db8c8..df2d2f67ae 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -677,6 +677,10 @@
"column": "列",
"columns": "カラム",
"comment": "コメント",
+ "container": {
+ "select": "コンテナーを選択",
+ "unspecified": "未指定"
+ },
"create-database": "データベースを作成",
"data-size": "データサイズ",
"edit-environment": "環境の編集",
@@ -773,10 +777,6 @@
"sync-schema-button": "スキーマを同期",
"sync-status": "同期ステータス",
"sync-status-failed": "同期に失敗しました",
- "table": {
- "select": "テーブルを選択",
- "select-tip": "開始するにはテーブルを選択してください。"
- },
"transfer-project": "プロジェクトの転送",
"unassign": "割り当てを解除する",
"unassign-alert-description": "選択したデータベースがプロジェクトから削除されます",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 138c6ef6a5..1e972af386 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -677,6 +677,10 @@
"column": "Cột",
"columns": "Cột",
"comment": "Bình luận",
+ "container": {
+ "select": "Chọn container",
+ "unspecified": "Không xác định"
+ },
"create-database": "Tạo cơ sở dữ liệu",
"data-size": "Kích thước dữ liệu",
"edit-environment": "Chỉnh sửa Môi trường",
@@ -773,10 +777,6 @@
"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",
- "select-tip": "Vui lòng chọn một bảng để bắt đầu."
- },
"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",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 80bddbca6b..411930340c 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -677,6 +677,10 @@
"column": "列",
"columns": "列",
"comment": "注释",
+ "container": {
+ "select": "选择容器",
+ "unspecified": "未指定"
+ },
"create-database": "创建数据库",
"data-size": "数据大小",
"edit-environment": "编辑环境",
@@ -773,10 +777,6 @@
"sync-schema-button": "同步 Schema",
"sync-status": "同步状态",
"sync-status-failed": "同步失败",
- "table": {
- "select": "选择表",
- "select-tip": "请选择一个表来开始查询。"
- },
"transfer-project": "转移项目",
"unassign": "取消分配",
"unassign-alert-description": "选定的数据库将从项目中移除",
diff --git a/frontend/src/modules/sql-editor/components/ConnectChooser.test.tsx b/frontend/src/modules/sql-editor/components/ConnectChooser.test.tsx
index d8c7f00e76..eea054caf0 100644
--- a/frontend/src/modules/sql-editor/components/ConnectChooser.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ConnectChooser.test.tsx
@@ -10,6 +10,7 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
getLayerRoot: vi.fn(() => document.body),
+ getPortalDropdownStyle: vi.fn(() => ({ top: 100, left: 0, width: 200 })),
}));
vi.mock("react-i18next", () => ({
@@ -22,7 +23,7 @@ vi.mock("@/components/ui/layer", () => ({
}));
vi.mock("@/components/ui/combobox-position", () => ({
- getPortalDropdownStyle: vi.fn(() => ({ top: 100, left: 0, width: 200 })),
+ getPortalDropdownStyle: mocks.getPortalDropdownStyle,
isPortalDropdownStyleEqual: vi.fn(() => true),
shouldIgnorePortalDropdownScroll: vi.fn(() => false),
}));
@@ -100,6 +101,78 @@ describe("ConnectChooser", () => {
unmount();
});
+ test("applies custom dropdown sizing class without widening the trigger", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <ConnectChooser
+ value="ED"
+ onChange={vi.fn()}
+ options={defaultOptions}
+ isChosen={true}
+ placeholder="Select container"
+ dropdownClassName="min-w-[12rem]"
+ />
+ );
+ render();
+
+ expect(container.querySelector("button")?.className).not.toContain(
+ "min-w-[12rem]"
+ );
+ act(() => {
+ container.querySelector("button")?.click();
+ });
+ expect(
+ document.body.querySelector(".min-w-\\[12rem\\]")
+ ).not.toBeNull();
+ unmount();
+ });
+
+ test("passes custom dropdown minimum width to portal positioning", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <ConnectChooser
+ value="ED"
+ onChange={vi.fn()}
+ options={defaultOptions}
+ isChosen={true}
+ placeholder="Select container"
+ dropdownMinWidth={192}
+ />
+ );
+ render();
+
+ act(() => {
+ container.querySelector("button")?.click();
+ });
+ expect(mocks.getPortalDropdownStyle).toHaveBeenCalledWith(
+ expect.any(Object),
+ expect.any(Number),
+ expect.any(Number),
+ {
+ minWidth: 192,
+ viewportWidth: expect.any(Number),
+ }
+ );
+ unmount();
+ });
+
+ test("does not render a chevron in the run trigger", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <ConnectChooser
+ value="-1"
+ onChange={vi.fn()}
+ options={defaultOptions}
+ isChosen={false}
+ placeholder="Select container"
+ triggerVariant="run"
+ />
+ );
+ render();
+
+ expect(container.querySelector("button")?.querySelectorAll("svg")).toHaveLength(
+ 1
+ );
+ unmount();
+ });
+
test("renders db.schema.default when isChosen=true but value is empty string", () => {
const { container, render, unmount } = renderIntoContainer(
<ConnectChooser
@@ -161,4 +234,35 @@ describe("ConnectChooser", () => {
expect(onChange).toHaveBeenCalled();
unmount();
});
+
+ test("opens the dropdown when the external open signal changes", () => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ document.body.appendChild(container);
+ const render = (openSignal: number) => {
+ act(() => {
+ root.render(
+ <ConnectChooser
+ value=""
+ onChange={vi.fn()}
+ options={defaultOptions}
+ isChosen={false}
+ placeholder="Select schema"
+ openSignal={openSignal}
+ />
+ );
+ });
+ };
+
+ render(0);
+ expect(document.body.textContent).not.toContain("Unspecified");
+
+ render(1);
+
+ expect(document.body.textContent).toContain("Unspecified");
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ });
});
diff --git a/frontend/src/modules/sql-editor/components/ConnectChooser.tsx b/frontend/src/modules/sql-editor/components/ConnectChooser.tsx
index dfc980709a..824fb243a3 100644
--- a/frontend/src/modules/sql-editor/components/ConnectChooser.tsx
+++ b/frontend/src/modules/sql-editor/components/ConnectChooser.tsx
@@ -9,6 +9,7 @@ import {
} from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
+import { Button } from "@/components/ui/button";
import type { ComboboxOption } from "@/components/ui/combobox";
import {
getPortalDropdownStyle,
@@ -28,6 +29,11 @@ type ConnectChooserProps = {
readonly options: ComboboxOption[];
readonly isChosen: boolean;
readonly placeholder: string;
+ readonly dropdownClassName?: string;
+ readonly dropdownMinWidth?: number;
+ readonly openSignal?: number;
+ readonly triggerClassName?: string;
+ readonly triggerVariant?: "connection" | "run";
};
/**
@@ -46,6 +52,11 @@ export function ConnectChooser({
options,
isChosen,
placeholder,
+ dropdownClassName,
+ dropdownMinWidth,
+ openSignal,
+ triggerClassName,
+ triggerVariant = "connection",
}: ConnectChooserProps) {
const { t } = useTranslation();
const displayValue = value || t("db.schema.default");
@@ -56,6 +67,7 @@ export function ConnectChooser({
const dropdownRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const [dropdownStyle, setDropdownStyle] = useState<React.CSSProperties>({});
+ const lastOpenSignalRef = useRef(openSignal);
const filteredOptions = useMemo(() => {
if (!search) return options;
@@ -77,7 +89,11 @@ export function ConnectChooser({
const nextStyle = getPortalDropdownStyle(
rect,
dropdownHeight,
- window.innerHeight
+ window.innerHeight,
+ {
+ minWidth: dropdownMinWidth,
+ viewportWidth: window.innerWidth,
+ }
);
setDropdownStyle((prev) =>
isPortalDropdownStyleEqual(prev, nextStyle) ? prev : nextStyle
@@ -134,6 +150,14 @@ export function ConnectChooser({
}
}, [open]);
+ useEffect(() => {
+ if (openSignal === undefined) return;
+ if (lastOpenSignalRef.current === openSignal) return;
+ lastOpenSignalRef.current = openSignal;
+ setOpen(true);
+ setSearch("");
+ }, [openSignal]);
+
const handleSelect = useCallback(
(optionValue: string) => {
onChange(optionValue);
@@ -149,7 +173,8 @@ export function ConnectChooser({
style={dropdownStyle}
className={cn(
"bg-background border border-control-border rounded-sm shadow-lg overflow-hidden",
- LAYER_SURFACE_CLASS
+ LAYER_SURFACE_CLASS,
+ dropdownClassName
)}
>
<SearchInput
@@ -197,29 +222,71 @@ export function ConnectChooser({
</div>
);
+ const triggerContent = (
+ <>
+ <Network
+ className={cn(
+ "size-4 shrink-0",
+ triggerVariant === "run"
+ ? "text-current"
+ : isChosen
+ ? "text-accent"
+ : "text-control-placeholder"
+ )}
+ />
+ {isChosen ? (
+ <span
+ className={cn(
+ "truncate",
+ triggerVariant === "connection" && "text-control"
+ )}
+ >
+ {displayValue}
+ </span>
+ ) : (
+ <span
+ className={cn(
+ "whitespace-nowrap",
+ triggerVariant === "connection" && "text-control-placeholder"
+ )}
+ >
+ {placeholder}
+ </span>
+ )}
+ </>
+ );
+
return (
<>
- <ConnectionChooserButton
- ref={triggerRef}
- className={isChosen ? "max-w-[12rem]" : "max-w-none"}
- aria-label={placeholder}
- aria-expanded={open}
- onClick={() => setOpen((v) => !v)}
- >
- <Network
+ {triggerVariant === "run" ? (
+ <Button
+ ref={triggerRef}
+ variant="default"
+ size="sm"
className={cn(
- "size-4 shrink-0",
- isChosen ? "text-accent" : "text-control-placeholder"
+ "h-7 min-w-[10rem] px-1.5 gap-1 rounded-r-none text-sm",
+ triggerClassName
)}
- />
- {isChosen ? (
- <span className="truncate text-control">{displayValue}</span>
- ) : (
- <span className="text-control-placeholder whitespace-nowrap">
- {placeholder}
- </span>
- )}
- </ConnectionChooserButton>
+ aria-label={placeholder}
+ aria-expanded={open}
+ onClick={() => setOpen((v) => !v)}
+ >
+ {triggerContent}
+ </Button>
+ ) : (
+ <ConnectionChooserButton
+ ref={triggerRef}
+ className={cn(
+ isChosen ? "max-w-[12rem]" : "max-w-none",
+ triggerClassName
+ )}
+ aria-label={placeholder}
+ aria-expanded={open}
+ onClick={() => setOpen((v) => !v)}
+ >
+ {triggerContent}
+ </ConnectionChooserButton>
+ )}
{open && createPortal(dropdownContent, getLayerRoot("overlay"))}
</>
);
diff --git a/frontend/src/modules/sql-editor/components/ContainerChooser.test.tsx b/frontend/src/modules/sql-editor/components/ContainerChooser.test.tsx
index 1be0dae131..594adeb225 100644
--- a/frontend/src/modules/sql-editor/components/ContainerChooser.test.tsx
+++ b/frontend/src/modules/sql-editor/components/ContainerChooser.test.tsx
@@ -68,20 +68,41 @@ vi.mock("./ConnectChooser", () => ({
options,
isChosen,
value,
+ onChange,
+ dropdownClassName,
+ dropdownMinWidth,
+ triggerClassName,
+ triggerVariant,
}: {
placeholder: string;
options: { value: string; label: string }[];
isChosen: boolean;
value: string;
+ onChange: (value: string) => void;
+ dropdownClassName?: string;
+ dropdownMinWidth?: number;
+ triggerClassName?: string;
+ triggerVariant?: string;
}) => (
- <div data-testid="connect-chooser">
+ <div
+ data-testid="connect-chooser"
+ data-dropdown-class-name={dropdownClassName}
+ data-dropdown-min-width={dropdownMinWidth}
+ data-trigger-class-name={triggerClassName}
+ data-trigger-variant={triggerVariant}
+ >
<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}`}>
+ <button
+ key={o.value}
+ type="button"
+ data-testid={`option-${o.value}`}
+ onClick={() => onChange(o.value)}
+ >
{o.label}
- </span>
+ </button>
))}
</div>
),
@@ -126,6 +147,7 @@ beforeEach(async () => {
);
mocks.tabTable = undefined;
mocks.currentTabId = "tab1";
+ mocks.router.currentRoute.value.query = {};
mocks.getSQLEditorTabsState.mockReturnValue({
currentTabId: "tab1",
tabsById: new Map([["tab1", { connection: {} }]]),
@@ -165,6 +187,9 @@ describe("ContainerChooser", () => {
expect(
container.querySelector("[data-testid='connect-chooser']")
).not.toBeNull();
+ expect(container.querySelector("[data-testid='placeholder']")?.textContent).toBe(
+ "database.container.select"
+ );
unmount();
});
@@ -205,6 +230,157 @@ describe("ContainerChooser", () => {
expect(
container.querySelector("[data-testid='is-chosen']")?.textContent
).toBe("true");
+ expect(
+ container
+ .querySelector("[data-testid='connect-chooser']")
+ ?.getAttribute("data-trigger-class-name")
+ ).toBeNull();
+ expect(
+ container
+ .querySelector("[data-testid='connect-chooser']")
+ ?.getAttribute("data-dropdown-min-width")
+ ).toBe("192");
+ unmount();
+ });
+
+ test("renders run variant when mounted for the Run button", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <ContainerChooser variant="run" />
+ );
+ render();
+
+ expect(
+ container
+ .querySelector("[data-testid='connect-chooser']")
+ ?.getAttribute("data-trigger-variant")
+ ).toBe("run");
+ unmount();
+ });
+
+ test("does not auto-select the only known CosmosDB container", () => {
+ const updateCurrentTab = vi.fn();
+ mocks.getSQLEditorTabsState.mockReturnValue({
+ currentTabId: "tab1",
+ tabsById: new Map([["tab1", { connection: { database: "db" } }]]),
+ updateCurrentTab,
+ });
+ mocks.metadata = {
+ schemas: [
+ {
+ name: "default",
+ tables: [{ name: "only-container" }],
+ },
+ ],
+ };
+
+ const { render, unmount } = renderIntoContainer(<ContainerChooser />);
+ render();
+
+ expect(updateCurrentTab).not.toHaveBeenCalled();
+ unmount();
+ });
+
+ test("allows clearing the selected container even when it is the only container", () => {
+ const updateCurrentTab = vi.fn((payload) => {
+ mocks.tabTable = payload.connection.table;
+ });
+ mocks.tabTable = "only-container";
+ mocks.getSQLEditorTabsState.mockImplementation(() => ({
+ currentTabId: "tab1",
+ tabsById: new Map([
+ [
+ "tab1",
+ {
+ connection: {
+ database: "db",
+ table: mocks.tabTable,
+ },
+ },
+ ],
+ ]),
+ updateCurrentTab,
+ }));
+ mocks.metadata = {
+ schemas: [
+ {
+ name: "default",
+ tables: [{ name: "only-container" }],
+ },
+ ],
+ };
+
+ const { container, render, unmount } = renderIntoContainer(
+ <ContainerChooser />
+ );
+ render();
+ act(() => {
+ container
+ .querySelector<HTMLButtonElement>("[data-testid='option--1']")
+ ?.click();
+ });
+ render();
+
+ expect(updateCurrentTab).toHaveBeenCalledTimes(1);
+ expect(updateCurrentTab).toHaveBeenCalledWith({
+ connection: {
+ database: "db",
+ table: undefined,
+ },
+ });
unmount();
});
+
+ test("does not restore a cleared container from a stale route query", () => {
+ const updateCurrentTab = vi.fn((payload) => {
+ mocks.tabTable = payload.connection.table;
+ });
+ mocks.tabTable = "ED";
+ mocks.router.currentRoute.value.query = { table: "ED" };
+ mocks.getSQLEditorTabsState.mockImplementation(() => ({
+ currentTabId: "tab1",
+ tabsById: new Map([
+ [
+ "tab1",
+ {
+ connection: {
+ database: "db",
+ table: mocks.tabTable,
+ },
+ },
+ ],
+ ]),
+ updateCurrentTab,
+ }));
+ mocks.metadata = {
+ schemas: [
+ {
+ name: "default",
+ tables: [{ name: "WorldCities" }, { name: "ED" }],
+ },
+ ],
+ };
+
+ const first = renderIntoContainer(<ContainerChooser />);
+ first.render();
+ updateCurrentTab.mockClear();
+
+ act(() => {
+ first.container
+ .querySelector<HTMLButtonElement>("[data-testid='option--1']")
+ ?.click();
+ });
+ first.unmount();
+
+ const second = renderIntoContainer(<ContainerChooser />);
+ second.render();
+
+ expect(updateCurrentTab).toHaveBeenCalledTimes(1);
+ expect(updateCurrentTab).toHaveBeenCalledWith({
+ connection: {
+ database: "db",
+ table: undefined,
+ },
+ });
+ second.unmount();
+ });
});
diff --git a/frontend/src/modules/sql-editor/components/ContainerChooser.tsx b/frontend/src/modules/sql-editor/components/ContainerChooser.tsx
index 9f0db1bf3e..373188bc51 100644
--- a/frontend/src/modules/sql-editor/components/ContainerChooser.tsx
+++ b/frontend/src/modules/sql-editor/components/ContainerChooser.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo } from "react";
+import { useCallback, useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useAppDatabaseMetadata } from "@/hooks/useAppDatabaseMetadata";
import { useReactiveRoute } from "@/hooks/useReactiveRoute";
@@ -11,13 +11,22 @@ import { Engine } from "@/types/proto-es/v1/common_pb";
import { ConnectChooser } from "./ConnectChooser";
const OptionValueUnspecified = "-1";
+const ignoredRouteTableByTab = new Map<string, string>();
+
+type Props = {
+ readonly openSignal?: number;
+ readonly variant?: "connection" | "run";
+};
/**
* 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() {
+export function ContainerChooser({
+ openSignal,
+ variant = "connection",
+}: Props) {
const { t } = useTranslation();
const { instance, database } = useConnectionOfCurrentSQLEditorTab();
@@ -34,46 +43,62 @@ export function ContainerChooser() {
const show = engine === Engine.COSMOSDB;
+ const containers = useMemo(
+ () => schemas.flatMap((schema) => schema.tables.map((table) => table.name)),
+ [schemas]
+ );
+
const options = useMemo(() => {
const opts = [
{
value: OptionValueUnspecified,
- label: t("database.schema.unspecified"),
+ label: t("database.container.unspecified"),
},
];
- for (const schema of schemas) {
- for (const table of schema.tables) {
- opts.push({ value: table.name, label: table.name });
- }
+ for (const container of containers) {
+ opts.push({ value: container, label: container });
}
return opts;
- }, [schemas, t]);
+ }, [containers, t]);
const value = tabTable === undefined ? OptionValueUnspecified : tabTable;
const isChosen = value !== OptionValueUnspecified;
- const handleChange = (next: string) => {
- const tabsState = getSQLEditorTabsState();
- const currentTab = tabsState.tabsById.get(tabsState.currentTabId);
- if (!currentTab) return;
- tabsState.updateCurrentTab({
- connection: {
- ...currentTab.connection,
- table: next === OptionValueUnspecified ? undefined : next,
- },
- });
- };
+ const queryParam = useReactiveRoute().query.table as string | undefined;
+ const currentTabId = useSQLEditorTabState((s) => s.currentTabId);
+ const handleChange = useCallback(
+ (next: string) => {
+ const tabsState = getSQLEditorTabsState();
+ const currentTab = tabsState.tabsById.get(tabsState.currentTabId);
+ if (!currentTab) return;
+ if (next === OptionValueUnspecified && queryParam) {
+ ignoredRouteTableByTab.set(currentTabId, queryParam);
+ } else {
+ ignoredRouteTableByTab.delete(currentTabId);
+ }
+ tabsState.updateCurrentTab({
+ connection: {
+ ...currentTab.connection,
+ table: next === OptionValueUnspecified ? undefined : next,
+ },
+ });
+ },
+ [currentTabId, queryParam]
+ );
// 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 = useReactiveRoute().query.table as string | undefined;
- const currentTabId = useSQLEditorTabState((s) => s.currentTabId);
useEffect(() => {
- if (queryParam) handleChange(queryParam);
- }, [queryParam, currentTabId]);
+ if (!queryParam) {
+ ignoredRouteTableByTab.delete(currentTabId);
+ return;
+ }
+ if (ignoredRouteTableByTab.get(currentTabId) === queryParam) return;
+ handleChange(queryParam);
+ }, [queryParam, currentTabId, handleChange]);
if (!show) return null;
@@ -83,7 +108,10 @@ export function ContainerChooser() {
onChange={handleChange}
options={options}
isChosen={isChosen}
- placeholder={t("database.table.select")}
+ placeholder={t("database.container.select")}
+ dropdownMinWidth={variant === "connection" ? 192 : undefined}
+ openSignal={openSignal}
+ triggerVariant={variant}
/>
);
}
diff --git a/frontend/src/modules/sql-editor/components/EditorAction.test.tsx b/frontend/src/modules/sql-editor/components/EditorAction.test.tsx
index d39e2e903d..c8fdfcf181 100644
--- a/frontend/src/modules/sql-editor/components/EditorAction.test.tsx
+++ b/frontend/src/modules/sql-editor/components/EditorAction.test.tsx
@@ -129,6 +129,11 @@ vi.mock("./AdminModeButton", () => ({
vi.mock("./ChooserGroup", () => ({
ChooserGroup: () => <div data-testid="chooser-group" />,
}));
+vi.mock("./ContainerChooser", () => ({
+ ContainerChooser: ({ variant }: { variant?: string }) => (
+ <div data-testid="run-container-chooser" data-variant={variant} />
+ ),
+}));
vi.mock("./OpenAIButton", () => ({
OpenAIButton: () => <div data-testid="openai-button" />,
}));
@@ -283,6 +288,35 @@ describe("EditorAction", () => {
| HTMLButtonElement
| undefined;
expect(runButton?.disabled).toBe(true);
+ expect(
+ container
+ .querySelector("[data-testid='query-context-setting-popover']")
+ ?.getAttribute("data-disabled")
+ ).toBe("false");
+
+ unmount();
+ });
+
+ test("CosmosDB Run button renders an inline container selector when container is missing", () => {
+ setup({ engine: Engine.COSMOSDB });
+ const onExecute = vi.fn();
+
+ const { container, render, unmount } = renderIntoContainer(
+ <EditorAction onExecute={onExecute} />
+ );
+ render();
+
+ expect(
+ container
+ .querySelector("[data-testid='run-container-chooser']")
+ ?.getAttribute("data-variant")
+ ).toBe("run");
+ expect(onExecute).not.toHaveBeenCalled();
+ expect(
+ container
+ .querySelector("[data-testid='query-context-setting-popover']")
+ ?.getAttribute("data-disabled")
+ ).toBe("false");
unmount();
});
diff --git a/frontend/src/modules/sql-editor/components/EditorAction.tsx b/frontend/src/modules/sql-editor/components/EditorAction.tsx
index 190408e539..b12c0d22de 100644
--- a/frontend/src/modules/sql-editor/components/EditorAction.tsx
+++ b/frontend/src/modules/sql-editor/components/EditorAction.tsx
@@ -25,6 +25,7 @@ import { Engine } from "@/types/proto-es/v1/common_pb";
import { isWorksheetWritableV1, keyboardShortcutStr } from "@/utils";
import { AdminModeButton } from "./AdminModeButton";
import { ChooserGroup } from "./ChooserGroup";
+import { ContainerChooser } from "./ContainerChooser";
import { OpenAIButton } from "./OpenAIButton";
import { QueryContextSettingPopover } from "./QueryContextSettingPopover";
import { SharePopoverBody } from "./SharePopoverBody";
@@ -74,18 +75,13 @@ export function EditorAction({ onExecute }: Props) {
const isAdminMode = tabMode === "ADMIN";
const showSheetsFeature = tabMode === "WORKSHEET";
const isEmptyStatement = !currentTab || tabStatement === "";
-
- const queryTip =
- instance.engine === Engine.COSMOSDB && !tabConnectionTable
- ? t("database.table.select-tip")
- : "";
+ const isCosmosDBWithoutContainer =
+ instance.engine === Engine.COSMOSDB && !tabConnectionTable;
const allowQuery = (() => {
if (isDisconnected) return false;
if (isEmptyStatement) return false;
- if (instance.engine === Engine.COSMOSDB) {
- return !!tabConnectionTable;
- }
+ if (isCosmosDBWithoutContainer) return false;
return true;
})();
@@ -166,22 +162,26 @@ export function EditorAction({ onExecute }: Props) {
{!isAdminMode && (
<div className="inline-flex">
- <Tooltip content={queryTip} side="bottom">
- <Button
- variant="default"
- size="sm"
- className={cn("h-7 px-1.5 gap-1 rounded-r-none text-sm")}
- disabled={!allowQuery}
- onClick={handleRunQuery}
- >
- <Play className="size-4 fill-current" />
- <span className="inline-flex items-center">
- (limit&nbsp;{resultRowsLimit})
- </span>
- </Button>
- </Tooltip>
+ {isCosmosDBWithoutContainer ? (
+ <ContainerChooser variant="run" />
+ ) : (
+ <Tooltip content="" side="bottom">
+ <Button
+ variant="default"
+ size="sm"
+ className={cn("h-7 px-1.5 gap-1 rounded-r-none text-sm")}
+ disabled={!allowQuery}
+ onClick={handleRunQuery}
+ >
+ <Play className="size-4 fill-current" />
+ <span className="inline-flex items-center">
+ (limit&nbsp;{resultRowsLimit})
+ </span>
+ </Button>
+ </Tooltip>
+ )}
<QueryContextSettingPopover
- disabled={!showQueryContextSettingPopover || !allowQuery}
+ disabled={!showQueryContextSettingPopover}
/>
</div>
)}