Skip to content

armgit / dbx

Public Imported from GitHub
0

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。

feat(connection): expose global timeout settings and a connect-failure shortcut

HighBigSkyea4331499f8a
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index 190559f16e..c65b944adf 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -5380,6 +5380,7 @@ onUnmounted(() => {
@start-resize="startSidebarResize"
@collapse="setSidebarOpen(false)"
@open-settings="(initialTab) => openSettings(initialTab ?? 'appearance')"
+ @open-connection-settings="(connectionId) => openConnectionSettings(connectionId, 'advanced')"
@add-to-ai="addToAi"
@open-dependency-object="onOpenDependencyObject"
@mousedown="rememberSidebarSearchSurface"
diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
index dc118b3522..d846a20078 100644
--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue
+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
@@ -6,6 +6,7 @@ import type { Ref } from "vue";
import type { EditorView as EditorViewType } from "@codemirror/view";
import { useI18n } from "vue-i18n";
import { translateBackendError } from "@/i18n/backend-errors";
+import { MAX_CONNECT_TIMEOUT_SECS, MAX_QUERY_TIMEOUT_SECS } from "@/lib/connection/timeoutLimits";
import {
AlertTriangle,
ArrowLeft,
@@ -745,6 +746,9 @@ const showDataGridTypeColorScheme = ref(false);
const editExecuteMode = ref(settingsStore.editorSettings.executeMode);
const editDefaultTransactionMode = ref(settingsStore.editorSettings.defaultTransactionMode);
const editKeepExplicitTransactionInAutoCommit = ref(settingsStore.editorSettings.keepExplicitTransactionInAutoCommit);
+// 全局连接/查询超时(秒):与连接编辑对话框「全局」档共用同一落盘字段,查询超时 0 表示不限制(#13233)。
+const editGlobalConnectTimeoutSecs = ref(settingsStore.editorSettings.globalConnectTimeoutSecs);
+const editGlobalQueryTimeoutSecs = ref(settingsStore.editorSettings.globalQueryTimeoutSecs);
const editShortcuts = ref(normalizeShortcutSettings(settingsStore.editorSettings.shortcuts));
function translateWithExecuteShortcut(key: string): string {
return t(key, { shortcut: formatShortcutDisplay(editShortcuts.value.executeSql) });
@@ -1196,6 +1200,8 @@ function currentEditorSettingsDraft(): EditorSettingsDraft {
executeMode: editExecuteMode.value,
defaultTransactionMode: editDefaultTransactionMode.value,
keepExplicitTransactionInAutoCommit: editKeepExplicitTransactionInAutoCommit.value,
+ globalConnectTimeoutSecs: editGlobalConnectTimeoutSecs.value,
+ globalQueryTimeoutSecs: editGlobalQueryTimeoutSecs.value,
executeAllOnBlankLine: editExecuteAllOnBlankLine.value,
showExecutionTargetPicker: editShowExecutionTargetPicker.value,
showStatementRunButtons: editShowStatementRunButtons.value,
@@ -1896,6 +1902,8 @@ function syncEditorSettingsDraftFromStore() {
editExecuteMode.value = settingsStore.editorSettings.executeMode;
editDefaultTransactionMode.value = settingsStore.editorSettings.defaultTransactionMode;
editKeepExplicitTransactionInAutoCommit.value = settingsStore.editorSettings.keepExplicitTransactionInAutoCommit;
+ editGlobalConnectTimeoutSecs.value = settingsStore.editorSettings.globalConnectTimeoutSecs;
+ editGlobalQueryTimeoutSecs.value = settingsStore.editorSettings.globalQueryTimeoutSecs;
editExecuteAllOnBlankLine.value = settingsStore.editorSettings.executeAllOnBlankLine;
editShowExecutionTargetPicker.value = settingsStore.editorSettings.showExecutionTargetPicker;
editShowStatementRunButtons.value = settingsStore.editorSettings.showStatementRunButtons;
@@ -2230,6 +2238,8 @@ const editorSettingsDraftRefs: EditorSettingsDraftRefMap = {
excludedCompletionItems: editExcludedCompletionItems,
defaultTransactionMode: editDefaultTransactionMode,
keepExplicitTransactionInAutoCommit: editKeepExplicitTransactionInAutoCommit,
+ globalConnectTimeoutSecs: editGlobalConnectTimeoutSecs,
+ globalQueryTimeoutSecs: editGlobalQueryTimeoutSecs,
tableColumnTemplateFields: editTableColumnTemplateRows,
modelGenerationTemplates: editModelGenerationTemplates,
};
@@ -2580,6 +2590,9 @@ async function persistSettings() {
// 同理:落盘口径可能改写键位(跨平台默认键、保留键回退),草稿要跟着回到
// 落盘值,避免面板卡在“未保存”无法应用(#9881)。
editShortcuts.value = normalizeShortcutSettings(settingsStore.editorSettings.shortcuts);
+ // 全局超时同样会被落盘口径截断(连接 1~300、查询 0~3600),回填避免输入框残留越界值(#13233)。
+ editGlobalConnectTimeoutSecs.value = settingsStore.editorSettings.globalConnectTimeoutSecs;
+ editGlobalQueryTimeoutSecs.value = settingsStore.editorSettings.globalQueryTimeoutSecs;
}
if (pendingBackgroundImageCleanup) {
const cleanupPath = pendingBackgroundImageCleanup;
@@ -2674,6 +2687,8 @@ function resetDefaultsForTab(tab: SettingsCategory) {
editExecuteMode.value = DEFAULT_EDITOR_SETTINGS.executeMode;
editDefaultTransactionMode.value = DEFAULT_EDITOR_SETTINGS.defaultTransactionMode;
editKeepExplicitTransactionInAutoCommit.value = DEFAULT_EDITOR_SETTINGS.keepExplicitTransactionInAutoCommit;
+ editGlobalConnectTimeoutSecs.value = DEFAULT_EDITOR_SETTINGS.globalConnectTimeoutSecs;
+ editGlobalQueryTimeoutSecs.value = DEFAULT_EDITOR_SETTINGS.globalQueryTimeoutSecs;
editExecuteAllOnBlankLine.value = DEFAULT_EDITOR_SETTINGS.executeAllOnBlankLine;
editShowExecutionTargetPicker.value = DEFAULT_EDITOR_SETTINGS.showExecutionTargetPicker;
editShowStatementRunButtons.value = DEFAULT_EDITOR_SETTINGS.showStatementRunButtons;
@@ -2874,6 +2889,8 @@ function resetAllDefaults() {
editExecuteMode.value = DEFAULT_EDITOR_SETTINGS.executeMode;
editDefaultTransactionMode.value = DEFAULT_EDITOR_SETTINGS.defaultTransactionMode;
editKeepExplicitTransactionInAutoCommit.value = DEFAULT_EDITOR_SETTINGS.keepExplicitTransactionInAutoCommit;
+ editGlobalConnectTimeoutSecs.value = DEFAULT_EDITOR_SETTINGS.globalConnectTimeoutSecs;
+ editGlobalQueryTimeoutSecs.value = DEFAULT_EDITOR_SETTINGS.globalQueryTimeoutSecs;
editExecuteAllOnBlankLine.value = DEFAULT_EDITOR_SETTINGS.executeAllOnBlankLine;
editShowExecutionTargetPicker.value = DEFAULT_EDITOR_SETTINGS.showExecutionTargetPicker;
editShowStatementRunButtons.value = DEFAULT_EDITOR_SETTINGS.showStatementRunButtons;
@@ -7909,6 +7926,28 @@ onUnmounted(() => {
</div>
<Switch id="editor-continue-on-error" v-model="editContinueOnErrorOnBatch" class="mt-0.5" />
</div>
+
+ <!-- 全局连接超时(秒):连接编辑对话框「全局」档读取的就是这个值(#13233) -->
+ <div class="settings-item flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2 md:col-span-2" data-editor-global-connect-timeout>
+ <div class="min-w-0 space-y-1">
+ <Label for="editor-global-connect-timeout">{{ t("connection.connectTimeout") }}</Label>
+ <p class="text-xs text-muted-foreground">
+ {{ t("connection.globalConnectTimeoutHint") }}
+ </p>
+ </div>
+ <Input id="editor-global-connect-timeout" v-model.number="editGlobalConnectTimeoutSecs" type="number" min="1" :max="MAX_CONNECT_TIMEOUT_SECS" step="1" class="h-8 w-24 shrink-0 text-right" />
+ </div>
+
+ <!-- 全局查询超时(秒):0 表示不限制,与连接编辑对话框「全局」档口径一致(#13233) -->
+ <div class="settings-item flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2 md:col-span-2" data-editor-global-query-timeout>
+ <div class="min-w-0 space-y-1">
+ <Label for="editor-global-query-timeout">{{ t("connection.queryTimeout") }}</Label>
+ <p class="text-xs text-muted-foreground">
+ {{ t("connection.globalQueryTimeoutHint") }}
+ </p>
+ </div>
+ <Input id="editor-global-query-timeout" v-model.number="editGlobalQueryTimeoutSecs" type="number" min="0" :max="MAX_QUERY_TIMEOUT_SECS" step="1" class="h-8 w-24 shrink-0 text-right" />
+ </div>
</div>
<Separator />
diff --git a/apps/desktop/src/components/editor/SqlParameterDialog.vue b/apps/desktop/src/components/editor/SqlParameterDialog.vue
index 0e1d7274fd..80deaf41f5 100644
--- a/apps/desktop/src/components/editor/SqlParameterDialog.vue
+++ b/apps/desktop/src/components/editor/SqlParameterDialog.vue
@@ -46,6 +46,7 @@ const syntaxLabels: Record<SqlParameterSyntax, string> = {
positional: "?",
named: ":name",
shell: "${name}",
+ "bracketed-shell": "[${name}]",
mybatis: "#{name}",
sqlserver: "@name",
substitution: "&name",
diff --git a/apps/desktop/src/components/layout/AppSidebar.vue b/apps/desktop/src/components/layout/AppSidebar.vue
index bc90e9ea13..0ce8de2ff2 100644
--- a/apps/desktop/src/components/layout/AppSidebar.vue
+++ b/apps/desktop/src/components/layout/AppSidebar.vue
@@ -32,6 +32,7 @@ const emit = defineEmits<{
startResize: [event: PointerEvent];
collapse: [];
"open-settings": [initialTab: string];
+ "open-connection-settings": [connectionId: string];
"add-to-ai": [nodes: TreeNode | TreeNode[]];
"open-dependency-object": [context: ObjectDependencyTarget, target: SqlObjectNavigationTarget];
}>();
@@ -334,7 +335,13 @@ defineExpose({ focusSearch, locateTabInSidebar, disconnectAllActiveConnections,
</template>
</div>
<div data-sidebar-connection-tree class="flex-1 min-h-0">
- <ConnectionTree ref="connectionTreeRef" @open-settings="(initialTab) => emit('open-settings', initialTab)" @add-to-ai="(nodes) => emit('add-to-ai', nodes)" @open-dependency-object="(context, target) => emit('open-dependency-object', context, target)" />
+ <ConnectionTree
+ ref="connectionTreeRef"
+ @open-settings="(initialTab) => emit('open-settings', initialTab)"
+ @open-connection-settings="(connectionId) => emit('open-connection-settings', connectionId)"
+ @add-to-ai="(nodes) => emit('add-to-ai', nodes)"
+ @open-dependency-object="(context, target) => emit('open-dependency-object', context, target)"
+ />
</div>
<div v-if="activeConnectionEndpoint" data-sidebar-connection-endpoint class="flex shrink-0 items-center gap-1.5 border-t border-border/60 px-2.5 py-1.5 text-[11px] leading-none text-muted-foreground" :title="activeWindowConnection?.name">
<Server class="h-3 w-3 shrink-0" />
diff --git a/apps/desktop/src/components/sidebar/ConnectionTree.vue b/apps/desktop/src/components/sidebar/ConnectionTree.vue
index 0c0dc66890..d5653401ec 100644
--- a/apps/desktop/src/components/sidebar/ConnectionTree.vue
+++ b/apps/desktop/src/components/sidebar/ConnectionTree.vue
@@ -137,6 +137,7 @@ const sidebarContextMenuItems = ref<ContextMenuItem[]>([]);
const { presentMenu, SidebarMenuPreferencesDialog, sidebarMenuPreferencesOpen, sidebarMenuPreferences } = useSidebarMenuPresentation();
const emit = defineEmits<{
"open-settings": [initialTab: string];
+ "open-connection-settings": [connectionId: string];
"add-to-ai": [nodes: TreeNode | TreeNode[]];
"open-dependency-object": [context: ObjectDependencyTarget, target: SqlObjectNavigationTarget];
}>();
@@ -2794,6 +2795,7 @@ defineExpose({
@open-object-source="openSidebarObjectSource"
@open-procedure="openSidebarProcedure"
@open-settings="openSidebarSettings"
+ @open-connection-settings="(connectionId) => emit('open-connection-settings', connectionId)"
@open-data="openSidebarData"
@open-visible-databases="openSidebarVisibleDatabases"
@open-visible-schemas="openSidebarVisibleSchemas"
diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
index f1e83f1af9..aff77a6a44 100644
--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
@@ -15,6 +15,8 @@ import { canDropDatabaseNode, notifyDatabaseBrowserMutation } from "@/lib/databa
import { canDropDatabaseTables, canEmptyDatabaseTables, useDatabaseTableEmpty } from "@/composables/useDatabaseTableEmpty";
import { useI18n } from "vue-i18n";
import { translateBackendError } from "@/i18n/backend-errors";
+import { normalizeBackendError } from "@/lib/backend/errorUtils";
+import { isConnectionTimeoutErrorMessage } from "@/lib/sql/queryError";
import {
Ban,
BarChart3,
@@ -548,6 +550,7 @@ const emit = defineEmits<{
"open-object-source": [node: TreeNode, initialEditing: boolean, initialSection?: ObjectDetailsSection];
"open-procedure": [node: TreeNode];
"open-settings": [initialTab: string];
+ "open-connection-settings": [connectionId: string];
"open-data": [node: TreeNode, requireSelection: boolean, openMode: DataTabOpenMode, runner: (node: TreeNode, request: SidebarDataOpenRequest) => Promise<void>];
"open-visible-databases": [node: TreeNode];
"open-visible-schemas": [node: TreeNode];
@@ -901,7 +904,7 @@ async function toggle(requestId = beginNavigationRequest()) {
if (!isCurrentNavigationRequest(requestId)) return;
const errMsg = e?.message || String(e);
if (errMsg.includes(CONNECTION_ATTEMPT_CANCELLED_MESSAGE)) return;
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
openDriverStoreForInstallError(errMsg, node);
}
return;
@@ -1043,7 +1046,7 @@ async function toggle(requestId = beginNavigationRequest()) {
}
const errMsg = e?.message || String(e);
if (errMsg.includes(CONNECTION_ATTEMPT_CANCELLED_MESSAGE)) return;
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
openDriverStoreForInstallError(errMsg);
}
return;
@@ -1236,7 +1239,7 @@ async function toggle(requestId = beginNavigationRequest()) {
if (!wasExpanded) node.isExpanded = false;
const errMsg = e?.message || String(e);
if (errMsg.includes(CONNECTION_ATTEMPT_CANCELLED_MESSAGE)) return;
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
openDriverStoreForInstallError(errMsg);
}
}
@@ -1322,13 +1325,22 @@ function openDriverStoreForInstallError(errMsg: string, node: TreeNode = activeN
if (focus) window.dispatchEvent(new CustomEvent("dbx-open-driver-store", { detail: focus }));
}
+// 连接/取数失败的统一 toast(issue #13233):命中「连接超时」类错误时附带「修改超时时间」
+// 动作,点击后经 open-connection-settings 事件链打开该连接的编辑对话框高级页(与查询结果
+// 错误区的同名入口一致)。非超时错误保持原有纯提示行为,不带动作。
+function toastConnectFailed(connectionId: string | undefined, error: unknown) {
+ const rawMessage = (error as { message?: string } | undefined)?.message || String(error);
+ const action = connectionId && isConnectionTimeoutErrorMessage(rawMessage, normalizeBackendError(error) ?? undefined) ? { label: t("editor.changeConnectionTimeout"), onClick: () => emit("open-connection-settings", connectionId) } : undefined;
+ toast(t("connection.connectFailed", { message: translateBackendError(t, error) }), 5000, action);
+}
+
async function loadMoreObjectGroupChildren() {
const node = activeNode.value;
const searchFilter = node.loadMore?.parentId ? connectionStore.sidebarTableSearchQueries[node.loadMore.parentId]?.trim() || "" : "";
try {
await connectionStore.loadMoreObjectGroupChildren(node, { searchFilter });
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
}
}
@@ -1337,7 +1349,7 @@ async function loadAllObjectGroupChildren() {
try {
await connectionStore.loadAllObjectGroupChildren(node);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
}
}
@@ -1985,7 +1997,7 @@ async function openObjectBrowser(eventReadOnly = false, openEventEditor: boolean
await toggle();
}
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
openDriverStoreForInstallError(e?.message || String(e));
}
}
@@ -2047,7 +2059,7 @@ async function openDatabaseBrowser() {
connectionStore.activeConnectionId = node.connectionId;
queryStore.openDatabaseBrowser(node.connectionId);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
openDriverStoreForInstallError(e?.message || String(e));
}
}
@@ -2064,7 +2076,7 @@ async function openProfileDatabaseWorkspace() {
const target = workspace.resolveTarget?.(node.database, "database") ?? { database: node.database };
queryStore.openDriverProfileWorkspace(node.connectionId, target.database, t(workspace.tabTitleKey), workspace.mode, workspace.tabScope, target.branch);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
}
}
@@ -2083,7 +2095,7 @@ async function openProfileConnectionWorkspace() {
const target = workspace.resolveTarget?.(database, "connection") ?? { database };
queryStore.openDriverProfileWorkspace(node.connectionId, target.database, t(workspace.tabTitleKey), workspace.mode, workspace.tabScope, target.branch);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
}
}
@@ -2095,7 +2107,7 @@ async function openUserAdmin() {
connectionStore.activeConnectionId = node.connectionId;
queryStore.openUserAdmin(node.connectionId);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
}
}
@@ -2107,7 +2119,7 @@ async function openXuguUserPermissions() {
connectionStore.activeConnectionId = node.connectionId;
queryStore.openXuguUserAdmin(node.connectionId);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e?.message || String(e)) }), 5000);
+ toastConnectFailed(node.connectionId, e?.message || String(e));
}
}
@@ -2119,7 +2131,7 @@ async function openProcessList() {
connectionStore.activeConnectionId = node.connectionId;
queryStore.openProcessList(node.connectionId);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
}
}
@@ -2131,7 +2143,7 @@ async function openSqlServerActivityTrace() {
connectionStore.activeConnectionId = node.connectionId;
queryStore.openSqlServerActivityTrace(node.connectionId);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
}
}
@@ -2153,7 +2165,7 @@ async function openServerDashboard() {
queryStore.openMysqlDashboard(node.connectionId);
}
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
}
}
@@ -2165,7 +2177,7 @@ async function openDamengUsers() {
connectionStore.activeConnectionId = node.connectionId;
queryStore.openDamengUsers(node.connectionId);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
}
}
@@ -2177,7 +2189,7 @@ async function openDamengRoles() {
connectionStore.activeConnectionId = node.connectionId;
queryStore.openDamengRoles(node.connectionId);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
}
}
@@ -2189,7 +2201,7 @@ async function openDamengJobAdmin() {
connectionStore.activeConnectionId = node.connectionId;
queryStore.openDamengJobAdmin(node.connectionId);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
}
}
@@ -2252,7 +2264,7 @@ async function newQuery(options: { reuseQueryTabByScope?: boolean } = {}) {
if (openDefault) await queryStore.openDefaultQuery({ connectionId: node.connectionId, database });
else queryStore.createTab(node.connectionId, database, undefined, "query", connection.default_schema);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
openDriverStoreForInstallError(e?.message || String(e));
}
}
@@ -2364,7 +2376,7 @@ async function newSelectTemplate() {
});
openSqlTemplateTab(context.node.connectionId!, context.node.database!, context.node.schema, context.node.catalog, sql);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(activeNode.value.connectionId, e);
}
}
@@ -2437,7 +2449,7 @@ async function runInsertTemplate(rowCount: number, prefetchedContexts?: TableTem
const title = contexts.length === 1 ? undefined : `INSERT - ${contexts.map((context) => context.node.label).join(", ")}`;
openSqlTemplateTab(tabTarget.connectionId!, tabTarget.database!, tabTarget.schema, tabTarget.catalog, sql, title);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(activeNode.value.connectionId, e);
}
}
@@ -2483,7 +2495,7 @@ async function newUpdateTemplate() {
});
openSqlTemplateTab(context.node.connectionId!, context.node.database!, context.node.schema, context.node.catalog, sql);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(activeNode.value.connectionId, e);
}
}
@@ -2529,7 +2541,7 @@ async function newDeleteTemplate() {
});
openSqlTemplateTab(context.node.connectionId!, context.node.database!, context.node.schema, context.node.catalog, sql);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(activeNode.value.connectionId, e);
}
}
@@ -2697,7 +2709,7 @@ async function refresh() {
toast(t("connection.objectCacheRefreshFailed", { message: translateBackendError(t, e) }), 5000);
return;
}
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
openDriverStoreForInstallError(e?.message || String(e), node);
}
return;
@@ -2705,7 +2717,7 @@ async function refresh() {
try {
await connectionStore.refreshTreeNode(node);
} catch (e: any) {
- toast(t("connection.connectFailed", { message: translateBackendError(t, e) }), 5000);
+ toastConnectFailed(node.connectionId, e);
openDriverStoreForInstallError(e?.message || String(e), node);
}
}
diff --git a/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.connectTimeoutToast.spec.ts b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.connectTimeoutToast.spec.ts
new file mode 100644
index 0000000000..9b81d0cb09
--- /dev/null
+++ b/apps/desktop/src/components/sidebar/__tests__/SidebarTreeRuntimeHost.connectTimeoutToast.spec.ts
@@ -0,0 +1,141 @@
+// @vitest-environment happy-dom
+
+// issue #13233:侧边栏连接/取数失败时,若错误属于「连接超时」,失败 toast 必须附带
+// 「修改超时时间」动作;点击动作后经 open-connection-settings 事件抛出连接 ID(由
+// App.vue 打开该连接的编辑对话框高级页)。非超时错误保持原有纯提示行为(无动作)。
+import { createApp, defineComponent, h, ref, type App } from "vue";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import i18n from "@/i18n";
+import type { TreeNode } from "@/types/database";
+import SidebarTreeRuntimeHost from "@/components/sidebar/SidebarTreeRuntimeHost.vue";
+
+const connectionStore = {
+ treeNodes: [] as TreeNode[],
+ selectedTreeNodeIds: [] as string[],
+ sidebarSearchQuery: "",
+ activeConnectionId: null as string | null,
+ connectedIds: new Set<string>(),
+ canUseLoadedTreeNodeToggle: vi.fn(() => true),
+ releaseCollapsedTreeNodeChildren: vi.fn(),
+ getConfig: vi.fn(() => ({ db_type: "mysql", name: "connection" })),
+ ensureConnected: vi.fn(async () => undefined),
+ // 数据库节点展开即触发连接/建表清单加载;由用例注入超时或普通错误。
+ loadTables: vi.fn(async () => undefined),
+ loadDatabases: vi.fn(async () => undefined),
+};
+
+const queryStore = {
+ openObjectBrowser: vi.fn(),
+ createTab: vi.fn(),
+};
+
+const toast = vi.fn();
+
+const settingsStore = {
+ editorSettings: {
+ sidebarActivation: "single" as "single" | "double",
+ sidebarBrowseObjectsOnDatabaseActivation: false,
+ shortcuts: { openDataInNewTab: "" },
+ },
+};
+
+vi.mock("@/stores/connectionStore", () => ({
+ CONNECTION_ATTEMPT_CANCELLED_MESSAGE: "Connection attempt was cancelled",
+ useConnectionStore: () => connectionStore,
+}));
+
+vi.mock("@/stores/queryStore", () => ({ useQueryStore: () => queryStore }));
+vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => settingsStore }));
+vi.mock("@/stores/savedSqlStore", () => ({ useSavedSqlStore: () => ({}) }));
+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast }) }));
+vi.mock("@/composables/useSqlHighlighter", () => ({ useSqlHighlighter: () => ({ highlight: vi.fn() }) }));
+vi.mock("@/composables/useSidebarDataOpenRuntime", () => ({ useSidebarDataOpenRuntime: () => ({ openData: vi.fn() }) }));
+vi.mock("@/composables/useDatabaseOptions", () => ({ useDatabaseOptions: () => ({ getDatabaseOptions: vi.fn() }) }));
+vi.mock("@/composables/useSidebarConnectionMutationRuntime", () => ({ useSidebarConnectionMutationRuntime: () => ({ isPinned: ref(false) }) }));
+vi.mock("@/composables/useSidebarDatabaseSpecificMutationRuntime", () => ({
+ useSidebarDatabaseSpecificMutationRuntime: () => ({
+ canManageMongoIndexes: ref(false),
+ canRenameMongoCollection: ref(false),
+ canCloneMongoCollection: ref(false),
+ canDropMongoCollection: ref(false),
+ }),
+}));
+vi.mock("@/composables/useSidebarTableMutationRuntime", () => ({ useSidebarTableMutationRuntime: () => ({}) }));
+vi.mock("@/composables/useSidebarTreeExportRuntime", () => ({ useSidebarTreeExportRuntime: () => ({}) }));
+vi.mock("@/composables/useSidebarTreeToolRuntime", () => ({ useSidebarTreeToolRuntime: () => ({}) }));
+vi.mock("@/lib/backend/api", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/backend/api")>();
+ return { ...actual, listPlugins: vi.fn().mockResolvedValue([]) };
+});
+
+const mountedApps: App[] = [];
+
+afterEach(() => {
+ for (const app of mountedApps.splice(0)) app.unmount();
+ document.body.innerHTML = "";
+ connectionStore.treeNodes = [];
+ connectionStore.sidebarSearchQuery = "";
+ connectionStore.activeConnectionId = null;
+ connectionStore.connectedIds.clear();
+ settingsStore.editorSettings.sidebarBrowseObjectsOnDatabaseActivation = false;
+ vi.clearAllMocks();
+ connectionStore.canUseLoadedTreeNodeToggle.mockReturnValue(true);
+ connectionStore.getConfig.mockReturnValue({ db_type: "mysql", name: "connection" });
+ connectionStore.loadTables.mockResolvedValue(undefined);
+ connectionStore.loadDatabases.mockResolvedValue(undefined);
+});
+
+// 挂载宿主并让 database 节点展开失败(loadTables/loadDatabases 抛出用例注入的错误),
+// 返回捕获 open-connection-settings 事件的监听器,供动作点击断言使用。
+async function mountAndFailExpand(error: unknown, openConnectionSettings: (connectionId: string) => void) {
+ const database: TreeNode = {
+ id: "mysql:dbx_test",
+ label: "dbx_test",
+ type: "database",
+ connectionId: "mysql",
+ database: "dbx_test",
+ isExpanded: false,
+ children: [],
+ };
+ connectionStore.treeNodes = [database];
+ connectionStore.loadTables.mockRejectedValue(error);
+ connectionStore.loadDatabases.mockRejectedValue(error);
+ const host = ref<InstanceType<typeof SidebarTreeRuntimeHost> | null>(null);
+ const app = createApp(
+ defineComponent({
+ setup: () => () => h(SidebarTreeRuntimeHost, { ref: host, node: database, depth: 0, onOpenConnectionSettings: openConnectionSettings }),
+ }),
+ );
+ mountedApps.push(app);
+ const container = document.createElement("div");
+ document.body.append(container);
+ app.use(i18n);
+ app.mount(container);
+
+ host.value!.toggleNode(database);
+ await vi.waitFor(() => expect(toast).toHaveBeenCalledOnce());
+ return toast.mock.calls[0] as [string, number, { label: string; onClick: () => void } | undefined];
+}
+
+describe("SidebarTreeRuntimeHost connect-failed toast timeout action", () => {
+ it("adds a change-timeout action when the expand failure is a connection timeout", async () => {
+ const openConnectionSettings = vi.fn();
+ const [message, duration, action] = await mountAndFailExpand(new Error("Connection attempt timed out: handshake failed"), openConnectionSettings);
+
+ expect(duration).toBe(5000);
+ expect(message).toContain(i18n.global.t("connection.connectFailed", { message: "Connection attempt timed out: handshake failed" }));
+ expect(action?.label).toBe(i18n.global.t("editor.changeConnectionTimeout"));
+
+ action!.onClick();
+ expect(openConnectionSettings).toHaveBeenCalledExactlyOnceWith("mysql");
+ });
+
+ it("keeps the plain toast without action for non-timeout failures", async () => {
+ const openConnectionSettings = vi.fn();
+ const [, duration, action] = await mountAndFailExpand(new Error("Access denied for user 'dbx'"), openConnectionSettings);
+
+ expect(duration).toBe(5000);
+ expect(action).toBeUndefined();
+ expect(openConnectionSettings).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 2b7d405b33..daaf187548 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -8237,6 +8237,8 @@ export default withEnglishFallback({
sqlVariableSyntax_namedDescription: "Adlandırılmış yer tutucuları əvəz etmək üçün dəyər soruş.",
sqlVariableSyntax_shell: "Əmr örtüyü üslublu yer tutucu",
sqlVariableSyntax_shellDescription: "Əmr örtüyü üslublu yer tutucuları əvəz etmək üçün dəyər soruş.",
+ sqlVariableSyntax_bracketedShell: "Mötərizəli əmr örtüyü üslublu yer tutucu",
+ sqlVariableSyntax_bracketedShellDescription: "Mötərizəli əmr örtüyü üslublu yer tutucuları əvəz etmək üçün dəyər soruş; mötərizələr əvəzetmə zamanı çıxarılır.",
sqlVariableSyntax_mybatis: "MyBatis üslublu yer tutucu",
sqlVariableSyntax_mybatisDescription: "MyBatis üslublu yer tutucuları əvəz etmək üçün dəyər soruş.",
sqlVariableSyntax_sqlserver: "SQL Server üslublu yer tutucu",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index c904d251ed..104162105b 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -10258,6 +10258,8 @@ export default {
sqlVariableSyntax_namedDescription: "Prompt for a value to substitute named placeholders.",
sqlVariableSyntax_shell: "Shell-style placeholder",
sqlVariableSyntax_shellDescription: "Prompt for a value to substitute shell-style placeholders.",
+ sqlVariableSyntax_bracketedShell: "Bracketed shell placeholder",
+ sqlVariableSyntax_bracketedShellDescription: "Prompt for a value to substitute bracketed shell placeholders; the brackets are removed on substitution.",
sqlVariableSyntax_mybatis: "MyBatis-style placeholder",
sqlVariableSyntax_mybatisDescription: "Prompt for a value to substitute MyBatis-style placeholders.",
sqlVariableSyntax_sqlserver: "SQL Server-style placeholder",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 8584b5b028..dd13cbb5fc 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -9048,6 +9048,8 @@ export default withEnglishFallback({
sqlVariableSyntax_namedDescription: "Solicita un valor para sustituir los marcadores con nombre.",
sqlVariableSyntax_shell: "Marcador estilo shell",
sqlVariableSyntax_shellDescription: "Solicita un valor para sustituir los marcadores de estilo shell.",
+ sqlVariableSyntax_bracketedShell: "Marcador de estilo shell entre corchetes",
+ sqlVariableSyntax_bracketedShellDescription: "Solicita un valor para sustituir los marcadores de estilo shell entre corchetes; los corchetes se eliminan al sustituir.",
sqlVariableSyntax_mybatis: "Marcador estilo MyBatis",
sqlVariableSyntax_mybatisDescription: "Solicita un valor para sustituir los marcadores de estilo MyBatis.",
sqlVariableSyntax_sqlserver: "Marcador estilo SQL Server",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index 741e03d134..21296facc7 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -9047,6 +9047,8 @@ export default withEnglishFallback({
sqlVariableSyntax_namedDescription: "Minta nilai untuk mensubstitusi placeholder bernama.",
sqlVariableSyntax_shell: "Placeholder bergaya shell",
sqlVariableSyntax_shellDescription: "Minta nilai untuk mensubstitusi placeholder bergaya shell.",
+ sqlVariableSyntax_bracketedShell: "Placeholder bergaya shell dalam kurung siku",
+ sqlVariableSyntax_bracketedShellDescription: "Minta nilai untuk mensubstitusi placeholder bergaya shell dalam kurung siku; kurung siku dihapus saat substitusi.",
sqlVariableSyntax_mybatis: "Placeholder bergaya MyBatis",
sqlVariableSyntax_mybatisDescription: "Minta nilai untuk mensubstitusi placeholder bergaya MyBatis.",
sqlVariableSyntax_sqlserver: "Placeholder bergaya SQL Server",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 254dc08d1a..3121438de8 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -8811,6 +8811,8 @@ export default withEnglishFallback({
sqlVariableSyntax_namedDescription: "Richiede un valore per sostituire i segnaposto con nome.",
sqlVariableSyntax_shell: "Segnaposto stile shell",
sqlVariableSyntax_shellDescription: "Richiede un valore per sostituire i segnaposto in stile shell.",
+ sqlVariableSyntax_bracketedShell: "Segnaposto stile shell tra parentesi quadre",
+ sqlVariableSyntax_bracketedShellDescription: "Richiede un valore per sostituire i segnaposto in stile shell tra parentesi quadre; le parentesi quadre vengono rimosse in fase di sostituzione.",
sqlVariableSyntax_mybatis: "Segnaposto stile MyBatis",
sqlVariableSyntax_mybatisDescription: "Richiede un valore per sostituire i segnaposto in stile MyBatis.",
sqlVariableSyntax_sqlserver: "Segnaposto stile SQL Server",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 867abf212d..b5b2f006d0 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -8808,6 +8808,8 @@ export default withEnglishFallback({
sqlVariableSyntax_namedDescription: "名前付きプレースホルダーを置き換える値の入力を求めます。",
sqlVariableSyntax_shell: "シェル形式プレースホルダー",
sqlVariableSyntax_shellDescription: "シェル形式プレースホルダーを置き換える値の入力を求めます。",
+ sqlVariableSyntax_bracketedShell: "角括弧シェル形式プレースホルダー",
+ sqlVariableSyntax_bracketedShellDescription: "角括弧シェル形式プレースホルダーを置き換える値の入力を求めます。置換時に角括弧は除去されます。",
sqlVariableSyntax_mybatis: "MyBatis 形式プレースホルダー",
sqlVariableSyntax_mybatisDescription: "MyBatis 形式プレースホルダーを置き換える値の入力を求めます。",
sqlVariableSyntax_sqlserver: "SQL Server 形式プレースホルダー",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index c4159be418..203f649bac 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -8973,6 +8973,8 @@ export default withEnglishFallback({
sqlVariableSyntax_namedDescription: "이름 있는 자리표시자를 치환할 값을 입력하라는 메시지를 표시합니다.",
sqlVariableSyntax_shell: "셸 스타일 자리표시자",
sqlVariableSyntax_shellDescription: "셸 스타일 자리표시자를 치환할 값을 입력하라는 메시지를 표시합니다.",
+ sqlVariableSyntax_bracketedShell: "대괄호 셸 스타일 자리표시자",
+ sqlVariableSyntax_bracketedShellDescription: "대괄호 셸 스타일 자리표시자를 치환할 값을 입력하라는 메시지를 표시합니다. 치환 시 대괄호는 제거됩니다.",
sqlVariableSyntax_mybatis: "MyBatis 스타일 자리표시자",
sqlVariableSyntax_mybatisDescription: "MyBatis 스타일 자리표시자를 치환할 값을 입력하라는 메시지를 표시합니다.",
sqlVariableSyntax_sqlserver: "SQL Server 스타일 자리표시자",
diff --git a/apps/desktop/src/i18n/locales/pl.ts b/apps/desktop/src/i18n/locales/pl.ts
index 2979043403..ec607eda58 100644
--- a/apps/desktop/src/i18n/locales/pl.ts
+++ b/apps/desktop/src/i18n/locales/pl.ts
@@ -9085,6 +9085,8 @@ export default withEnglishFallback({
sqlVariableSyntax_namedDescription: "Pytaj o wartość do podstawienia dla nazwanych symboli zastępczych.",
sqlVariableSyntax_shell: "Symbol zastępczy w stylu powłoki (shell)",
sqlVariableSyntax_shellDescription: "Pytaj o wartość do podstawienia dla symboli zastępczych w stylu powłoki.",
+ sqlVariableSyntax_bracketedShell: "Symbol zastępczy w stylu powłoki w nawiasach kwadratowych",
+ sqlVariableSyntax_bracketedShellDescription: "Pytaj o wartość do podstawienia dla symboli zastępczych w stylu powłoki w nawiasach kwadratowych; nawiasy są usuwane podczas podstawiania.",
sqlVariableSyntax_mybatis: "Symbol zastępczy w stylu MyBatis",
sqlVariableSyntax_mybatisDescription: "Pytaj o wartość do podstawienia dla symboli zastępczych w stylu MyBatis.",
sqlVariableSyntax_sqlserver: "Symbol zastępczy w stylu SQL Server",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index f39c4aedd3..ce9b9a1715 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -8809,6 +8809,8 @@ export default withEnglishFallback({
sqlVariableSyntax_namedDescription: "Solicita um valor para substituir os espaços reservados nomeados.",
sqlVariableSyntax_shell: "Espaço reservado estilo shell",
sqlVariableSyntax_shellDescription: "Solicita um valor para substituir os espaços reservados de estilo shell.",
+ sqlVariableSyntax_bracketedShell: "Espaço reservado estilo shell entre colchetes",
+ sqlVariableSyntax_bracketedShellDescription: "Solicita um valor para substituir os espaços reservados de estilo shell entre colchetes; os colchetes são removidos na substituição.",
sqlVariableSyntax_mybatis: "Espaço reservado estilo MyBatis",
sqlVariableSyntax_mybatisDescription: "Solicita um valor para substituir os espaços reservados de estilo MyBatis.",
sqlVariableSyntax_sqlserver: "Espaço reservado estilo SQL Server",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index e0165d5965..631d77af1c 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -10439,6 +10439,8 @@ export default withEnglishFallback({
sqlVariableSyntax_namedDescription: "Запрашивать значение для подстановки именованных заполнителей.",
sqlVariableSyntax_shell: "Заполнитель в стиле shell",
sqlVariableSyntax_shellDescription: "Запрашивать значение для подстановки заполнителей в стиле shell.",
+ sqlVariableSyntax_bracketedShell: "Заполнитель в стиле shell в квадратных скобках",
+ sqlVariableSyntax_bracketedShellDescription: "Запрашивать значение для подстановки заполнителей в стиле shell в квадратных скобках; скобки удаляются при подстановке.",
sqlVariableSyntax_mybatis: "Заполнитель в стиле MyBatis",
sqlVariableSyntax_mybatisDescription: "Запрашивать значение для подстановки заполнителей в стиле MyBatis.",
sqlVariableSyntax_sqlserver: "Заполнитель в стиле SQL Server",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index 8a5c4191d1..0fbd42f31b 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -10831,6 +10831,8 @@ export default withEnglishFallback({
sqlVariableSyntax_namedDescription: "ขอค่าเพื่อแทนที่ Placeholder แบบชื่อ",
sqlVariableSyntax_shell: "Placeholder แบบ Shell",
sqlVariableSyntax_shellDescription: "ขอค่าเพื่อแทนที่ Placeholder แบบ Shell",
+ sqlVariableSyntax_bracketedShell: "Placeholder แบบ Shell ในวงเล็บเหลี่ยม",
+ sqlVariableSyntax_bracketedShellDescription: "ขอค่าเพื่อแทนที่ Placeholder แบบ Shell ในวงเล็บเหลี่ยม; วงเล็บเหลี่ยมจะถูกลบออกเมื่อแทนที่",
sqlVariableSyntax_mybatis: "Placeholder แบบ MyBatis",
sqlVariableSyntax_mybatisDescription: "ขอค่าเพื่อแทนที่ Placeholder แบบ MyBatis",
sqlVariableSyntax_sqlserver: "Placeholder แบบ SQL Server",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index 89942ce01d..d4ed01cf48 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -8135,6 +8135,8 @@ export default withEnglishFallback({
sqlVariableSyntax_namedDescription: "Adlandırılmış yer tutucuları değiştirmek için değer sor.",
sqlVariableSyntax_shell: "Kabuk biçemli yer tutucu",
sqlVariableSyntax_shellDescription: "Kabuk biçemli yer tutucuları değiştirmek için değer sor.",
+ sqlVariableSyntax_bracketedShell: "Köşeli parantezli kabuk biçemli yer tutucu",
+ sqlVariableSyntax_bracketedShellDescription: "Köşeli parantezli kabuk biçemli yer tutucuları değiştirmek için değer sor; köşeli parantezler değişim sırasında kaldırılır.",
sqlVariableSyntax_mybatis: "MyBatis biçemli yer tutucu",
sqlVariableSyntax_mybatisDescription: "MyBatis biçemli yer tutucuları değiştirmek için değer sor.",
sqlVariableSyntax_sqlserver: "SQL Server biçemli yer tutucu",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index f3274a8221..52c89e6762 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -10221,6 +10221,8 @@ export default withEnglishFallback({
sqlVariableSyntax_namedDescription: "为命名占位符提示输入替换值。",
sqlVariableSyntax_shell: "Shell 风格占位符",
sqlVariableSyntax_shellDescription: "为 Shell 风格占位符提示输入替换值。",
+ sqlVariableSyntax_bracketedShell: "方括号 Shell 占位符",
+ sqlVariableSyntax_bracketedShellDescription: "为方括号 Shell 占位符提示输入替换值,替换时移除方括号。",
sqlVariableSyntax_mybatis: "MyBatis 风格占位符",
sqlVariableSyntax_mybatisDescription: "为 MyBatis 风格占位符提示输入替换值。",
sqlVariableSyntax_sqlserver: "SQL Server 风格占位符",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 97bb3392f4..ea47afa678 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -8152,6 +8152,8 @@ export default withEnglishFallback({
sqlVariableSyntax_namedDescription: "為具名佔位符提示輸入替換值。",
sqlVariableSyntax_shell: "Shell 風格佔位符",
sqlVariableSyntax_shellDescription: "為 Shell 風格佔位符提示輸入替換值。",
+ sqlVariableSyntax_bracketedShell: "方括號 Shell 佔位符",
+ sqlVariableSyntax_bracketedShellDescription: "為方括號 Shell 佔位符提示輸入替換值,替換時移除方括號。",
sqlVariableSyntax_mybatis: "MyBatis 風格佔位符",
sqlVariableSyntax_mybatisDescription: "為 MyBatis 風格佔位符提示輸入替換值。",
sqlVariableSyntax_sqlserver: "SQL Server 風格佔位符",
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts
index ba27e8f4ae..678c9eee3e 100644
--- a/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/sqlParameters.spec.ts
@@ -642,6 +642,53 @@ describe("extractSqlParameters", () => {
]);
});
+ describe("bracketed-shell placeholders", () => {
+ it("recognizes [${name}] as a bracketed-shell parameter covering the brackets", () => {
+ const sql = "select * from t where id = [${userId}]";
+ expect(extractSqlParameterDescriptors(sql)).toEqual([{ key: "userId", name: "userId", syntax: "bracketed-shell", token: "[${userId}]" }]);
+ // Postgres must prefer bracketed-shell over its array-bracket handling too.
+ expect(extractSqlParameterDescriptors(sql, { databaseType: "postgres" })).toEqual([{ key: "userId", name: "userId", syntax: "bracketed-shell", token: "[${userId}]" }]);
+ });
+
+ it("replaces the whole [${name}] token so the brackets disappear", () => {
+ const sql = "select * from t where id = [${userId}]";
+ expect(substituteSqlParameters(sql, { userId: { kind: "number", value: "5" } })).toBe("select * from t where id = 5");
+ expect(substituteSqlParameters(sql, { userId: { kind: "string", value: "abc" } })).toBe("select * from t where id = 'abc'");
+ });
+
+ it("still recognizes bare ${name} as a shell parameter", () => {
+ expect(extractSqlParameterDescriptors("select ${name}")).toEqual([{ key: "name", name: "name", syntax: "shell", token: "${name}" }]);
+ });
+
+ it("falls back to shell recognition when the closing bracket is missing", () => {
+ const sql = "select [${name}";
+ expect(extractSqlParameterDescriptors(sql)).toEqual([{ key: "name", name: "name", syntax: "shell", token: "${name}" }]);
+ expect(substituteSqlParameters(sql, { name: { kind: "number", value: "7" } })).toBe("select [7");
+ });
+
+ it("falls back without swallowing characters when the inner name is invalid", () => {
+ const sql = "select [${bad-name}]";
+ expect(extractSqlParameterDescriptors(sql)).toEqual([]);
+ expect(substituteSqlParameters(sql, {})).toBe(sql);
+ });
+
+ it("does not recognize the syntax when bracketed-shell is disabled", () => {
+ const sql = "select * from t where id = [${userId}]";
+ expect(extractSqlParameterDescriptors(sql, { enabledSyntaxes: ["shell"] })).toEqual([]);
+ expect(substituteSqlParameters(sql, { userId: { kind: "number", value: "5" } }, { enabledSyntaxes: ["shell"] })).toBe(sql);
+ // Postgres never swallows brackets: the inner ${...} stays recognized as shell.
+ expect(extractSqlParameterDescriptors(sql, { databaseType: "postgres", enabledSyntaxes: ["shell"] })).toEqual([{ key: "userId", name: "userId", syntax: "shell", token: "${userId}" }]);
+ });
+
+ it("leaves bracketed-shell candidates inside string literals to embedded shell handling", () => {
+ const sql = "select '[${x}]' as c";
+ expect(extractSqlParameterDescriptors(sql)).toEqual([{ key: "x", name: "x", syntax: "shell", token: "${x}" }]);
+ // Existing behavior: the embedded ${x} inside the string is replaced as a
+ // string fragment while the brackets stay part of the literal.
+ expect(substituteSqlParameters(sql, { x: { kind: "string", value: "hi" } })).toBe("select '[hi]' as c");
+ });
+ });
+
it("ignores declared SQL Server variables and system variables", () => {
const sql = `
declare @id int = 1, @name nvarchar(50);
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlVariableSyntax.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlVariableSyntax.spec.ts
index 9ce301759d..cfe24f98da 100644
--- a/apps/desktop/src/lib/__tests__/sql/sqlVariableSyntax.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/sqlVariableSyntax.spec.ts
@@ -146,6 +146,7 @@ describe("resolveSqlVariableSyntaxToggles", () => {
positional: true,
named: true,
shell: true,
+ bracketedShell: true,
mybatis: true,
sqlserver: false,
substitution: false,
@@ -165,6 +166,7 @@ describe("resolveSqlVariableSyntaxToggles", () => {
positional: false,
named: false,
shell: false,
+ bracketedShell: false,
mybatis: false,
sqlserver: false,
substitution: false,
@@ -174,6 +176,7 @@ describe("resolveSqlVariableSyntaxToggles", () => {
positional: false,
named: false,
shell: false,
+ bracketedShell: false,
mybatis: false,
sqlserver: false,
substitution: false,
@@ -190,6 +193,7 @@ describe("resolveSqlVariableSyntaxToggles", () => {
positional: true,
named: true,
shell: false,
+ bracketedShell: true,
mybatis: true,
sqlserver: true,
substitution: false,
@@ -197,24 +201,29 @@ describe("resolveSqlVariableSyntaxToggles", () => {
});
expect(overrides).toEqual({ mysql: { shell: false, atSet: false } });
});
+
+ it("honors the bracketedShell override per database type", () => {
+ expect(resolveSqlVariableSyntaxToggles({ mysql: { bracketedShell: false } }, "mysql").bracketedShell).toBe(false);
+ expect(resolveSqlVariableSyntaxToggles({ mysql: { bracketedShell: false } }, "postgres").bracketedShell).toBe(true);
+ });
});
describe("enabledSqlParameterSyntaxes", () => {
- it("returns the five default placeholder syntaxes for generic databases and never atSet", () => {
- expect(enabledSqlParameterSyntaxes(DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES)).toEqual(["positional", "named", "shell", "mybatis", "sqlserver"]);
+ it("returns the six default placeholder syntaxes for generic databases and never atSet", () => {
+ expect(enabledSqlParameterSyntaxes(DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES)).toEqual(["positional", "named", "shell", "bracketed-shell", "mybatis", "sqlserver"]);
});
- it("returns all six placeholder syntaxes when substitution is enabled", () => {
- expect(enabledSqlParameterSyntaxes({ ...DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES, substitution: true })).toEqual(["positional", "named", "shell", "mybatis", "sqlserver", "substitution"]);
+ it("returns all seven placeholder syntaxes when substitution is enabled", () => {
+ expect(enabledSqlParameterSyntaxes({ ...DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES, substitution: true })).toEqual(["positional", "named", "shell", "bracketed-shell", "mybatis", "sqlserver", "substitution"]);
});
it("filters out disabled placeholder syntaxes", () => {
- expect(enabledSqlParameterSyntaxes({ positional: false, named: true, shell: false, mybatis: true, sqlserver: false, substitution: true, atSet: true })).toEqual(["named", "mybatis", "substitution"]);
+ expect(enabledSqlParameterSyntaxes({ positional: false, named: true, shell: false, bracketedShell: true, mybatis: true, sqlserver: false, substitution: true, atSet: true })).toEqual(["named", "bracketed-shell", "mybatis", "substitution"]);
});
it("ignores the atSet toggle entirely", () => {
- expect(enabledSqlParameterSyntaxes({ positional: true, named: true, shell: true, mybatis: true, sqlserver: true, substitution: true, atSet: false })).toEqual(["positional", "named", "shell", "mybatis", "sqlserver", "substitution"]);
- expect(enabledSqlParameterSyntaxes({ positional: false, named: false, shell: false, mybatis: false, sqlserver: false, substitution: false, atSet: true })).toEqual([]);
+ expect(enabledSqlParameterSyntaxes({ positional: true, named: true, shell: true, bracketedShell: true, mybatis: true, sqlserver: true, substitution: true, atSet: false })).toEqual(["positional", "named", "shell", "bracketed-shell", "mybatis", "sqlserver", "substitution"]);
+ expect(enabledSqlParameterSyntaxes({ positional: false, named: false, shell: false, bracketedShell: false, mybatis: false, sqlserver: false, substitution: false, atSet: true })).toEqual([]);
});
});
@@ -229,17 +238,23 @@ describe("normalizeSqlVariableSyntaxOverrides", () => {
it("keeps only syntaxes that deviate from defaults", () => {
expect(
normalizeSqlVariableSyntaxOverrides({
- mysql: { positional: true, shell: false, substitution: false, atSet: false },
+ mysql: { positional: true, shell: false, bracketedShell: false, substitution: false, atSet: false },
postgres: { substitution: true },
oracle: { substitution: false, shell: true },
}),
).toEqual({
- mysql: { shell: false, atSet: false },
+ mysql: { shell: false, bracketedShell: false, atSet: false },
postgres: { substitution: true },
oracle: { substitution: false },
});
});
+ it("round-trips a bracketedShell override through normalization", () => {
+ const normalized = normalizeSqlVariableSyntaxOverrides({ mysql: { bracketedShell: false } });
+ expect(normalized).toEqual({ mysql: { bracketedShell: false } });
+ expect(normalizeSqlVariableSyntaxOverrides(normalized)).toEqual(normalized);
+ });
+
it("drops entries with no deviating syntaxes", () => {
expect(normalizeSqlVariableSyntaxOverrides({ mysql: { positional: true, substitution: false }, postgres: {} })).toEqual({});
expect(normalizeSqlVariableSyntaxOverrides({ oracle: { positional: true, substitution: true } })).toEqual({});
diff --git a/apps/desktop/src/lib/settings/__tests__/editorSettingsDraft.spec.ts b/apps/desktop/src/lib/settings/__tests__/editorSettingsDraft.spec.ts
index 962e9ac621..6285b2f358 100644
--- a/apps/desktop/src/lib/settings/__tests__/editorSettingsDraft.spec.ts
+++ b/apps/desktop/src/lib/settings/__tests__/editorSettingsDraft.spec.ts
@@ -59,9 +59,16 @@ describe("EDITOR_SETTINGS_DRAFT_KEYS", () => {
expect(draft.dataGridColumnCommentsInInfoArea).toBe(true);
expect(editorSettingsPatchFromDraft(draft, base)).toEqual({ dataGridColumnCommentsInInfoArea: true, dataGridTransposeMetadataInInfoColumn: true });
});
- it("keeps connection and query timeout ownership outside editor settings", () => {
- expect(EDITOR_SETTINGS_DRAFT_KEYS).not.toContain("globalConnectTimeoutSecs");
- expect(EDITOR_SETTINGS_DRAFT_KEYS).not.toContain("globalQueryTimeoutSecs");
+ it("exposes the global connect/query timeouts in the settings draft (#13233)", () => {
+ // 设置页现在直接展示并允许调整全局超时(issue #13233),草稿键必须包含这两个字段,
+ // 且落盘口径与连接编辑对话框一致:连接超时 1~300 秒,查询超时 0~3600 秒(0=不限)。
+ expect(EDITOR_SETTINGS_DRAFT_KEYS).toContain("globalConnectTimeoutSecs");
+ expect(EDITOR_SETTINGS_DRAFT_KEYS).toContain("globalQueryTimeoutSecs");
+ const settings = makeSettings({ globalConnectTimeoutSecs: 10, globalQueryTimeoutSecs: 60 } as Partial<EditorSettings>);
+ const draft = editorSettingsDraftFromSettings(settings);
+ draft.globalConnectTimeoutSecs = 9999;
+ draft.globalQueryTimeoutSecs = 0;
+ expect(editorSettingsPatchFromDraft(draft, editorSettingsDraftFromSettings(settings))).toEqual({ globalConnectTimeoutSecs: 300, globalQueryTimeoutSecs: 0 });
});
it("includes showLineNumbers", () => {
@@ -268,12 +275,14 @@ describe("editorSettingsDraftFromSettings", () => {
expect(base.sqlVariableSyntaxOverrides).toEqual({ mysql: { shell: false } });
});
- it("does not include persisted global timeout values in editor drafts", () => {
+ it("includes persisted global timeout values in editor drafts (#13233)", () => {
+ // 设置页直接展示全局超时后(issue #13233),草稿必须携带落盘值且走同一 normalize 口径;
+ // 未修改时不应产生这两个字段的 patch,避免 Apply 误覆盖。
const settings = makeSettings({ globalConnectTimeoutSecs: 17, globalQueryTimeoutSecs: 43 });
const draft = editorSettingsDraftFromSettings(settings);
- expect(draft).not.toHaveProperty("globalConnectTimeoutSecs");
- expect(draft).not.toHaveProperty("globalQueryTimeoutSecs");
+ expect(draft.globalConnectTimeoutSecs).toBe(17);
+ expect(draft.globalQueryTimeoutSecs).toBe(43);
expect(editorSettingsPatchFromDraft(draft, draft)).not.toHaveProperty("globalConnectTimeoutSecs");
expect(editorSettingsPatchFromDraft(draft, draft)).not.toHaveProperty("globalQueryTimeoutSecs");
});
diff --git a/apps/desktop/src/lib/settings/__tests__/settingsSearch.spec.ts b/apps/desktop/src/lib/settings/__tests__/settingsSearch.spec.ts
index 4c6e4e3df2..0c53ff3c87 100644
--- a/apps/desktop/src/lib/settings/__tests__/settingsSearch.spec.ts
+++ b/apps/desktop/src/lib/settings/__tests__/settingsSearch.spec.ts
@@ -179,9 +179,10 @@ describe("settings search", () => {
expect(withSqlServer.map((entry) => entry.id)).toContain("editor-sqlserver-space-completion");
});
- it("does not index connection or query timeout under editor settings", () => {
- expect(SETTINGS_SEARCH_DEFINITIONS.map((definition) => definition.id)).not.toContain("editor-global-connect-timeout");
- expect(SETTINGS_SEARCH_DEFINITIONS.map((definition) => definition.id)).not.toContain("editor-global-query-timeout");
+ it("indexes the global connection/query timeouts under editor settings (#13233)", () => {
+ // 全局超时现已在设置页展示(issue #13233),设置搜索需要索引这两个控件。
+ expect(SETTINGS_SEARCH_DEFINITIONS.map((definition) => definition.id)).toContain("editor-global-connect-timeout");
+ expect(SETTINGS_SEARCH_DEFINITIONS.map((definition) => definition.id)).toContain("editor-global-query-timeout");
});
it("indexes the multi-statement default view and its settings control", () => {
diff --git a/apps/desktop/src/lib/settings/editorSettingsDraft.ts b/apps/desktop/src/lib/settings/editorSettingsDraft.ts
index e0826fdbd7..c99cad7fca 100644
--- a/apps/desktop/src/lib/settings/editorSettingsDraft.ts
+++ b/apps/desktop/src/lib/settings/editorSettingsDraft.ts
@@ -10,6 +10,7 @@ import { normalizeTableHoverLookupMode } from "@/lib/editor/hoverTableLookup";
import { normalizeRedisKeyTemplates } from "@/lib/redis/redisKeyTemplates";
import { normalizeCsvNullMode } from "@/lib/export/csvNullMode";
import { normalizeAiSqlApplyTargetMode } from "@/lib/ai/aiSqlTargetTab";
+import { normalizeConnectTimeoutSecs, normalizeQueryTimeoutSecs } from "@/lib/connection/timeoutLimits";
export const EDITOR_SETTINGS_DRAFT_KEYS = [
"fontFamily",
@@ -179,6 +180,8 @@ export const EDITOR_SETTINGS_DRAFT_KEYS = [
"excludedCompletionItems",
"defaultTransactionMode",
"keepExplicitTransactionInAutoCommit",
+ "globalConnectTimeoutSecs",
+ "globalQueryTimeoutSecs",
] as const satisfies readonly (keyof EditorSettings)[];
export type EditorSettingsDraftKey = (typeof EDITOR_SETTINGS_DRAFT_KEYS)[number];
@@ -213,6 +216,10 @@ function normalizedDraftValue(key: EditorSettingsDraftKey, value: unknown): unkn
if (key === "webLogoPosition") return value === "right" || value === "hidden" ? value : "left";
if (key === "aiSqlApplyTargetMode") return normalizeAiSqlApplyTargetMode(value);
if (key === "colorizeConnectionTabsScope") return value === "active" ? "active" : "all";
+ // 全局连接/查询超时与连接编辑对话框「全局」档共用同一落盘口径(1~300 / 0~3600,0=不限),
+ // 草稿比较与回填都走同一 normalize,避免输入框残留越界值导致面板卡在“未保存”。
+ if (key === "globalConnectTimeoutSecs") return normalizeConnectTimeoutSecs(value);
+ if (key === "globalQueryTimeoutSecs") return normalizeQueryTimeoutSecs(value);
return value;
}
diff --git a/apps/desktop/src/lib/settings/settingsSearch.ts b/apps/desktop/src/lib/settings/settingsSearch.ts
index 91856f1fa9..15e694f1de 100644
--- a/apps/desktop/src/lib/settings/settingsSearch.ts
+++ b/apps/desktop/src/lib/settings/settingsSearch.ts
@@ -148,6 +148,9 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
{ id: "editor-execute-mode", category: "editor", titleKey: "settings.executeMode", targetId: "editor", keywordKeys: ["settings.executeModeAll", "settings.executeModeCurrent"] },
{ id: "editor-default-transaction-mode", category: "editor", titleKey: "settings.defaultTransactionMode", descriptionKey: "settings.defaultTransactionModeDescription", targetId: "editor", keywordKeys: ["settings.defaultTransactionModeAuto", "settings.defaultTransactionModeManual"] },
{ id: "editor-execute-all-on-blank-line", category: "editor", titleKey: "settings.executeAllOnBlankLine", descriptionKey: "settings.executeAllOnBlankLineDescription", targetId: "editor" },
+ // 全局超时入口(#13233):标题/描述复用连接对话框已有的 connection.* 文案,避免 14 个 locale 各补一份同义 key。
+ { id: "editor-global-connect-timeout", category: "editor", titleKey: "connection.connectTimeout", descriptionKey: "connection.globalConnectTimeoutHint", targetId: "editor" },
+ { id: "editor-global-query-timeout", category: "editor", titleKey: "connection.queryTimeout", descriptionKey: "connection.globalQueryTimeoutHint", targetId: "editor" },
{ id: "editor-execution-target", category: "editor", titleKey: "settings.showExecutionTargetPicker", descriptionKey: "settings.showExecutionTargetPickerDescription", targetId: "editor" },
{ id: "editor-run-buttons", category: "editor", titleKey: "settings.showStatementRunButtons", descriptionKey: "settings.showStatementRunButtonsDescription", targetId: "editor" },
{ id: "editor-locate-cursor-on-gutter-execute", category: "editor", titleKey: "settings.locateCursorOnGutterExecute", descriptionKey: "settings.locateCursorOnGutterExecuteDescription", targetId: "editor" },
diff --git a/apps/desktop/src/lib/settings/settingsTransfer.ts b/apps/desktop/src/lib/settings/settingsTransfer.ts
index 145c9d1f6c..b9eb61210f 100644
--- a/apps/desktop/src/lib/settings/settingsTransfer.ts
+++ b/apps/desktop/src/lib/settings/settingsTransfer.ts
@@ -284,6 +284,8 @@ const SETTINGS_TRANSFER_CATEGORY_KEYS: Record<SettingsTransferCategoryId, readon
"globalDateTimeDisplayFormat",
"globalDateTimeExportFormat",
"globalDateTimeImportFormat",
+ "globalConnectTimeoutSecs",
+ "globalQueryTimeoutSecs",
],
shortcuts: ["shortcuts", "sqlShortcuts"],
snippets: ["snippets", "snippetTriggerKey"],
diff --git a/apps/desktop/src/lib/sql/sqlParameters.ts b/apps/desktop/src/lib/sql/sqlParameters.ts
index 7040273227..8044559160 100644
--- a/apps/desktop/src/lib/sql/sqlParameters.ts
+++ b/apps/desktop/src/lib/sql/sqlParameters.ts
@@ -10,7 +10,7 @@ export interface SqlParameterInput {
value: string;
}
-export type SqlParameterSyntax = "positional" | "named" | "shell" | "mybatis" | "sqlserver" | "substitution";
+export type SqlParameterSyntax = "positional" | "named" | "shell" | "bracketed-shell" | "mybatis" | "sqlserver" | "substitution";
export interface SqlParameterDescriptor {
key: string;
@@ -513,6 +513,22 @@ function findSqlParameterOccurrences(sql: string, options?: SqlParameterOptions)
continue;
}
if (ch === "[") {
+ if (isSyntaxEnabled("bracketed-shell") && sql.startsWith("${", i + 1)) {
+ const bracketed = tryReadBracketedShellPlaceholder(sql, i);
+ if (bracketed) {
+ occurrences.push(bracketed);
+ i = bracketed.end;
+ continue;
+ }
+ // A failed bracketed-shell candidate must never swallow characters:
+ // treat "[" as a plain character so the inner `${...}` is still picked
+ // up by the shell branch below. Postgres keeps its array-bracket
+ // tracking so `:` slice handling stays intact.
+ if (databaseType !== "postgres") {
+ i += 1;
+ continue;
+ }
+ }
if (databaseType === "postgres") {
postgresBracketStack.push({
constructor: isPostgresArrayConstructorBracket(sql, i, postgresBracketStack[postgresBracketStack.length - 1]?.constructor ?? false),
@@ -1687,6 +1703,22 @@ function readParameterName(sql: string, start: number): string {
return sql.slice(start, i);
}
+/**
+ * Match the bracketed-shell placeholder `[${name}]` (Navicat-style). All five
+ * segments — "[", "${", a valid parameter name, "}", "]" — must match, and the
+ * brackets belong to the token so they disappear on substitution. Any mismatch
+ * returns null so the caller falls back to the default "[" handling without
+ * consuming characters.
+ */
+function tryReadBracketedShellPlaceholder(sql: string, start: number): ParameterOccurrence | null {
+ if (sql[start] !== "[" || sql[start + 1] !== "$" || sql[start + 2] !== "{") return null;
+ const closeBrace = sql.indexOf("}", start + 3);
+ if (closeBrace === -1 || sql[closeBrace + 1] !== "]") return null;
+ const name = sql.slice(start + 3, closeBrace).trim();
+ if (!PARAMETER_NAME_RE.test(name)) return null;
+ return { key: name, name, syntax: "bracketed-shell", token: sql.slice(start, closeBrace + 2), start, end: closeBrace + 2 };
+}
+
/** Match only unprefixed quote + exact `${name}`/`#{name}` + same quote. Leaves skipQuoted unchanged. */
function tryReadQuotedBracedPlaceholder(sql: string, start: number, quote: "'" | '"', isSyntaxEnabled: (syntax: SqlParameterSyntax) => boolean): ParameterOccurrence | null {
if (sql[start] !== quote) return null;
diff --git a/apps/desktop/src/lib/sql/sqlVariableSyntax.ts b/apps/desktop/src/lib/sql/sqlVariableSyntax.ts
index 3189b47ed8..82e0fb8737 100644
--- a/apps/desktop/src/lib/sql/sqlVariableSyntax.ts
+++ b/apps/desktop/src/lib/sql/sqlVariableSyntax.ts
@@ -1,7 +1,7 @@
// Per-database-type configuration for SQL variable/placeholder substitution.
//
// DBX runs two client-side substitution systems before sending SQL to a backend:
-// the placeholder parameter dialog (`sqlParameters.ts`, six syntaxes) and the
+// the placeholder parameter dialog (`sqlParameters.ts`, seven syntaxes) and the
// `@set name = value;` expansion (`sqlVariables.ts`). This module lets users opt
// out of individual syntaxes per database type. SQL syntaxes default to `true`,
// except Neo4j's `:label` patterns, which are not named parameters, and Oracle
@@ -19,6 +19,7 @@ export interface SqlVariableSyntaxToggles {
positional: boolean; // ?
named: boolean; // :name
shell: boolean; // ${name}
+ bracketedShell: boolean; // [${name}]
mybatis: boolean; // #{name}
sqlserver: boolean; // @name
substitution: boolean; // &name, &&name
@@ -29,6 +30,7 @@ export const DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES: SqlVariableSyntaxToggles = {
positional: true,
named: true,
shell: true,
+ bracketedShell: true,
mybatis: true,
sqlserver: true,
substitution: false,
@@ -36,21 +38,22 @@ export const DEFAULT_SQL_VARIABLE_SYNTAX_TOGGLES: SqlVariableSyntaxToggles = {
};
// Fixed order for iterating the toggles in the settings UI.
-export const SQL_VARIABLE_SYNTAX_KEYS = ["positional", "named", "shell", "mybatis", "sqlserver", "substitution", "atSet"] as const satisfies readonly (keyof SqlVariableSyntaxToggles)[];
+export const SQL_VARIABLE_SYNTAX_KEYS = ["positional", "named", "shell", "bracketedShell", "mybatis", "sqlserver", "substitution", "atSet"] as const satisfies readonly (keyof SqlVariableSyntaxToggles)[];
// Display tokens (code symbols, not translated) shown next to each toggle.
export const SQL_VARIABLE_SYNTAX_TOKENS: Record<keyof SqlVariableSyntaxToggles, string> = {
positional: "?",
named: ":name",
shell: "${name}",
+ bracketedShell: "[${name}]",
mybatis: "#{name}",
sqlserver: "@name",
substitution: "&name",
atSet: "@set …;",
};
-// The first six toggles map one-to-one onto placeholder parameter syntaxes.
-const PARAMETER_SYNTAX_KEYS = ["positional", "named", "shell", "mybatis", "sqlserver", "substitution"] as const satisfies readonly SqlParameterSyntax[];
+// The first seven toggles map one-to-one onto placeholder parameter syntaxes.
+const PARAMETER_SYNTAX_KEYS = ["positional", "named", "shell", "bracketed-shell", "mybatis", "sqlserver", "substitution"] as const satisfies readonly SqlParameterSyntax[];
export type SqlVariableSyntaxOverrides = Partial<Record<DatabaseType, Partial<SqlVariableSyntaxToggles>>>;
@@ -89,6 +92,7 @@ export function defaultSqlVariableSyntaxToggles(dbType?: DatabaseType, compatibi
positional: true,
named: dbType !== "neo4j" && dbType !== "nebula",
shell: true,
+ bracketedShell: true,
mybatis: true,
sqlserver: true,
substitution: isOracleSubstitutionDatabase(dbType, compatibilityMode),
@@ -108,6 +112,7 @@ export function resolveSqlVariableSyntaxToggles(overrides: SqlVariableSyntaxOver
positional: false,
named: false,
shell: false,
+ bracketedShell: false,
mybatis: false,
sqlserver: false,
substitution: false,
@@ -120,6 +125,7 @@ export function resolveSqlVariableSyntaxToggles(overrides: SqlVariableSyntaxOver
positional: partial?.positional ?? defaults.positional,
named: dbType === "neo4j" || dbType === "nebula" ? false : (partial?.named ?? defaults.named),
shell: partial?.shell ?? defaults.shell,
+ bracketedShell: partial?.bracketedShell ?? defaults.bracketedShell,
mybatis: partial?.mybatis ?? defaults.mybatis,
sqlserver: partial?.sqlserver ?? defaults.sqlserver,
substitution: partial?.substitution ?? defaults.substitution,
@@ -129,7 +135,9 @@ export function resolveSqlVariableSyntaxToggles(overrides: SqlVariableSyntaxOver
/** Derive the enabled placeholder parameter syntaxes (excludes `atSet`). */
export function enabledSqlParameterSyntaxes(toggles: SqlVariableSyntaxToggles): SqlParameterSyntax[] {
- return PARAMETER_SYNTAX_KEYS.filter((key) => toggles[key]);
+ // The toggle property is camelCase (`bracketedShell`) while the syntax id is
+ // kebab-case ("bracketed-shell"), so map explicitly instead of indexing by id.
+ return PARAMETER_SYNTAX_KEYS.filter((key) => toggles[key === "bracketed-shell" ? "bracketedShell" : key]);
}
/**