25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(sidebar): configure production badge scope and sticky context
zipgd5c8d5574aae
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vueindex 1f736a01f9..42a12c627f 100644--- a/apps/desktop/src/components/connection/ConnectionDialog.vue+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue@@ -9,6 +9,8 @@ import { Badge } from "@/components/ui/badge";import { Input } from "@/components/ui/input";import PasswordInput from "@/components/ui/PasswordInput.vue";import { Label } from "@/components/ui/label";+import { sidebarProductionBadgeScope } from "@/lib/sidebar/sidebarProductionBadge";+import type { ProductionBadgeScope } from "@/types/database";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import { HelpTooltip, Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";@@ -454,6 +456,7 @@ const defaultForm = (): ConnectionForm => ({sidebar_auto_load_all_tables: false,is_production: false,production_databases: [],+ production_badge_scope: "database",visible_databases: undefined,save_password: true,});@@ -3147,6 +3150,7 @@ watch(sidebar_auto_load_all_tables: config.sidebar_auto_load_all_tables === true,is_production: config.is_production || false,production_databases: config.production_databases || [],+ production_badge_scope: sidebarProductionBadgeScope(config),visible_databases: config.visible_databases,visible_schemas: config.visible_schemas,save_password: config.save_password !== false,@@ -10311,7 +10315,9 @@ function openExternalUrl(url: string) {</label></div><div class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelSmallClass">{{ t("connection.readOnly") }}</Label>+ <Label :class="connectionLabelSmallClass">+ <span class="inline-flex items-center gap-1">{{ t("connection.readOnly") }} <HelpTooltip :label="t('connection.readOnlyExplanation')" /></span>+ </Label><label class="col-span-3 flex items-center gap-2 cursor-pointer"><input type="checkbox" v-model="form.read_only" class="mr-0" /><span class="text-xs text-muted-foreground">{{ t("connection.readOnlyHint") }}</span>@@ -10354,7 +10360,7 @@ function openExternalUrl(url: string) {</div><div v-if="!isPluginConnection" class="grid grid-cols-4 items-start gap-4 rounded-[6px] border border-red-500/25 bg-red-500/[0.035] px-3 py-2.5"><Label :class="[connectionLabelSmallClass, 'pt-0.5 text-red-700 dark:text-red-300']">- <span class="inline-flex items-center justify-end gap-1"><ShieldAlert class="h-3.5 w-3.5" />PROD</span>+ <span class="inline-flex items-center justify-end gap-1"><ShieldAlert class="h-3.5 w-3.5" />PROD <HelpTooltip :label="t('production.explanation')" trigger-class="text-red-700/70 dark:text-red-300/70" /></span></Label><div class="col-span-3 grid gap-2"><div class="flex items-center justify-between gap-3">@@ -10382,6 +10388,19 @@ function openExternalUrl(url: string) {{{ t(productionScopePickerLabelKey) }}</Button></div>+ <div class="grid gap-1.5 pt-1">+ <Label for="production-badge-scope" class="text-xs font-medium">{{ t("production.badgeScope") }}</Label>+ <Select :model-value="form.production_badge_scope || 'database'" @update:model-value="form.production_badge_scope = $event as ProductionBadgeScope">+ <SelectTrigger id="production-badge-scope" class="h-8" :aria-label="t('production.badgeScope')"><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectItem value="connection">{{ t("production.badgeScopeConnection") }}</SelectItem>+ <SelectItem value="database">{{ t("production.badgeScopeDatabase") }}</SelectItem>+ <SelectItem value="table">{{ t("production.badgeScopeTable") }}</SelectItem>+ </SelectContent>+ </Select>+ <p class="text-xs leading-5 text-muted-foreground">{{ t(`production.badgeScopeHint${form.production_badge_scope === "connection" ? "Connection" : form.production_badge_scope === "table" ? "Table" : "Database"}`) }}</p>+ <p class="text-xs leading-5 text-muted-foreground">{{ t("production.badgeScopeSafetyHint") }}</p>+ </div></template></div></div>diff --git a/apps/desktop/src/components/connection/__tests__/ConnectionDialog.deepLinkEdit.spec.ts b/apps/desktop/src/components/connection/__tests__/ConnectionDialog.deepLinkEdit.spec.tsindex 28153a5f18..469ecb0d92 100644--- a/apps/desktop/src/components/connection/__tests__/ConnectionDialog.deepLinkEdit.spec.ts+++ b/apps/desktop/src/components/connection/__tests__/ConnectionDialog.deepLinkEdit.spec.ts@@ -6,6 +6,8 @@ import i18n from "@/i18n";import type { ConnectionConfig } from "@/types/database";import { parseConnectionDeepLinkUpdate } from "@/lib/connection/connectionDeepLink";+const visibleTab = vi.hoisted(() => ({ value: "connection" }));+const { store, settings, backend } = vi.hoisted(() => ({store: {connectionGroupOptions: [],@@ -121,7 +123,7 @@ vi.mock("@/components/ui/tabs", async () => {setup:(props, { slots }) =>() =>- props.value === "connection" ? h("div", slots.default?.()) : null,+ props.value === visibleTab.value ? h("div", slots.default?.()) : null,});return { Tabs: pass, TabsContent, TabsList: pass, TabsTrigger: pass };});@@ -156,6 +158,7 @@ function savedConnection(overrides: Partial<ConnectionConfig> = {}): ConnectionCread_only: true,is_production: true,production_databases: ["orders"],+ production_badge_scope: "table",save_password: true,visible_databases: ["orders"],url_params: "connectTimeout=25",@@ -192,6 +195,7 @@ async function mountDialog(config: ConnectionConfig, url: string, initiallyOpenbeforeEach(() => {vi.clearAllMocks();+ visibleTab.value = "connection";i18n.global.locale.value = "en";for (const fn of Object.values(backend)) fn.mockResolvedValue([]);backend.listenAgentInstallProgress.mockResolvedValue(() => {});@@ -205,6 +209,30 @@ afterEach(() => {});describe("ConnectionDialog deep-link edit confirmation", () => {+ it("changes the advanced badge picker and persists it while retaining production protection", async () => {+ visibleTab.value = "advanced";+ await mountDialog(savedConnection({ production_badge_scope: "connection" }), "dbx://connection/new?id=saved-production");+ const trigger = document.querySelector<HTMLButtonElement>("#production-badge-scope");+ expect(trigger?.textContent).toContain("Connection");+ trigger!.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ await settle();+ const option = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find((element) => element.textContent?.trim() === "Table / object");+ expect(option).toBeTruthy();+ option!.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ await settle();+ expect(trigger?.textContent).toContain("Table / object");+ const save = [...document.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Save");+ save!.click();+ await settle();+ expect(store.updateConnection).toHaveBeenCalledWith(expect.objectContaining({ production_badge_scope: "table", is_production: true, production_databases: ["orders"] }));+ });++ it("shows the default badge picker for an old saved connection", async () => {+ visibleTab.value = "advanced";+ await mountDialog(savedConnection({ production_badge_scope: undefined }), "dbx://connection/new?id=saved-production");+ expect(document.querySelector("#production-badge-scope")?.textContent).toContain("Database / schema (default)");+ });+it("does not save, connect, or send retained credentials before confirmation", async () => {const saved = savedConnection();await mountDialog(saved, "dbx://connection/new?id=saved-production&host=new.example.test");@@ -254,6 +282,7 @@ describe("ConnectionDialog deep-link edit confirmation", () => {read_only: true,is_production: true,production_databases: ["orders"],+ production_badge_scope: "table",visible_databases: ["orders"],sidebar_auto_load_all_tables: true,url_params: "connectTimeout=25",diff --git a/apps/desktop/src/components/sidebar/ConnectionTree.vue b/apps/desktop/src/components/sidebar/ConnectionTree.vueindex 0193d10f0a..bb46873adb 100644--- a/apps/desktop/src/components/sidebar/ConnectionTree.vue+++ b/apps/desktop/src/components/sidebar/ConnectionTree.vue@@ -65,6 +65,9 @@ import { insertSidebarTableSearchControls, isSidebarTableSearchControlNode } froimport { createSidebarTableSearchDebouncer, invalidateSidebarTableSearchBuild, loadOrBuildSidebarTableSearchIndex, scheduleExclusiveSidebarTableSearchDebounce } from "@/lib/sidebar/sidebarTableSearchIndex";import { runSidebarSearchTasks, type SidebarSearchTask } from "./sidebarSearchTaskRunner";import TreeItem from "./TreeItem.vue";+import ProductionContextBadge from "@/components/common/ProductionContextBadge.vue";+import { showSidebarStickyProductionBadge } from "@/lib/sidebar/sidebarProductionBadge";+import { resolvePlainStickyContainerIndex } from "@/lib/sidebar/sidebarStickyProductionContext";import ActiveConnectionFilterButton from "./ActiveConnectionFilterButton.vue";import SidebarListOptionsIcon from "./SidebarListOptionsIcon.vue";import SidebarLocateButton from "./SidebarLocateButton.vue";@@ -1102,6 +1105,7 @@ watch(// individual rows. A shared overlay can be pushed out by the next connection// boundary, while native sticky rows would cover that non-sticky connection.const stickyScrollTop = ref(0);+const plainStickyContainerIndex = ref(-1);const sidebarScrollMetrics = ref({ scrollTop: 0, scrollLeft: 0, clientHeight: 0, clientWidth: 0, scrollHeight: 0, scrollWidth: 0 });const isScrollingSidebar = ref(false);const isDraggingSidebarScrollbar = ref(false);@@ -1120,6 +1124,13 @@ function updateSidebarScrollMetrics() {}stickyScrollTop.value = scroller.scrollTop;+ if (useVirtualTree.value || isTreeSearchFiltering.value) {+ plainStickyContainerIndex.value = -1;+ } else {+ const scrollerTop = scroller.getBoundingClientRect().top + scroller.clientTop;+ const rows = Array.from(scroller.querySelectorAll<HTMLElement>("[data-node-id]")).map((row) => ({ nodeId: row.dataset.nodeId ?? "", top: row.getBoundingClientRect().top }));+ plainStickyContainerIndex.value = resolvePlainStickyContainerIndex(flatNodes.value, flatTreeIndex.value, rows, scrollerTop);+ }sidebarScrollMetrics.value = {scrollTop: scroller.scrollTop,scrollLeft: scroller.scrollLeft,@@ -1182,6 +1193,7 @@ watch(const stickyContainerIndex = computed(() => {if (isTreeSearchFiltering.value) return -1;+ if (!useVirtualTree.value) return plainStickyContainerIndex.value;const nodes = flatNodes.value;const len = nodes.length;if (len === 0) return -1;@@ -1243,13 +1255,26 @@ const stickyHeaderStyle = computed<CSSProperties>(() => {const nextBoundaryIndex = flatTreeIndex.value.nextBoundaryIndexByIndex[currentIndex] ?? -1;const nextCollisionIndex = nextContainerIndex < 0 ? nextBoundaryIndex : nextBoundaryIndex < 0 ? nextContainerIndex : Math.min(nextContainerIndex, nextBoundaryIndex);if (nextCollisionIndex < 0) return {};- const distanceToNext = nextCollisionIndex * sidebarTreeRowHeight.value - stickyScrollTop.value;+ let distanceToNext = nextCollisionIndex * sidebarTreeRowHeight.value - stickyScrollTop.value;+ if (!useVirtualTree.value) {+ const scroller = plainTreeScrollerRef.value;+ const nextNodeId = flatNodes.value[nextCollisionIndex]?.id;+ const nextRow = nextNodeId ? Array.from(scroller?.querySelectorAll<HTMLElement>("[data-node-id]") ?? []).find((row) => row.dataset.nodeId === nextNodeId) : undefined;+ if (scroller && nextRow) distanceToNext = nextRow.getBoundingClientRect().top - scroller.getBoundingClientRect().top;+ }if (distanceToNext >= stickyHeaderHeight.value) return {};return {transform: `translateY(${Math.min(0, distanceToNext - stickyHeaderHeight.value)}px)`,};});+// Keep the badge outside the translated header so production-to-production+// handovers do not cover or remount it. Both tree renderers share this context.+const stickyProductionContext = computed(() => {+ const node = stickyNode.value?.node;+ return showSidebarStickyProductionBadge(node, node?.connectionId ? store.getConfig(node.connectionId) : undefined);+});+// Clamp tracking when the tree rebuilds, preserving the search input in the// overlay when its results change instead of unmounting it on each keystroke.watch(flatNodes, (nodes, previousNodes) => {@@ -2801,10 +2826,14 @@ defineExpose({ focusSearch, createNewGroup, collapseAllTreeNodes, locateTabInSid:reorder-disabled="true":reference-drag-disabled="true":comment-label-width="sidebarCommentLabelWidths.get(stickyNode.node.id)"+ :is-sticky-context="stickyProductionContext"@context-menu="(event, node) => openSidebarContextMenu(event, node, contextMenuSlot.onContextMenu)"/><TreeItem v-if="stickyTableSearchNode" :key="stickyTableSearchNode.renderKey" :node="stickyTableSearchNode.node" :depth="stickyTableSearchNode.depth" :reorder-disabled="true" :reference-drag-disabled="true" /></div>+ <div v-if="stickyProductionContext" class="sidebar-sticky-production" :style="{ height: `${sidebarTreeRowHeight}px` }">+ <ProductionContextBadge compact />+ </div><divv-if="hasSidebarVerticalOverflow"ref="sidebarScrollbarTrackRef"@@ -2850,10 +2879,14 @@ defineExpose({ focusSearch, createNewGroup, collapseAllTreeNodes, locateTabInSid:reorder-disabled="true":reference-drag-disabled="true":comment-label-width="sidebarCommentLabelWidths.get(stickyNode.node.id)"+ :is-sticky-context="stickyProductionContext"@context-menu="(event, node) => openSidebarContextMenu(event, node, contextMenuSlot.onContextMenu)"/><TreeItem v-if="stickyTableSearchNode" :key="stickyTableSearchNode.renderKey" :node="stickyTableSearchNode.node" :depth="stickyTableSearchNode.depth" :reorder-disabled="true" :reference-drag-disabled="true" /></div>+ <div v-if="stickyProductionContext" class="sidebar-sticky-production" :style="{ height: `${sidebarTreeRowHeight}px` }">+ <ProductionContextBadge compact />+ </div><divv-if="hasSidebarVerticalOverflow"ref="sidebarScrollbarTrackRef"@@ -2993,6 +3026,16 @@ defineExpose({ focusSearch, createNewGroup, collapseAllTreeNodes, locateTabInSid</template><style scoped>+.sidebar-sticky-production {+ pointer-events: none;+ position: absolute;+ top: 0;+ right: 8px;+ z-index: 6;+ display: flex;+ align-items: center;+}+.sticky-database-header {background-color: var(--sidebar);container-type: inline-size;diff --git a/apps/desktop/src/components/sidebar/TreeItem.vue b/apps/desktop/src/components/sidebar/TreeItem.vueindex 7a89718bd5..130faf3853 100644--- a/apps/desktop/src/components/sidebar/TreeItem.vue+++ b/apps/desktop/src/components/sidebar/TreeItem.vue@@ -96,7 +96,7 @@ import { supportsSidebarObjectNameFilter } from "@/lib/sidebar/sidebarObjectNameimport { hasTreeNodeDatabaseContext } from "@/lib/sidebar/treeNodeContext";import { isWindows } from "@/lib/backend/platform";import { flattenTree } from "@/composables/useFlatTree";-import { productionContextForDatabase } from "@/lib/database/productionSafety";+import { showSidebarRowProductionBadge } from "@/lib/sidebar/sidebarProductionBadge";import { focusSidebarRenameInput } from "@/lib/sidebar/sidebarRenameFocus";import { ensureSqlExtension, stripSqlExtension } from "@/lib/savedSql/savedSqlFileName";import { savedSqlErrorMessage } from "@/lib/savedSql/savedSqlErrors";@@ -203,6 +203,8 @@ const props = defineProps<{pendingRename?: boolean;highlighted?: boolean;commentLabelWidth?: number;+ /** This row is rendered as the fixed database/schema context. */+ isStickyContext?: boolean;}>();const emit = defineEmits<{@@ -229,40 +231,9 @@ const activeNode = shallowRef<TreeNode>(props.node);const isDisabledTrigger = computed(() => activeNode.value.type === "trigger" && (activeNode.value.meta as TriggerInfo | undefined)?.enabled === false);-// Marked rows answer "which environment am I looking at" for the connection and-// database that carry the mark, plus the objects below them: a long tree scrolls-// the boundary row out of sight, and that is exactly when the marker is needed.-// Grouping rows (group-*), detail rows (column, index, …) and chrome rows stay-// unmarked so the badge keeps pointing at write targets.-const PRODUCTION_BADGE_NODE_TYPES: ReadonlySet<TreeNode["type"]> = new Set([- "connection",- "database",- "redis-db",- "mongo-db",- "table",- "table-vgroup",- "view",- "materialized_view",- "procedure",- "function",- "sequence",- "synonym",- "type",- "package",- "job",- "extension",- "event-trigger",- "oracle-db-link",- "mongo-collection",- "dynamodb-table",- "vector-collection",- "elasticsearch-index",-]);-const showProductionBadge = computed(() => {- const connectionId = activeNode.value.connectionId;- const context = productionContextForDatabase(connectionId ? connectionStore.getConfig(connectionId) : undefined, activeNode.value.database);- return context.active && PRODUCTION_BADGE_NODE_TYPES.has(activeNode.value.type);+ const node = activeNode.value;+ return showSidebarRowProductionBadge(node, node.connectionId ? connectionStore.getConfig(node.connectionId) : undefined, props.isStickyContext);});function currentDatabaseType(): DatabaseType | undefined {@@ -1057,7 +1028,7 @@ const rowStyle = computed(() => {const backgroundColor = hexToRgba(color, isActiveConnectionScope.value ? 0.14 : 0.08);return {paddingLeft: paddingLeft.value,- paddingRight: trailingComment.value ? "12px" : undefined,+ paddingRight: props.isStickyContext && !showProductionBadge.value ? "72px" : trailingComment.value ? "12px" : undefined,"--tree-connection-row-bg": backgroundColor,"--tree-connection-row-hover-bg": hexToRgba(color, isActiveConnectionScope.value ? 0.2 : 0.16),"--tree-connection-active-bg": hexToRgba(color, 0.18),diff --git a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.stickySearchBoundary.spec.ts b/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.stickySearchBoundary.spec.tsindex f25dfe3e1a..de7e345f79 100644--- a/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.stickySearchBoundary.spec.ts+++ b/apps/desktop/src/components/sidebar/__tests__/ConnectionTree.stickySearchBoundary.spec.ts@@ -33,7 +33,8 @@ function fixture(tree: TreeNode[], grouped: boolean, rowHeight: number) {}),);const stickyScrollTop = ref(0);- const bindings = { computed, flatNodes, flatTreeIndex, stickyScrollTop, sidebarTreeRowHeight: ref(rowHeight), isTreeSearchFiltering: ref(false), isSidebarTableSearchControlNode, SCHEMA_LEVEL_TYPES: new Set(["schema"]) };+ const plainStickyContainerIndex = ref(-1);+ const bindings = { computed, flatNodes, flatTreeIndex, stickyScrollTop, plainStickyContainerIndex, sidebarTreeRowHeight: ref(rowHeight), useVirtualTree: ref(true), isTreeSearchFiltering: ref(false), isSidebarTableSearchControlNode, SCHEMA_LEVEL_TYPES: new Set(["schema"]) };const state = new Function(...Object.keys(bindings), `${compiled}; return {stickyNode, stickyTableSearchNode, stickyHeaderStyle, stickyHeaderHeight};`)(...Object.values(bindings));return {state,diff --git a/apps/desktop/src/components/sidebar/__tests__/TreeItem.productionBadgeScope.spec.ts b/apps/desktop/src/components/sidebar/__tests__/TreeItem.productionBadgeScope.spec.tsindex fb7ffbe7ff..20ce2e8f51 100644--- a/apps/desktop/src/components/sidebar/__tests__/TreeItem.productionBadgeScope.spec.ts+++ b/apps/desktop/src/components/sidebar/__tests__/TreeItem.productionBadgeScope.spec.ts@@ -118,14 +118,14 @@ function createTreeRuntimeHost(): SidebarTreeRuntimeHost {};}-function mountTreeItem(node: TreeNode) {+function mountTreeItem(node: TreeNode, isStickyContext = false) {const container = document.createElement("div");document.body.appendChild(container);const runtime = createSidebarTreeRuntime(createTreeRuntimeHost());const rootComponent = defineComponent({setup() {- return () => h(TreeItem, { node, depth: 1 });+ return () => h(TreeItem, { node, depth: 1, isStickyContext });},});@@ -145,11 +145,45 @@ function rowText(container: HTMLElement, nodeId: string): string {}describe("TreeItem production badge scope", () => {- it("marks object rows inside a production connection", async () => {+ it("keeps the connection's production marker visible", async () => {+ const container = mountTreeItem({ id: "connection-1", label: "Orders", type: "connection", connectionId: productionConnection.id });+ await nextTick();+ expect(rowText(container, "connection-1")).toContain("PROD");+ });++ it.each(["database", "schema"] as const)("reserves space for the independent badge on a fixed %s", async (type) => {+ connection = { ...productionConnection, production_badge_scope: "connection" };+ const container = mountTreeItem({ id: "scope-1", label: "analytics", type, connectionId: productionConnection.id, database: "analytics", schema: "public" }, true);+ await nextTick();+ expect(rowText(container, "scope-1")).not.toContain("PROD");+ expect(container.querySelector<HTMLElement>('[data-node-id="scope-1"]')?.style.paddingRight).toBe("72px");+ });++ it.each(["database", "schema"] as const)("marks ordinary %s rows by default", async (type) => {+ const container = mountTreeItem({ id: "scope-1", label: "analytics", type, connectionId: productionConnection.id, database: "analytics", schema: "public" });+ await nextTick();+ expect(rowText(container, "scope-1")).toContain("PROD");+ });+ it.each(["database", "schema"] as const)("does not mark ordinary %s rows in connection scope", async (type) => {+ connection = { ...productionConnection, production_badge_scope: "connection" };+ const container = mountTreeItem({ id: "scope-connection", label: "analytics", type, connectionId: productionConnection.id, database: "analytics", schema: "public" });+ await nextTick();+ expect(rowText(container, "scope-connection")).not.toContain("PROD");+ });++ it("keeps the fixed database/schema row badge inline outside connection scope", async () => {+ connection = { ...productionConnection, production_badge_scope: "database" };+ const container = mountTreeItem({ id: "scope-inline", label: "analytics", type: "schema", connectionId: productionConnection.id, database: "analytics", schema: "public" }, true);+ await nextTick();+ expect(rowText(container, "scope-inline")).toContain("PROD");+ expect(container.querySelector<HTMLElement>('[data-node-id="scope-inline"]')?.style.paddingRight).toBe("");+ });++ it("leaves ordinary object rows unmarked inside a production connection", async () => {const container = mountTreeItem({ id: "table-1", label: "orders", type: "table", connectionId: productionConnection.id, database: "shop" });await nextTick();- expect(rowText(container, "table-1")).toContain("PROD");+ expect(rowText(container, "table-1")).not.toContain("PROD");});it("keeps grouping and detail rows unmarked", async () => {@@ -177,14 +211,14 @@ describe("TreeItem production badge scope", () => {expect(rowText(container, "table-1")).not.toContain("PROD");});- it("marks object rows only for the databases marked as production", async () => {+ it("leaves ordinary objects unmarked even in a database marked as production", async () => {connection = databaseMarkedConnection;const markedContainer = mountTreeItem({ id: "table-1", label: "orders", type: "table", connectionId: productionConnection.id, database: "analytics" });const otherContainer = mountTreeItem({ id: "table-2", label: "orders", type: "table", connectionId: productionConnection.id, database: "staging" });await nextTick();- expect(rowText(markedContainer, "table-1")).toContain("PROD");+ expect(rowText(markedContainer, "table-1")).not.toContain("PROD");expect(rowText(otherContainer, "table-2")).not.toContain("PROD");});});diff --git a/apps/desktop/src/components/ui/tooltip/HelpTooltip.vue b/apps/desktop/src/components/ui/tooltip/HelpTooltip.vueindex 6e9b1ffa88..ead5c34548 100644--- a/apps/desktop/src/components/ui/tooltip/HelpTooltip.vue+++ b/apps/desktop/src/components/ui/tooltip/HelpTooltip.vue@@ -32,7 +32,7 @@ withDefaults(</button><template #content><div class="px-3 py-1.5 text-xs leading-relaxed" :class="contentClass">- <slot />+ <slot>{{ label }}</slot></div></template></LightTooltip>diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.tsindex 70f8aa2eaf..9bc201af58 100644--- a/apps/desktop/src/i18n/locales/az.ts+++ b/apps/desktop/src/i18n/locales/az.ts@@ -6037,6 +6037,14 @@ export default withEnglishFallback({confirm: "İcra et",},production: {+ badgeScope: "PROD nişanının göstərilmə əhatəsi",+ badgeScopeConnection: "Bağlantı",+ badgeScopeDatabase: "Verilənlər bazası / sxem (standart)",+ badgeScopeTable: "Cədvəl / obyekt",+ badgeScopeHintConnection: "PROD bağlantılarda göstərilir və sürüşdürmə zamanı sabitlənmiş obyektlərdə saxlanılır.",+ badgeScopeHintDatabase: "PROD bağlantılarda və verilənlər bazası və ya sxem yuxarıda sabitlənəndə göstərilir.",+ badgeScopeHintTable: "PROD bağlantılarda, verilənlər bazalarında, sxemlərdə və obyektlərdə göstərilir.",+ badgeScopeSafetyHint: "Yalnız yan panel nişanlarına təsir edir; istehsal mühiti qoruma qaydaları dəyişmir.",title: "İstismar mühiti",connection: "İstismar əlaqəsi",enable: "İstismar mühitinin qorunmasını aktiv et",diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 839cc5bba0..066ee003d5 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -1674,6 +1674,7 @@ export default {keepaliveInterval: "Keepalive Interval (seconds)",readOnly: "Read Only",readOnlyHint: "Block all write operations (INSERT, UPDATE, DELETE, etc.)",+ readOnlyExplanation: "Read-only mode directly blocks writes on this connection. You must temporarily unlock writes before changing data.",doltShowSystemTables: "Show Dolt System Tables",doltShowSystemTablesHint: "Show Dolt's built-in version-control tables in table lists for this connection.",showSystemSchemas: "Show System Schemas",@@ -6968,6 +6969,15 @@ export default {confirm: "Execute",},production: {+ badgeScope: "PROD badge display scope",+ badgeScopeConnection: "Connection",+ badgeScopeDatabase: "Database / schema (default)",+ badgeScopeTable: "Table / object",+ badgeScopeHintConnection: "Show PROD on connection rows, and keep it on pinned objects while scrolling.",+ badgeScopeHintDatabase: "Show PROD on connection, database, and schema rows, including the pinned header.",+ badgeScopeHintTable: "Show PROD on connections, databases, schemas, and object rows.",+ badgeScopeSafetyHint: "Only affects sidebar badges; production protection rules stay unchanged.",+ explanation: "Production protection: writes, DDL, imports, exports, and other changes on production databases require an extra confirmation before they run. Ordinary queries are unaffected. It does not make the connection read-only.",title: "Production environment",connection: "Production connection",enable: "Enable production safeguards",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex db5914207b..2f83b615cf 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -1412,6 +1412,7 @@ export default withEnglishFallback({keepaliveInterval: "Intervalo de keepalive (segundos)",readOnly: "Solo lectura",readOnlyHint: "Bloquear todas las operaciones de escritura (INSERT, UPDATE, DELETE, etc.)",+ readOnlyExplanation: "El modo de solo lectura bloquea directamente las escrituras en esta conexión. Debes desbloquearlas temporalmente antes de modificar datos.",readOnlyBadge: "Solo lectura",proxy: "Proxy",proxyType: "Tipo de proxy",@@ -10652,6 +10653,15 @@ export default withEnglishFallback({presetSchemaDesc: "Definición del schema actual del tema",},production: {+ badgeScope: "Alcance visual de PROD",+ badgeScopeConnection: "Conexión",+ badgeScopeDatabase: "Base de datos / esquema (predeterminado)",+ badgeScopeTable: "Tabla / objeto",+ badgeScopeHintConnection: "Mostrar PROD en las conexiones y mantenerlo en los objetos fijados al desplazarse.",+ badgeScopeHintDatabase: "Mostrar PROD en las conexiones y cuando una base de datos o esquema quede fijado arriba.",+ badgeScopeHintTable: "Mostrar PROD en conexiones, bases de datos, esquemas y objetos.",+ badgeScopeSafetyHint: "Solo afecta a las etiquetas de la barra lateral; no cambia las reglas de protección.",+ explanation: "Protección de producción: las escrituras, DDL, importaciones, exportaciones y otros cambios en bases de datos de producción requieren una confirmación adicional antes de ejecutarse. Las consultas normales no se ven afectadas. No convierte la conexión en solo lectura.",title: "Entorno de producción",connection: "Conexión de producción",enable: "Activar protección del entorno de producción",diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.tsindex 4123b4d84a..a7cc2662b6 100644--- a/apps/desktop/src/i18n/locales/id.ts+++ b/apps/desktop/src/i18n/locales/id.ts@@ -6703,6 +6703,14 @@ export default withEnglishFallback({confirm: "Jalankan",},production: {+ badgeScope: "Cakupan tampilan PROD",+ badgeScopeConnection: "Koneksi",+ badgeScopeDatabase: "Basis data / skema (default)",+ badgeScopeTable: "Tabel / objek",+ badgeScopeHintConnection: "Tampilkan PROD pada koneksi dan pertahankan pada objek yang disematkan saat menggulir.",+ badgeScopeHintDatabase: "Tampilkan PROD pada koneksi dan saat basis data atau skema disematkan di bagian atas.",+ badgeScopeHintTable: "Tampilkan PROD pada koneksi, basis data, skema, dan objek.",+ badgeScopeSafetyHint: "Hanya memengaruhi penanda bilah sisi; aturan perlindungan produksi tidak berubah.",title: "Lingkungan produksi",connection: "Koneksi produksi",enable: "Aktifkan pengaman produksi",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 012b6fc0e4..e07d55714a 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -1334,6 +1334,7 @@ export default withEnglishFallback({keepaliveInterval: "Intervallo keepalive (secondi)",readOnly: "Sola lettura",readOnlyHint: "Blocca tutte le operazioni di scrittura (INSERT, UPDATE, DELETE, ecc.)",+ readOnlyExplanation: "La modalità di sola lettura blocca direttamente le scritture su questa connessione. Devi sbloccare temporaneamente le scritture prima di modificare i dati.",readOnlyBadge: "Sola lettura",proxy: "Proxy",proxyType: "Tipo Proxy",@@ -10394,6 +10395,15 @@ export default withEnglishFallback({presetSchemaDesc: "Definizione schema topic corrente",},production: {+ badgeScope: "Ambito di visualizzazione PROD",+ badgeScopeConnection: "Connessione",+ badgeScopeDatabase: "Database / schema (predefinito)",+ badgeScopeTable: "Tabella / oggetto",+ badgeScopeHintConnection: "Mostra PROD nelle connessioni e mantienilo sugli oggetti fissi durante lo scorrimento.",+ badgeScopeHintDatabase: "Mostra PROD nelle connessioni e quando un database o schema viene fissato in alto.",+ badgeScopeHintTable: "Mostra PROD nelle connessioni, nei database, negli schemi e negli oggetti.",+ badgeScopeSafetyHint: "Modifica solo i badge della barra laterale; le regole di protezione restano invariate.",+ explanation: "Protezione della produzione: scritture, DDL, importazioni, esportazioni e altre modifiche nei database di produzione richiedono una conferma aggiuntiva prima dell esecuzione. Le query normali non sono interessate. La connessione non viene resa di sola lettura.",title: "Ambiente di produzione",connection: "Connessione di produzione",enable: "Abilita protezione ambiente di produzione",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 2f9cae833d..512386cc3e 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -1304,6 +1304,7 @@ export default withEnglishFallback({keepaliveInterval: "Keepalive 間隔(秒)",readOnly: "読み取り専用",readOnlyHint: "すべての書き込み操作(INSERT, UPDATE, DELETEなど)をブロックします",+ readOnlyExplanation: "読み取り専用モードでは、この接続への書き込みを直接ブロックします。データを変更するには、一時的に書き込みを解除する必要があります。",readOnlyBadge: "読み取り専用",proxy: "プロキシ",proxyType: "プロキシタイプ",@@ -10432,6 +10433,15 @@ export default withEnglishFallback({presetSchemaDesc: "現在のトピックスキーマ定義",},production: {+ badgeScope: "PROD バッジの表示範囲",+ badgeScopeConnection: "接続",+ badgeScopeDatabase: "データベース / スキーマ(既定)",+ badgeScopeTable: "テーブル / オブジェクト",+ badgeScopeHintConnection: "接続行に PROD を表示し、スクロール中も固定されたオブジェクトに表示します。",+ badgeScopeHintDatabase: "接続行に PROD を表示し、データベースまたはスキーマが上部に固定されたときに表示します。",+ badgeScopeHintTable: "接続、データベース、スキーマ、オブジェクト行に PROD を表示します。",+ badgeScopeSafetyHint: "サイドバーの表示のみを変更します。本番環境の保護ルールは変わりません。",+ explanation: "本番環境の保護:本番データベースへの書き込み、DDL、インポート、エクスポートなどの変更を実行する前に、追加の確認を求めます。通常のクエリには影響しません。接続を読み取り専用にはしません。",title: "本番環境",connection: "本番接続",enable: "本番環境保護を有効にする",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 1572384a22..5ad3e4111c 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -1489,6 +1489,7 @@ export default withEnglishFallback({keepaliveInterval: "킵얼라이브 간격 (초)",readOnly: "읽기 전용",readOnlyHint: "모든 쓰기 작업 차단 (INSERT, UPDATE, DELETE 등)",+ readOnlyExplanation: "읽기 전용 모드는 이 연결의 쓰기 작업을 직접 차단합니다. 데이터를 변경하려면 일시적으로 쓰기 잠금을 해제해야 합니다.",showSystemSchemas: "시스템 스키마 표시",showSystemSchemasHint: "이 연결의 사이드바와 스키마 선택기에 내장 및 메타데이터 스키마를 표시합니다.",showDatabaseLinks: "데이터베이스 링크 표시",@@ -5951,6 +5952,15 @@ export default withEnglishFallback({confirm: "실행",},production: {+ badgeScope: "PROD 표시 범위",+ badgeScopeConnection: "연결",+ badgeScopeDatabase: "데이터베이스 / 스키마 (기본값)",+ badgeScopeTable: "테이블 / 객체",+ badgeScopeHintConnection: "연결 행에 PROD를 표시하고 스크롤 중에도 고정된 객체에 표시합니다.",+ badgeScopeHintDatabase: "연결 행에 PROD를 표시하고 데이터베이스 또는 스키마가 상단에 고정될 때 표시합니다.",+ badgeScopeHintTable: "연결, 데이터베이스, 스키마 및 객체 행에 PROD를 표시합니다.",+ badgeScopeSafetyHint: "사이드바 표시에만 영향을 주며 운영 환경 보호 규칙은 변경하지 않습니다.",+ explanation: "운영 환경 보호: 운영 데이터베이스에서 쓰기, DDL, 가져오기, 내보내기 및 기타 변경 작업을 실행하기 전에 추가 확인을 요청합니다. 일반 쿼리에는 영향을 주지 않으며 연결을 읽기 전용으로 만들지 않습니다.",title: "프로덕션 환경",connection: "프로덕션 연결",enable: "프로덕션 보호 활성화",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex aff7c0ce56..4127fd459f 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -1335,6 +1335,7 @@ export default withEnglishFallback({keepaliveInterval: "Intervalo de keepalive (segundos)",readOnly: "Somente leitura",readOnlyHint: "Bloquear todas as operações de escrita (INSERT, UPDATE, DELETE, etc.)",+ readOnlyExplanation: "O modo somente leitura bloqueia diretamente as gravações nesta conexão. É necessário desbloquear temporariamente as gravações antes de alterar dados.",readOnlyBadge: "Somente leitura",proxy: "Proxy",proxyType: "Tipo de Proxy",@@ -10391,6 +10392,15 @@ export default withEnglishFallback({presetSchemaDesc: "Definição atual do schema do tópico",},production: {+ badgeScope: "Escopo visual de PROD",+ badgeScopeConnection: "Conexão",+ badgeScopeDatabase: "Banco de dados / esquema (padrão)",+ badgeScopeTable: "Tabela / objeto",+ badgeScopeHintConnection: "Mostrar PROD nas conexões e mantê-lo nos objetos fixos durante a rolagem.",+ badgeScopeHintDatabase: "Mostrar PROD nas conexões e quando um banco de dados ou esquema for fixado no topo.",+ badgeScopeHintTable: "Mostrar PROD nas conexões, bancos de dados, esquemas e objetos.",+ badgeScopeSafetyHint: "Afeta apenas os marcadores da barra lateral; as regras de proteção não mudam.",+ explanation: "Proteção de produção: gravações, DDL, importações, exportações e outras alterações em bancos de dados de produção exigem uma confirmação extra antes da execução. Consultas comuns não são afetadas. A conexão não é transformada em somente leitura.",title: "Ambiente de Produção",connection: "Conexão de Produção",enable: "Ativar proteção de ambiente de produção",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex a3269d89e9..5e4a0761b0 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -1584,6 +1584,7 @@ export default withEnglishFallback({keepaliveInterval: "Интервал keepalive (секунды)",readOnly: "Только чтение",readOnlyHint: "Блокировать все операции записи (INSERT, UPDATE, DELETE и т. д.)",+ readOnlyExplanation: "Режим только для чтения напрямую блокирует запись в этом подключении. Перед изменением данных запись необходимо временно разблокировать.",doltShowSystemTables: "Показывать системные таблицы Dolt",doltShowSystemTablesHint: "Показывать встроенные таблицы контроля версий Dolt в списках таблиц для этого подключения.",showSystemSchemas: "Показывать системные схемы",@@ -7378,6 +7379,15 @@ export default withEnglishFallback({confirm: "Выполнить",},production: {+ badgeScope: "Область отображения PROD",+ badgeScopeConnection: "Подключение",+ badgeScopeDatabase: "База данных / схема (по умолчанию)",+ badgeScopeTable: "Таблица / объект",+ badgeScopeHintConnection: "Показывать PROD в подключениях и сохранять его на закреплённых объектах при прокрутке.",+ badgeScopeHintDatabase: "Показывать PROD в подключениях и при закреплении базы данных или схемы вверху.",+ badgeScopeHintTable: "Показывать PROD в подключениях, базах данных, схемах и объектах.",+ badgeScopeSafetyHint: "Меняет только метки в боковой панели; правила защиты рабочей среды не меняются.",+ explanation: "Защита рабочей среды: для записи, DDL, импорта, экспорта и других изменений в рабочих базах данных требуется дополнительное подтверждение. Обычные запросы не затрагиваются. Подключение не переводится в режим только для чтения.",title: "Продуктивная среда",connection: "Продуктивное подключение",enable: "Включить защиту продуктивной среды",diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.tsindex 7ed8766e73..e8e3a366b7 100644--- a/apps/desktop/src/i18n/locales/tr.ts+++ b/apps/desktop/src/i18n/locales/tr.ts@@ -5931,6 +5931,14 @@ export default withEnglishFallback({confirm: "Çalıştır",},production: {+ badgeScope: "PROD gösterim kapsamı",+ badgeScopeConnection: "Bağlantı",+ badgeScopeDatabase: "Veritabanı / şema (varsayılan)",+ badgeScopeTable: "Tablo / nesne",+ badgeScopeHintConnection: "PROD bağlantılarda gösterilir ve kaydırırken sabitlenmiş nesnelerde korunur.",+ badgeScopeHintDatabase: "PROD bağlantılarda ve veritabanı veya şema üstte sabitlendiğinde gösterilir.",+ badgeScopeHintTable: "PROD bağlantılarda, veritabanlarında, şemalarda ve nesnelerde gösterilir.",+ badgeScopeSafetyHint: "Yalnızca kenar çubuğu işaretlerini etkiler; üretim koruma kuralları değişmez.",title: "Üretim ortamı",connection: "Üretim bağlantısı",enable: "Üretim korumalarını etkinleştir",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 10282f3963..4948251e62 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -1613,6 +1613,7 @@ export default withEnglishFallback({keepaliveInterval: "保持连接间隔(秒)",readOnly: "只读模式",readOnlyHint: "阻止所有写操作(INSERT、UPDATE、DELETE 等)",+ readOnlyExplanation: "只读模式:直接阻止当前连接的写操作,需要临时解锁后才能写入。",doltShowSystemTables: "显示 Dolt 内置表",doltShowSystemTablesHint: "在当前连接的表列表中显示 Dolt 内置的版本控制表。",showSystemSchemas: "显示系统 Schema",@@ -6951,6 +6952,15 @@ export default withEnglishFallback({confirm: "执行",},production: {+ badgeScope: "PROD 标记显示范围",+ badgeScopeConnection: "连接",+ badgeScopeDatabase: "库 / 模式(默认)",+ badgeScopeTable: "表 / 对象",+ badgeScopeHintConnection: "在连接行显示 PROD;滚动时,顶部固定对象也保留对应的 PROD 提示。",+ badgeScopeHintDatabase: "在连接、库和模式行显示 PROD,固定到顶部时也保留标记。",+ badgeScopeHintTable: "连接、库、模式及表等对象行均显示 PROD。",+ badgeScopeSafetyHint: "仅影响侧边栏标记显示,不改变生产环境保护规则。",+ explanation: "生产保护:对生产库的写入、DDL、导入导出等变更操作,执行前要求再次确认;普通查询不受影响。它不会把连接设为只读。",title: "生产环境",connection: "生产连接",enable: "启用生产环境保护",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 1e34d18758..fa3de78287 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -1665,6 +1665,7 @@ export default withEnglishFallback({mqttClientCertPath: "用戶端憑證路徑",mqttClientKeyPath: "用戶端私鑰路徑",mqttNoLocal: "禁止本機轉送",+ readOnlyExplanation: "唯讀模式:直接阻止目前連線的寫入操作,需要暫時解鎖後才能寫入。",},editor: {duckdbDraining: "上一筆 DuckDB 查詢仍在停止,請稍後重試。",@@ -10406,6 +10407,14 @@ export default withEnglishFallback({presetSchemaDesc: "檢視主題目前 schema 定義",},production: {+ badgeScope: "PROD 標記顯示範圍",+ badgeScopeConnection: "連線",+ badgeScopeDatabase: "資料庫 / 結構描述(預設)",+ badgeScopeTable: "資料表 / 物件",+ badgeScopeHintConnection: "在連線列顯示 PROD;捲動時,頂端固定物件也保留對應的 PROD 提示。",+ badgeScopeHintDatabase: "在連線、資料庫與結構描述列顯示 PROD,固定在頂端時也保留標記。",+ badgeScopeHintTable: "連線、資料庫、結構描述及資料表等物件列均顯示 PROD。",+ badgeScopeSafetyHint: "僅影響側邊欄標記顯示,不改變正式環境保護規則。",title: "生產環境",connection: "生產連線",enable: "啟用生產環境保護",@@ -10461,6 +10470,7 @@ export default withEnglishFallback({sourceAdmin: "資料庫管理",aiReviewRequired: "生產 SQL 已放入編輯器。請先檢查,再手動執行以確認。",sourceMultiDbSql: "多庫 SQL 執行",+ explanation: "生產保護:對生產資料庫的寫入、DDL、匯入匯出等變更操作,執行前要求再次確認;一般查詢不受影響。它不會把連線設為唯讀。",},readOnlyUnlock: {confirmTitle: "暫時解鎖寫入",diff --git a/apps/desktop/src/lib/connection/__tests__/connectionSubmitNormalization.spec.ts b/apps/desktop/src/lib/connection/__tests__/connectionSubmitNormalization.spec.tsindex 94467b4473..13ed60e5c2 100644--- a/apps/desktop/src/lib/connection/__tests__/connectionSubmitNormalization.spec.ts+++ b/apps/desktop/src/lib/connection/__tests__/connectionSubmitNormalization.spec.ts@@ -16,6 +16,18 @@ function config(overrides: Partial<ConnectionConfig> = {}): ConnectionConfig {}describe("connection submit normalization", () => {+ it.each(["connection", "database", "table"] as const)("preserves %s badge scope without changing production protection", (scope) => {+ const value = config({ production_badge_scope: scope, is_production: true, production_databases: ["app"] });+ normalizeConnectionScope(value);+ expect(value).toMatchObject({ production_badge_scope: scope, is_production: true, production_databases: ["app"] });+ });++ it("defaults legacy connections to database/schema badges", () => {+ const value = config();+ normalizeConnectionScope(value);+ expect(value.production_badge_scope).toBe("database");+ });+it("normalizes invalid timeout values and inherited global values", () => {const inherited = config({ connect_timeout_inherit: true, query_timeout_inherit: true, idle_timeout_secs: -1, keepalive_interval_secs: Number.NaN });normalizeConnectionTimeouts(inherited, 12, 34);diff --git a/apps/desktop/src/lib/connection/connectionSubmitNormalization.ts b/apps/desktop/src/lib/connection/connectionSubmitNormalization.tsindex c2d6a9ffc6..81d184f674 100644--- a/apps/desktop/src/lib/connection/connectionSubmitNormalization.ts+++ b/apps/desktop/src/lib/connection/connectionSubmitNormalization.ts@@ -1,3 +1,4 @@+import { sidebarProductionBadgeScope } from "@/lib/sidebar/sidebarProductionBadge";import { normalizeIdleTimeoutSecs } from "@/lib/connection/timeoutLimits";import { isSingleDatabase } from "@/lib/database/databaseFeatureSupport";import { normalizeGlobalConnectTimeoutSecs, normalizeGlobalQueryTimeoutSecs } from "@/stores/settingsStore";@@ -13,6 +14,7 @@ export function normalizeConnectionTimeouts(config: ConnectionConfig, connectTim}export function normalizeConnectionScope(config: ConnectionConfig): void {+ config.production_badge_scope = sidebarProductionBadgeScope(config);if (!config.one_time) config.one_time = undefined;if (!config.read_only) config.read_only = undefined;// Persist only an explicit opt-out; absent/true keeps the existing save-password behavior.diff --git a/apps/desktop/src/lib/diagram/explainPlan.ts b/apps/desktop/src/lib/diagram/explainPlan.tsindex 93b2e0a10f..803eb19978 100644--- a/apps/desktop/src/lib/diagram/explainPlan.ts+++ b/apps/desktop/src/lib/diagram/explainPlan.ts@@ -414,6 +414,7 @@ function parseSqlServerExplain(result: QueryResult): ParsedExplainPlan {if (!raw) throw new Error("SQL Server did not return ShowPlan XML");if (typeof DOMParser === "undefined") throw new Error("XML parser is unavailable");+ if (!hasBalancedXmlTags(raw)) throw new Error("Invalid SQL Server ShowPlan XML");const parserIssues: string[] = [];type XmlParserConstructor = new (options?: { onError?: (level: string, message: string) => void }) => DOMParser;const Parser = DOMParser as unknown as XmlParserConstructor;@@ -446,6 +447,23 @@ function parseSqlServerExplain(result: QueryResult): ParsedExplainPlan {};}+function hasBalancedXmlTags(xml: string): boolean {+ const stack: string[] = [];+ const tokens = xml.match(/<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<\?[^>]*\?>|<!DOCTYPE[^>]*>|<\/?[A-Za-z_][\w:.-]*(?:\s[^<>]*?)?\/?>/gi);+ if (!tokens || xml.replace(/<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<\?[^>]*\?>|<!DOCTYPE[^>]*>|<\/?[A-Za-z_][\w:.-]*(?:\s[^<>]*?)?\/?>/gi, "").includes("<")) return false;+ for (const token of tokens) {+ if (token.startsWith("<!--") || token.startsWith("<![CDATA[") || token.startsWith("<?") || /^<!DOCTYPE/i.test(token)) continue;+ const closing = /^<\//.test(token);+ const selfClosing = /\/\s*>$/.test(token);+ const name = token.match(/^<\/?([A-Za-z_][\w:.-]*)/)?.[1];+ if (!name) return false;+ if (closing) {+ if (stack.pop() !== name) return false;+ } else if (!selfClosing) stack.push(name);+ }+ return stack.length === 0;+}+function firstSqlServerShowplanXml(result: QueryResult): string | undefined {for (const row of result.rows) {for (const cell of row) {diff --git a/apps/desktop/src/lib/sidebar/__tests__/sidebarProductionBadge.spec.ts b/apps/desktop/src/lib/sidebar/__tests__/sidebarProductionBadge.spec.tsnew file mode 100644index 0000000000..4c666fc248--- /dev/null+++ b/apps/desktop/src/lib/sidebar/__tests__/sidebarProductionBadge.spec.ts@@ -0,0 +1,65 @@+import { describe, expect, it } from "vitest";+import { sidebarProductionBadgeScope, showSidebarRowProductionBadge, showSidebarStickyProductionBadge } from "../sidebarProductionBadge";+import { assessProductionSql } from "@/lib/database/productionSafety";+import type { ConnectionConfig, ProductionBadgeScope, TreeNodeType } from "@/types/database";++const connection: ConnectionConfig = { id: "c", name: "prod", db_type: "postgres", host: "localhost", port: 5432, username: "", password: "", is_production: true };+const node = (type: TreeNodeType, database = "app") => ({ type, database });++describe("production badge display scope", () => {+ it("defaults old and missing connections to database scope", () => {+ expect(sidebarProductionBadgeScope(connection)).toBe("database");+ expect(sidebarProductionBadgeScope(undefined)).toBe("database");+ expect(sidebarProductionBadgeScope({ ...connection, production_badge_scope: "unknown" as ProductionBadgeScope })).toBe("database");+ });++ it.each(["connection", "database", "table"] as const)("retains the connection marker in %s scope", (scope) => {+ expect(showSidebarRowProductionBadge(node("connection"), { ...connection, production_badge_scope: scope })).toBe(true);+ });++ it.each(["database", "schema", "table", "view", "procedure", "mongo-collection", "nacos-namespace"] as const)("respects the selected range on ordinary %s rows", (type) => {+ for (const scope of ["connection", "database", "table"] as const) {+ expect(showSidebarRowProductionBadge(node(type), { ...connection, production_badge_scope: scope })).toBe(scope === "table" || (scope === "database" && ["database", "schema", "nacos-namespace"].includes(type)));+ }+ });++ it.each(["group-tables", "column", "index", "connection-group", "table-search-control"] as const)("keeps %s unmarked in table scope", (type) => {+ expect(showSidebarRowProductionBadge(node(type), { ...connection, production_badge_scope: "table" })).toBe(false);+ });++ it.each(["connection", "database", "table"] as const)("resolves the sticky badge in %s scope", (scope) => {+ const config = { ...connection, production_badge_scope: scope };+ expect(showSidebarStickyProductionBadge(node("schema"), config)).toBe(scope === "connection");+ expect(showSidebarRowProductionBadge(node("database"), config, true)).toBe(scope !== "connection");+ expect(showSidebarStickyProductionBadge(undefined, config)).toBe(false);+ });++ it("does not transfer database-only production markers to other databases", () => {+ const config = { ...connection, is_production: false, production_databases: ["app"], production_badge_scope: "table" as const };+ expect(showSidebarRowProductionBadge(node("connection", ""), config)).toBe(false);+ expect(showSidebarRowProductionBadge(node("schema"), config)).toBe(true);+ expect(showSidebarRowProductionBadge(node("table", "other"), config)).toBe(false);+ expect(showSidebarStickyProductionBadge(node("schema", "other"), config)).toBe(false);+ });++ it.each(["connection", "database", "table"] as const)("clears the fixed marker when entering a non-production database in %s scope", (scope) => {+ const config = { ...connection, is_production: false, production_databases: ["app"], production_badge_scope: scope };+ expect(showSidebarStickyProductionBadge(node("schema"), config)).toBe(scope === "connection");+ expect(showSidebarStickyProductionBadge(node("schema", "other"), config)).toBe(false);+ expect(showSidebarStickyProductionBadge(node("schema"), { ...config, production_databases: [] })).toBe(false);+ });++ it("warns on the connection for selected production databases in connection-only mode", () => {+ const config = { ...connection, is_production: false, production_databases: ["app"], production_badge_scope: "connection" as const };+ expect(showSidebarRowProductionBadge(node("connection", ""), config)).toBe(true);+ expect(showSidebarRowProductionBadge(node("table"), config)).toBe(false);+ expect(assessProductionSql("DELETE FROM orders", config, "other").active).toBe(false);+ expect(assessProductionSql("DELETE FROM orders", config, "app").active).toBe(true);+ });++ it.each(["connection", "database", "table"] as const)("leaves SQL production protection intact in %s scope", (scope) => {+ const config = { ...connection, production_badge_scope: scope };+ expect(assessProductionSql("DELETE FROM orders", config, "app")).toMatchObject({ active: true, isMutation: true, reason: "connection" });+ expect(assessProductionSql("DELETE FROM app.orders", { ...config, db_type: "mysql", is_production: false, production_databases: ["app"] }, "other")).toMatchObject({ active: true, isMutation: true });+ });+});diff --git a/apps/desktop/src/lib/sidebar/__tests__/sidebarStickyProductionContext.spec.ts b/apps/desktop/src/lib/sidebar/__tests__/sidebarStickyProductionContext.spec.tsnew file mode 100644index 0000000000..2363d08326--- /dev/null+++ b/apps/desktop/src/lib/sidebar/__tests__/sidebarStickyProductionContext.spec.ts@@ -0,0 +1,82 @@+import { describe, expect, it } from "vitest";+import { createFlatTreeIndex, flattenTree } from "@/composables/useFlatTree";+import { resolvePlainStickyContainerIndex, resolveSidebarStickyProductionNode } from "@/lib/sidebar/sidebarStickyProductionContext";+import { productionContextForDatabase } from "@/lib/database/productionSafety";+import type { ConnectionConfig, TreeNode, TreeNodeType } from "@/types/database";++function node(id: string, type: TreeNodeType, children: TreeNode[] = []): TreeNode {+ return { id, label: id, type, connectionId: "connection", database: id, isExpanded: true, children };+}++function fixture(roots: TreeNode[]) {+ const nodes = flattenTree(roots);+ const index = createFlatTreeIndex(nodes, {+ isSelectable: () => true,+ isBoundary: (type) => type === "connection" || type === "connection-group",+ isDatabaseContainer: (type) => type === "database",+ isSchemaContainer: (type) => type === "schema",+ });+ return { nodes, index, resolve: (current: number, scroll: number, height = 28) => resolveSidebarStickyProductionNode(nodes, index, current, scroll, height)?.id ?? null };+}++const production: ConnectionConfig = { id: "connection", name: "Reporting", db_type: "postgres", host: "localhost", port: 5432, username: "", password: "", production_databases: ["production"] };++describe("sidebar sticky production context", () => {+ it("uses real plain-row positions instead of switching by the estimated row height", () => {+ const scope = fixture([node("connection", "connection", [node("first", "database", [node("query", "saved-sql-root")]), node("second", "database")])]);+ const rows = scope.nodes.map((item, index) => ({ nodeId: item.id, top: 100 + index * 29 }));+ const firstTop = scope.nodes.findIndex((item) => item.id === "first");+ const secondTop = scope.nodes.findIndex((item) => item.id === "second");+ expect(+ resolvePlainStickyContainerIndex(+ scope.nodes,+ scope.index,+ rows.map((row) => ({ ...row, top: row.top - 29 })),+ 100,+ ),+ ).toBe(firstTop);+ expect(resolvePlainStickyContainerIndex(scope.nodes, scope.index, rows, 100)).toBe(-1);+ expect(secondTop).toBeGreaterThan(firstTop);+ });++ it("has no marker before a container becomes fixed", () => {+ expect(fixture([node("connection", "connection")]).resolve(-1, 0)).toBeNull();+ });++ it.each(["database", "schema"] as const)("transfers the fixed %s context as the next row begins to cover it", (type) => {+ const scope = fixture([node("connection", "connection", [node("production", type, [node("table", "table")]), node("staging", type)])]);+ expect(scope.resolve(1, 55)).toBe("production");+ expect(scope.resolve(1, 57)).toBe("staging");+ expect(scope.resolve(3, 85)).toBe("staging");+ const incoming = resolveSidebarStickyProductionNode(scope.nodes, scope.index, 1, 57, 28);+ expect(productionContextForDatabase(production, incoming?.node.database).active).toBe(false);+ });++ it("does not let a production marker cross a connection boundary", () => {+ const scope = fixture([node("prod-connection", "connection", [node("production", "database", [node("table", "table")])]), node("other-connection", "connection", [node("other", "database")])]);+ expect(scope.resolve(1, 55)).toBe("production");+ expect(scope.resolve(1, 57)).toBeNull();+ expect(scope.resolve(-1, 85)).toBeNull();+ expect(scope.resolve(4, 113)).toBe("other");+ });++ it("ends the old context at a group boundary before the next connection", () => {+ const scope = fixture([node("connection", "connection", [node("production", "database", [node("table", "table")])]), node("group", "connection-group", [node("next-connection", "connection", [node("other", "database")])])]);+ expect(scope.resolve(1, 57)).toBeNull();+ });++ it("uses compact row height for the same handover", () => {+ const scope = fixture([node("connection", "connection", [node("production", "database", [node("table", "table")]), node("staging", "database")])]);+ expect(scope.resolve(1, 47, 24)).toBe("production");+ expect(scope.resolve(1, 49, 24)).toBe("staging");+ });++ it("retains production through a production-to-production handover", () => {+ const scope = fixture([node("connection", "connection", [node("production", "database", [node("table", "table")]), node("second-production", "database")])]);+ const connection = { ...production, production_databases: ["production", "second-production"] };+ for (const scroll of [55, 57, 83, 85]) {+ const incoming = resolveSidebarStickyProductionNode(scope.nodes, scope.index, scroll < 84 ? 1 : 3, scroll, 28);+ expect(productionContextForDatabase(connection, incoming?.node.database).active).toBe(true);+ }+ });+});diff --git a/apps/desktop/src/lib/sidebar/sidebarProductionBadge.ts b/apps/desktop/src/lib/sidebar/sidebarProductionBadge.tsnew file mode 100644index 0000000000..bb1e4a2a6f--- /dev/null+++ b/apps/desktop/src/lib/sidebar/sidebarProductionBadge.ts@@ -0,0 +1,53 @@+import { productionContextForDatabase, productionDatabases } from "@/lib/database/productionSafety";+import type { ConnectionConfig, ProductionBadgeScope, TreeNode } from "@/types/database";++const productionContainerTypes: ReadonlySet<TreeNode["type"]> = new Set(["database", "schema", "redis-db", "mongo-db", "mq-tenant", "nacos-namespace", "consul-root"]);++const productionObjectTypes: ReadonlySet<TreeNode["type"]> = new Set([+ "database",+ "schema",+ "redis-db",+ "mongo-db",+ "mq-tenant",+ "nacos-namespace",+ "consul-root",+ "table",+ "table-vgroup",+ "view",+ "materialized_view",+ "procedure",+ "function",+ "sequence",+ "synonym",+ "type",+ "package",+ "job",+ "extension",+ "event-trigger",+ "oracle-db-link",+ "mongo-collection",+ "dynamodb-table",+ "vector-collection",+ "elasticsearch-index",+]);++export function sidebarProductionBadgeScope(connection: ConnectionConfig | undefined): ProductionBadgeScope {+ const scope = connection?.production_badge_scope;+ return scope === "connection" || scope === "table" ? scope : "database";+}++export function showSidebarRowProductionBadge(node: Pick<TreeNode, "type" | "database">, connection: ConnectionConfig | undefined, stickyContext = false): boolean {+ const scope = sidebarProductionBadgeScope(connection);+ if (stickyContext && scope === "connection") return false;+ const active = productionContextForDatabase(connection, node.database).active;+ // Connection-only display must still warn when just selected databases are+ // production; the safety scope remains limited to those databases.+ if (node.type === "connection") return active || (scope === "connection" && productionDatabases(connection).length > 0);+ return active && ((scope === "database" && productionContainerTypes.has(node.type)) || (scope === "table" && productionObjectTypes.has(node.type)));+}++export function showSidebarStickyProductionBadge(node: Pick<TreeNode, "database"> | undefined, connection: ConnectionConfig | undefined): boolean {+ // Only connection scope needs a separate fixed badge. Database/schema and+ // table/object scopes render the badge on the fixed row itself.+ return !!node && sidebarProductionBadgeScope(connection) === "connection" && productionContextForDatabase(connection, node.database).active;+}diff --git a/apps/desktop/src/lib/sidebar/sidebarStickyProductionContext.ts b/apps/desktop/src/lib/sidebar/sidebarStickyProductionContext.tsnew file mode 100644index 0000000000..af53950922--- /dev/null+++ b/apps/desktop/src/lib/sidebar/sidebarStickyProductionContext.ts@@ -0,0 +1,32 @@+import type { FlatTreeIndex, FlatTreeNode } from "@/composables/useFlatTree";++/** Resolve the context entering the fixed header's first row during handover. */+export function resolveSidebarStickyProductionNode(nodes: readonly FlatTreeNode[], index: FlatTreeIndex, currentIndex: number, scrollTop: number, rowHeight: number): FlatTreeNode | null {+ const current = nodes[currentIndex];+ if (currentIndex < 0 || !current) return null;+ const nextContainer = current.type === "schema" ? index.nextSchemaContainerIndexByIndex[currentIndex] : index.nextDatabaseContainerIndexByIndex[currentIndex];+ const nextBoundary = index.nextBoundaryIndexByIndex[currentIndex] ?? -1;+ const nextCollision = nextContainer < 0 ? nextBoundary : nextBoundary < 0 ? nextContainer : Math.min(nextContainer, nextBoundary);+ if (nextCollision < 0 || nextCollision * rowHeight - scrollTop >= rowHeight) return current;+ // A connection/group boundary ends the previous container's production scope.+ return nextCollision === nextBoundary ? null : (nodes[nextCollision] ?? null);+}++/**+ * Resolve the fixed container for a plain DOM tree from actual row positions.+ * This avoids switching early when rendered rows are taller than the virtual+ * row-height estimate (for example after a query node or font-size change).+ */+export function resolvePlainStickyContainerIndex(_nodes: readonly FlatTreeNode[], index: FlatTreeIndex, rows: readonly { nodeId: string; top: number }[], scrollerTop: number): number {+ let pinnedIndex = -1;+ for (const row of rows) {+ const flatIndex = index.flatNodeIndexById.get(row.nodeId);+ if (flatIndex == null) continue;+ if (row.top <= scrollerTop + 0.5) {+ pinnedIndex = index.stickyContainerIndexByIndex[flatIndex] ?? -1;+ continue;+ }+ break;+ }+ return pinnedIndex;+}diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.tsindex 42c4d40e0d..8925c54b44 100644--- a/apps/desktop/src/types/database.ts+++ b/apps/desktop/src/types/database.ts@@ -182,10 +182,14 @@ export interface ConnectionConfig {is_production?: boolean;/** Database-level production markers for multi-database connections. */production_databases?: string[];+ /** Sidebar presentation only; absent means database/schema rows plus sticky context. */+ production_badge_scope?: ProductionBadgeScope;/** Metadata captured from the latest successful connection test for the saved config. */database_info?: DatabaseConnectionInfo;}+export type ProductionBadgeScope = "connection" | "database" | "table";+export type IdentifierCase = "lower" | "upper" | "mixed";export interface DatabaseConnectionInfo {diff --git a/crates/dbx-core/examples/table_import_live_bench.rs b/crates/dbx-core/examples/table_import_live_bench.rsindex 928bf71b32..aca90889d4 100644--- a/crates/dbx-core/examples/table_import_live_bench.rs+++ b/crates/dbx-core/examples/table_import_live_bench.rs@@ -220,6 +220,7 @@ fn connection_config(id: &str, database: BenchDatabase) -> Result<ConnectionConfread_only: false,is_production: false,production_databases: Vec::new(),+ production_badge_scope: None,database_info: None,})}diff --git a/crates/dbx-core/src/admin/mq/config.rs b/crates/dbx-core/src/admin/mq/config.rsindex a9396c9bb7..716ccac643 100644--- a/crates/dbx-core/src/admin/mq/config.rs+++ b/crates/dbx-core/src/admin/mq/config.rs@@ -245,6 +245,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,};cfg.redis_key_separator = ":".to_string();diff --git a/crates/dbx-core/src/admin/mq/service.rs b/crates/dbx-core/src/admin/mq/service.rsindex 66ec323978..09ae32a8f3 100644--- a/crates/dbx-core/src/admin/mq/service.rs+++ b/crates/dbx-core/src/admin/mq/service.rs@@ -991,6 +991,7 @@ mod tests {read_only,is_production: false,production_databases: Vec::new(),+ production_badge_scope: None,database_info: None,}}diff --git a/crates/dbx-core/src/admin/nacos/config.rs b/crates/dbx-core/src/admin/nacos/config.rsindex 4eb18afc17..41c1b55fbe 100644--- a/crates/dbx-core/src/admin/nacos/config.rs+++ b/crates/dbx-core/src/admin/nacos/config.rs@@ -432,6 +432,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}diff --git a/crates/dbx-core/src/admin/nacos/service.rs b/crates/dbx-core/src/admin/nacos/service.rsindex c64df0af63..3ec33e84e9 100644--- a/crates/dbx-core/src/admin/nacos/service.rs+++ b/crates/dbx-core/src/admin/nacos/service.rs@@ -708,6 +708,7 @@ mod tests {read_only: true,is_production: false,production_databases: Vec::new(),+ production_badge_scope: None,database_info: None,};cfg.read_only = true;@@ -795,6 +796,7 @@ mod tests {read_only: true,is_production: false,production_databases: Vec::new(),+ production_badge_scope: None,database_info: None,};state.configs.write().await.insert(cfg.id.clone(), cfg);diff --git a/crates/dbx-core/src/ai/agent_tools.rs b/crates/dbx-core/src/ai/agent_tools.rsindex ab9d155242..152c499e57 100644--- a/crates/dbx-core/src/ai/agent_tools.rs+++ b/crates/dbx-core/src/ai/agent_tools.rs@@ -2059,6 +2059,7 @@ for line in sys.stdin:read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}diff --git a/crates/dbx-core/src/connection/connection_secrets.rs b/crates/dbx-core/src/connection/connection_secrets.rsindex 395524f605..c9b21a6a04 100644--- a/crates/dbx-core/src/connection/connection_secrets.rs+++ b/crates/dbx-core/src/connection/connection_secrets.rs@@ -1096,6 +1096,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}diff --git a/crates/dbx-core/src/connection/mod.rs b/crates/dbx-core/src/connection/mod.rsindex 52ca966825..fcd2d239d7 100644--- a/crates/dbx-core/src/connection/mod.rs+++ b/crates/dbx-core/src/connection/mod.rs@@ -7480,6 +7480,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}@@ -10033,6 +10034,7 @@ sleep 30read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,show_system_schemas: false,sidebar_auto_load_all_tables: false,show_database_links: None,diff --git a/crates/dbx-core/src/data/transfer.rs b/crates/dbx-core/src/data/transfer.rsindex 388e1fb7c2..46a1a6de64 100644--- a/crates/dbx-core/src/data/transfer.rs+++ b/crates/dbx-core/src/data/transfer.rs@@ -13599,6 +13599,7 @@ for line in sys.stdin:read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,docs_notes_path: None,}@@ -20749,6 +20750,7 @@ SELECT 1 FROM dual"#read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,};let mut gbase_jdbc = config.clone();diff --git a/crates/dbx-core/src/persistence/cloud_sync.rs b/crates/dbx-core/src/persistence/cloud_sync.rsindex debeff4d7f..bd7124c495 100644--- a/crates/dbx-core/src/persistence/cloud_sync.rs+++ b/crates/dbx-core/src/persistence/cloud_sync.rs@@ -3584,6 +3584,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}@@ -3680,6 +3681,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}@@ -3985,6 +3987,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,};config.connection_secrets.insert("api_token".to_string(), "plugin-secret".to_string());diff --git a/crates/dbx-core/src/persistence/storage.rs b/crates/dbx-core/src/persistence/storage.rsindex e3b422ead7..b09bec901a 100644--- a/crates/dbx-core/src/persistence/storage.rs+++ b/crates/dbx-core/src/persistence/storage.rs@@ -11923,6 +11923,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}@@ -12003,6 +12004,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}diff --git a/crates/dbx-core/src/query/mod.rs b/crates/dbx-core/src/query/mod.rsindex 784e15821e..c5a744c92d 100644--- a/crates/dbx-core/src/query/mod.rs+++ b/crates/dbx-core/src/query/mod.rs@@ -8580,6 +8580,7 @@ for line in sys.stdin:read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}@@ -11703,6 +11704,7 @@ for line in sys.stdin:read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,};diff --git a/crates/dbx-core/src/safety/production_safety.rs b/crates/dbx-core/src/safety/production_safety.rsindex e1c52149a2..a24319bec2 100644--- a/crates/dbx-core/src/safety/production_safety.rs+++ b/crates/dbx-core/src/safety/production_safety.rs@@ -946,6 +946,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec!["prod_app".to_string()],+ production_badge_scope: None,database_info: None,}}diff --git a/crates/dbx-core/src/schema/mod.rs b/crates/dbx-core/src/schema/mod.rsindex 9b214b5029..049faa88e7 100644--- a/crates/dbx-core/src/schema/mod.rs+++ b/crates/dbx-core/src/schema/mod.rs@@ -3403,6 +3403,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}diff --git a/crates/dbx-core/src/schema/normalization.rs b/crates/dbx-core/src/schema/normalization.rsindex 058b86ea8e..b09fe49d61 100644--- a/crates/dbx-core/src/schema/normalization.rs+++ b/crates/dbx-core/src/schema/normalization.rs@@ -204,6 +204,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}diff --git a/crates/dbx-core/tests/connection_url_compatibility.rs b/crates/dbx-core/tests/connection_url_compatibility.rsindex cb616f4c9b..682a2645b4 100644--- a/crates/dbx-core/tests/connection_url_compatibility.rs+++ b/crates/dbx-core/tests/connection_url_compatibility.rs@@ -72,6 +72,7 @@ fn mysql_config(username: &str, password: &str, database: Option<&str>) -> Conneread_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}diff --git a/crates/dbx-core/tests/dump_docs_fixture.rs b/crates/dbx-core/tests/dump_docs_fixture.rsindex 172a470e0b..4e77dba503 100644--- a/crates/dbx-core/tests/dump_docs_fixture.rs+++ b/crates/dbx-core/tests/dump_docs_fixture.rs@@ -84,6 +84,7 @@ fn live_postgres_config(read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,show_system_schemas: false,sidebar_auto_load_all_tables: false,show_database_links: None,diff --git a/crates/dbx-core/tests/live_postgres_docs_annotations.rs b/crates/dbx-core/tests/live_postgres_docs_annotations.rsindex 63ab0eef7d..2cdfeb592e 100644--- a/crates/dbx-core/tests/live_postgres_docs_annotations.rs+++ b/crates/dbx-core/tests/live_postgres_docs_annotations.rs@@ -80,6 +80,7 @@ fn live_postgres_config(read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,show_system_schemas: false,sidebar_auto_load_all_tables: false,show_database_links: None,diff --git a/crates/dbx-core/tests/live_postgres_docs_snapshot.rs b/crates/dbx-core/tests/live_postgres_docs_snapshot.rsindex 75186edaa9..d15189b91c 100644--- a/crates/dbx-core/tests/live_postgres_docs_snapshot.rs+++ b/crates/dbx-core/tests/live_postgres_docs_snapshot.rs@@ -75,6 +75,7 @@ fn live_postgres_config(read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,show_system_schemas: false,sidebar_auto_load_all_tables: false,show_database_links: None,diff --git a/crates/dbx-core/tests/live_postgres_error_position.rs b/crates/dbx-core/tests/live_postgres_error_position.rsindex 840e68ed2a..5d97e159d9 100644--- a/crates/dbx-core/tests/live_postgres_error_position.rs+++ b/crates/dbx-core/tests/live_postgres_error_position.rs@@ -229,6 +229,7 @@ fn live_connection_config(read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,show_system_schemas: false,sidebar_auto_load_all_tables: false,show_database_links: None,diff --git a/crates/dbx-core/tests/live_postgres_query_result_export.rs b/crates/dbx-core/tests/live_postgres_query_result_export.rsindex 150484e73b..1ec328ce46 100644--- a/crates/dbx-core/tests/live_postgres_query_result_export.rs+++ b/crates/dbx-core/tests/live_postgres_query_result_export.rs@@ -80,6 +80,7 @@ fn live_postgres_config(read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,show_system_schemas: false,sidebar_auto_load_all_tables: false,show_database_links: None,diff --git a/crates/dbx-core/tests/live_postgres_transfer.rs b/crates/dbx-core/tests/live_postgres_transfer.rsindex 2f49c13e9b..2dc1998e58 100644--- a/crates/dbx-core/tests/live_postgres_transfer.rs+++ b/crates/dbx-core/tests/live_postgres_transfer.rs@@ -75,6 +75,7 @@ fn postgres_test_config(id: &str, database: &str) -> ConnectionConfig {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,show_system_schemas: false,sidebar_auto_load_all_tables: false,show_database_links: None,diff --git a/crates/dbx-core/tests/live_sqlite_to_sqlserver_transfer.rs b/crates/dbx-core/tests/live_sqlite_to_sqlserver_transfer.rsindex 60c0bd0a3e..20864a9eb9 100644--- a/crates/dbx-core/tests/live_sqlite_to_sqlserver_transfer.rs+++ b/crates/dbx-core/tests/live_sqlite_to_sqlserver_transfer.rs@@ -79,6 +79,7 @@ fn sqlite_config(id: &str, path: &str) -> ConnectionConfig {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,show_system_schemas: false,sidebar_auto_load_all_tables: false,show_database_links: None,diff --git a/crates/dbx-core/tests/live_sqlserver_completion.rs b/crates/dbx-core/tests/live_sqlserver_completion.rsindex 4a97e80b8b..b8973b4867 100644--- a/crates/dbx-core/tests/live_sqlserver_completion.rs+++ b/crates/dbx-core/tests/live_sqlserver_completion.rs@@ -81,6 +81,7 @@ fn live_sqlserver_config(id: &str, database: &str) -> dbx_core::models::connectiread_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,show_system_schemas: false,sidebar_auto_load_all_tables: false,show_database_links: None,diff --git a/crates/dbx-core/tests/live_sqlserver_query_result_export.rs b/crates/dbx-core/tests/live_sqlserver_query_result_export.rsindex 3a56397615..4c28a295ad 100644--- a/crates/dbx-core/tests/live_sqlserver_query_result_export.rs+++ b/crates/dbx-core/tests/live_sqlserver_query_result_export.rs@@ -70,6 +70,7 @@ fn live_sqlserver_config(id: &str, database: &str) -> dbx_core::models::connectiread_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,show_system_schemas: false,sidebar_auto_load_all_tables: false,show_database_links: None,diff --git a/crates/dbx-core/tests/live_sqlserver_split_zip_e2e.rs b/crates/dbx-core/tests/live_sqlserver_split_zip_e2e.rsindex 98693a9d43..9d94b2638a 100644--- a/crates/dbx-core/tests/live_sqlserver_split_zip_e2e.rs+++ b/crates/dbx-core/tests/live_sqlserver_split_zip_e2e.rs@@ -85,6 +85,7 @@ fn live_sqlserver_config(id: &str, database: &str) -> dbx_core::models::connectiread_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,show_system_schemas: false,database_info: None,sidebar_auto_load_all_tables: false,diff --git a/crates/dbx-core/tests/live_sqlserver_transfer.rs b/crates/dbx-core/tests/live_sqlserver_transfer.rsindex dd3fc610ad..d561f00ea8 100644--- a/crates/dbx-core/tests/live_sqlserver_transfer.rs+++ b/crates/dbx-core/tests/live_sqlserver_transfer.rs@@ -74,6 +74,7 @@ fn live_sqlserver_config(id: &str, database: &str) -> ConnectionConfig {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,show_system_schemas: false,sidebar_auto_load_all_tables: false,show_database_links: None,diff --git a/crates/dbx-core/tests/support/mod.rs b/crates/dbx-core/tests/support/mod.rsindex 7460755934..0a8510ab5f 100644--- a/crates/dbx-core/tests/support/mod.rs+++ b/crates/dbx-core/tests/support/mod.rs@@ -195,6 +195,7 @@ pub fn postgres_test_config(id: &str, port: u16) -> ConnectionConfig {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,show_system_schemas: false,sidebar_auto_load_all_tables: false,show_database_links: None,diff --git a/crates/dbx-driver-agent/src/agent_connection.rs b/crates/dbx-driver-agent/src/agent_connection.rsindex 1050089796..b90621e22e 100644--- a/crates/dbx-driver-agent/src/agent_connection.rs+++ b/crates/dbx-driver-agent/src/agent_connection.rs@@ -851,6 +851,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}diff --git a/crates/dbx-driver-redis/src/lib.rs b/crates/dbx-driver-redis/src/lib.rsindex e89f0acf27..4fd851ba7e 100644--- a/crates/dbx-driver-redis/src/lib.rs+++ b/crates/dbx-driver-redis/src/lib.rs@@ -10298,6 +10298,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}diff --git a/crates/dbx-types/src/models/connection.rs b/crates/dbx-types/src/models/connection.rsindex 7d04eb7554..958f0f5e86 100644--- a/crates/dbx-types/src/models/connection.rs+++ b/crates/dbx-types/src/models/connection.rs@@ -122,6 +122,15 @@ pub struct RedisKeyGrouping {pub rules: Vec<RedisKeyGroupRule>,}+/// Sidebar marker presentation only; never changes production safety assessment.+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum ProductionBadgeScope {+ Connection,+ Database,+ Table,+}+#[derive(Clone, Serialize, PartialEq)]pub struct ConnectionConfig {pub id: String,@@ -284,6 +293,8 @@ pub struct ConnectionConfig {/// Database-level production markers for multi-database connections.#[serde(default, skip_serializing_if = "Vec::is_empty")]pub production_databases: Vec<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub production_badge_scope: Option<ProductionBadgeScope>,/// Metadata captured from the latest successful connection test for this saved config.#[serde(default, skip_serializing_if = "Option::is_none")]pub database_info: Option<DatabaseConnectionInfo>,@@ -739,6 +750,8 @@ struct ConnectionConfigData {pub is_production: bool,#[serde(default)]pub production_databases: Vec<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub production_badge_scope: Option<ProductionBadgeScope>,#[serde(default)]pub database_info: Option<DatabaseConnectionInfo>,}@@ -812,6 +825,7 @@ impl From<ConnectionConfigData> for ConnectionConfig {read_only: data.read_only,is_production: data.is_production,production_databases: data.production_databases,+ production_badge_scope: data.production_badge_scope,database_info: data.database_info,}}@@ -3001,7 +3015,7 @@ mod tests {database_info_from_protocol_value, default_query_timeout_secs, default_redis_key_separator,default_ssh_connect_timeout_secs, sqlserver_legacy_compatibility_param,without_sqlserver_legacy_compatibility_param, ConnectionConfig, ConnectionTestResult, DatabaseConnectionInfo,- DatabaseType, IdentifierCase, ProxyTunnelConfig, ProxyType, TransportLayerConfig,+ DatabaseType, IdentifierCase, ProductionBadgeScope, ProxyTunnelConfig, ProxyType, TransportLayerConfig,};#[test]@@ -3095,6 +3109,33 @@ mod tests {assert!(serde_json::to_value(configured).unwrap()["sidebar_auto_load_all_tables"].as_bool().unwrap());}+ #[test]+ fn production_badge_scope_legacy_and_all_options_round_trip() {+ let mut value = serde_json::to_value(mysql_config("root", "", Some("app"))).unwrap();+ value["is_production"] = serde_json::json!(true);+ value["production_databases"] = serde_json::json!(["app"]);+ let legacy: ConnectionConfig = serde_json::from_value(value.clone()).unwrap();+ assert_eq!(legacy.production_badge_scope, None);+ assert!(serde_json::to_value(legacy).unwrap().get("production_badge_scope").is_none());+ for (name, expected) in [+ ("connection", ProductionBadgeScope::Connection),+ ("database", ProductionBadgeScope::Database),+ ("table", ProductionBadgeScope::Table),+ ] {+ value["production_badge_scope"] = serde_json::json!(name);+ let config: ConnectionConfig = serde_json::from_value(value.clone()).unwrap();+ assert_eq!(config.production_badge_scope, Some(expected));+ assert!(config.is_production);+ assert_eq!(config.production_databases, vec!["app"]);+ let serialized = serde_json::to_value(&config).unwrap();+ assert_eq!(serialized["production_badge_scope"], name);+ assert_eq!(+ serde_json::from_value::<ConnectionConfig>(serialized).unwrap().production_badge_scope,+ Some(expected)+ );+ }+ }+#[test]fn show_database_links_opt_out_round_trips() {let mut value = serde_json::json!({@@ -3183,6 +3224,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}diff --git a/crates/dbx-web/src/routes/connection.rs b/crates/dbx-web/src/routes/connection.rsindex 72e2f955b3..d8dcbd7fe0 100644--- a/crates/dbx-web/src/routes/connection.rs+++ b/crates/dbx-web/src/routes/connection.rs@@ -1128,6 +1128,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}diff --git a/crates/dbx-web/src/routes/docs.rs b/crates/dbx-web/src/routes/docs.rsindex ca4716ddc8..79f249b3fb 100644--- a/crates/dbx-web/src/routes/docs.rs+++ b/crates/dbx-web/src/routes/docs.rs@@ -271,6 +271,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}diff --git a/crates/dbx-web/src/routes/transfer.rs b/crates/dbx-web/src/routes/transfer.rsindex b70ed93e9b..9d31acd223 100644--- a/crates/dbx-web/src/routes/transfer.rs+++ b/crates/dbx-web/src/routes/transfer.rs@@ -845,6 +845,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}diff --git a/src-tauri/src/commands/connection.rs b/src-tauri/src/commands/connection.rsindex d0e96440bd..2ff62c009a 100644--- a/src-tauri/src/commands/connection.rs+++ b/src-tauri/src/commands/connection.rs@@ -304,6 +304,7 @@ mod tests {read_only: false,is_production: false,production_databases: vec![],+ production_badge_scope: None,database_info: None,}}