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(editor): execute custom sql template by shortcut on selection
Mo-Moore802019daa356
diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vueindex d0af3bdf82..e50b01b02e 100644--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue@@ -154,8 +154,9 @@ import { isMcpPolicyMutationBlocked, MCP_CAPABILITY_ROWS, MCP_EXECUTION_MODE_COLimport { isMacOS, isWindows } from "@/lib/backend/platform";import { combineDataTypeForDatabase, dataTypeLengthInputValue, getDataTypeOptions, getDefaultLengthForType, isDataTypeLengthDisabled, splitDataType } from "@/lib/table/tableStructureEditorState";import { useToast } from "@/composables/useToast";-import type { DatabaseType, SqlSnippet } from "@/types/database";+import type { DatabaseType, SqlShortcutAction, SqlSnippet } from "@/types/database";import { uuid } from "@/lib/common/utils";+import { findSqlShortcutConflicts, hasSqlShortcutConflicts as sqlShortcutsHaveConflicts, SQL_SHORTCUT_TABLE_TOKEN } from "@/lib/sql/sqlShortcutActions";import { DEFAULT_SQL_SNIPPETS } from "@/lib/sql/sqlCompletion";import AiProviderLogo from "@/components/icons/AiProviderLogo.vue";import AppLogo from "@/components/icons/AppLogo.vue";@@ -563,6 +564,12 @@ function editableSnippet(snippet: SqlSnippet): SqlSnippet {const editSnippets = ref<SqlSnippet[]>(settingsStore.editorSettings.snippets.map(editableSnippet));+function editableSqlShortcut(action: SqlShortcutAction): SqlShortcutAction {+ return { ...action, enabled: action.enabled !== false };+}++const editSqlShortcuts = ref<SqlShortcutAction[]>(settingsStore.editorSettings.sqlShortcuts.map(editableSqlShortcut));+function currentEditorSettingsDraft(): EditorSettingsDraft {return {fontFamily: editFontFamily.value,@@ -652,6 +659,7 @@ function currentEditorSettingsDraft(): EditorSettingsDraft {updateDownloadSource: editUpdateDownloadSource.value,toolbarItems: { ...editToolbarItems.value },snippets: editSnippets.value,+ sqlShortcuts: editSqlShortcuts.value,sqlVariableSubstitutionEnabled: editSqlVariableSubstitutionEnabled.value,sqlVariableSyntaxOverrides: editSqlVariableSyntaxOverrides.value,clickTableNavigationTarget: editClickTableNavigationTarget.value,@@ -665,6 +673,12 @@ const snippetDialogOpen = ref(false);const snippetEditingId = ref<string | null>(null);const snippetForm = ref({ label: "", prefix: "", body: "" });const snippetFormPrefixError = ref("");++const sqlShortcutDialogOpen = ref(false);+const sqlShortcutEditingId = ref<string | null>(null);+const sqlShortcutForm = ref({ label: "", shortcut: "", sql: "" });+const sqlShortcutFormLabelError = ref("");+const editingSqlShortcutInputId = ref<string | null>(null);const iconThemeBlackDescriptionText = computed(() => (isMacOS() ? t("settings.iconThemeBlackDescriptionMac") : t("settings.iconThemeBlackDescription")));const layoutDescTruncated = {separated: ref<boolean>(false),@@ -792,6 +806,127 @@ function confirmDeleteSnippet(snippet: SqlSnippet) {}}+function openAddSqlShortcutDialog() {+ sqlShortcutEditingId.value = null;+ sqlShortcutForm.value = { label: "", shortcut: "", sql: `SELECT * FROM ${SQL_SHORTCUT_TABLE_TOKEN}` };+ sqlShortcutFormLabelError.value = "";+ editingSqlShortcutInputId.value = null;+ sqlShortcutDialogOpen.value = true;+}++function openEditSqlShortcutDialog(action: SqlShortcutAction) {+ sqlShortcutEditingId.value = action.id;+ sqlShortcutForm.value = {+ label: action.label,+ shortcut: action.shortcut,+ sql: action.sql,+ };+ sqlShortcutFormLabelError.value = "";+ editingSqlShortcutInputId.value = null;+ sqlShortcutDialogOpen.value = true;+}++function saveSqlShortcut() {+ const label = sqlShortcutForm.value.label.trim();+ if (!label) {+ sqlShortcutFormLabelError.value = t("settings.sqlShortcutsLabelRequired");+ return;+ }+ const payload: SqlShortcutAction = {+ id: sqlShortcutEditingId.value ?? uuid(),+ label,+ shortcut: sqlShortcutForm.value.shortcut.trim(),+ sql: sqlShortcutForm.value.sql,+ enabled: true,+ };+ const nextShortcuts = sqlShortcutEditingId.value+ ? editSqlShortcuts.value.map((item) =>+ item.id === sqlShortcutEditingId.value+ ? {+ ...payload,+ enabled: item.enabled !== false,+ }+ : item,+ )+ : [...editSqlShortcuts.value, payload];+ if (sqlShortcutsHaveConflicts(nextShortcuts, editShortcuts.value)) {+ toast(t("settings.shortcutConflict"), 3000);+ return;+ }+ editSqlShortcuts.value = nextShortcuts;+ sqlShortcutDialogOpen.value = false;+ void commitSqlShortcuts();+}++function setSqlShortcutEnabled(id: string, enabled: boolean) {+ const idx = editSqlShortcuts.value.findIndex((item) => item.id === id);+ if (idx === -1) return;+ if (enabled) {+ const next = editSqlShortcuts.value.map((item) => (item.id === id ? { ...item, enabled } : item));+ if (sqlShortcutsHaveConflicts(next, editShortcuts.value)) {+ toast(t("settings.shortcutConflict"), 3000);+ return;+ }+ }+ editSqlShortcuts.value[idx] = { ...editSqlShortcuts.value[idx], enabled };+ void commitSqlShortcuts();+}++function deleteSqlShortcut(id: string) {+ editSqlShortcuts.value = editSqlShortcuts.value.filter((item) => item.id !== id);+ void commitSqlShortcuts();+}++function confirmDeleteSqlShortcut(action: SqlShortcutAction) {+ if (window.confirm(t("settings.sqlShortcutsDeleteConfirm", { name: action.label }))) {+ deleteSqlShortcut(action.id);+ }+}++function onSqlShortcutBindingKeydown(id: string, event: KeyboardEvent) {+ event.preventDefault();+ event.stopPropagation();+ if (editingSqlShortcutInputId.value !== id) return;+ if (event.key === "Escape") {+ editingSqlShortcutInputId.value = null;+ return;+ }+ const shortcut = eventToShortcut(event);+ if (!shortcut) return;+ sqlShortcutForm.value = { ...sqlShortcutForm.value, shortcut };+ editingSqlShortcutInputId.value = null;+}++function focusSqlShortcutInput(id: string) {+ editingSqlShortcutInputId.value = id;+ const input = document.querySelector<HTMLInputElement>(`[data-sql-shortcut-input="${id}"]`);+ requestAnimationFrame(() => {+ input?.focus();+ input?.select();+ });+}++function cancelSqlShortcutInputEdit() {+ editingSqlShortcutInputId.value = null;+}++function clearSqlShortcutBinding() {+ sqlShortcutForm.value = { ...sqlShortcutForm.value, shortcut: "" };+}++async function commitSqlShortcuts() {+ const sqlShortcuts = editSqlShortcuts.value.map(editableSqlShortcut);+ try {+ await settingsStore.updateEditorSettingsAndPersist({ sqlShortcuts });+ editEditorSettingsBase.value = {+ ...editEditorSettingsBase.value,+ sqlShortcuts: JSON.parse(JSON.stringify(sqlShortcuts)) as SqlShortcutAction[],+ };+ } catch (error) {+ applySettingsErrorToast(error);+ }+}+const uiFontPreviewValues = new Set([DEFAULT_UI_FONT_FAMILY, SYSTEM_UI_FONT_FAMILY]);const systemFontOptions = computed(() => {@@ -920,6 +1055,7 @@ function syncEditorSettingsDraftFromStore() {editUpdateDownloadSource.value = settingsStore.editorSettings.updateDownloadSource;editToolbarItems.value = { ...settingsStore.editorSettings.toolbarItems };editSnippets.value = settingsStore.editorSettings.snippets.map(editableSnippet);+ editSqlShortcuts.value = settingsStore.editorSettings.sqlShortcuts.map(editableSqlShortcut);editSqlVariableSubstitutionEnabled.value = settingsStore.editorSettings.sqlVariableSubstitutionEnabled;editSqlVariableSyntaxOverrides.value = normalizeSqlVariableSyntaxOverrides(settingsStore.editorSettings.sqlVariableSyntaxOverrides);editClickTableNavigationTarget.value = settingsStore.editorSettings.clickTableNavigationTarget;@@ -960,6 +1096,8 @@ const shortcutConflicts = computed(() =>return conflict ? [definition.id] : [];}),);+const sqlShortcutConflicts = computed(() => findSqlShortcutConflicts(editSqlShortcuts.value, editShortcuts.value));+const hasSqlShortcutConflicts = computed(() => sqlShortcutConflicts.value.length > 0);const shortcutSearchQuery = ref("");const formatterEditorShortcutIds: ShortcutActionId[] = ["formatSql",@@ -997,8 +1135,13 @@ const filteredShortcutDefinitions = computed(() => {});const hasShortcutConflicts = computed(() => shortcutConflicts.value.length > 0);const shortcutsChanged = computed(() => JSON.stringify(editShortcuts.value) !== JSON.stringify(editEditorSettingsBase.value.shortcuts));+const sqlShortcutsChanged = computed(() => JSON.stringify(editSqlShortcuts.value) !== JSON.stringify(editEditorSettingsBase.value.sqlShortcuts));const duckDbWorkerSettingsRequireRestart = computed(() => editDuckDbWorkerProcessIsolation.value !== startupDuckDbWorkerProcessIsolation.value || normalizeDuckDbWorkerMaxProcesses(editDuckDbWorkerMaxProcesses.value) !== startupDuckDbWorkerMaxProcesses.value);-const hasBlockingShortcutConflicts = computed(() => shortcutsChanged.value && hasShortcutConflicts.value);+const hasBlockingShortcutConflicts = computed(() => {+ const shortcutDraftTouched = shortcutsChanged.value || sqlShortcutsChanged.value;+ if (!shortcutDraftTouched) return false;+ return hasShortcutConflicts.value || hasSqlShortcutConflicts.value;+});const hasBlockingFormatterConfig = computed(() => activeSettingsTab.value === "formatter" && !sqlFormatterConfigValid.value);const hasBlockingQueryResultRowLimit = computed(() => editQueryResultMaxRowsEnabled.value && editQueryResultMaxRows.value < editPageSize.value);const hasApplyBlocker = computed(() => hasBlockingShortcutConflicts.value || hasBlockingFormatterConfig.value || hasBlockingQueryResultRowLimit.value);@@ -1304,6 +1447,7 @@ function resetAllDefaults() {editUpdateDownloadSource.value = DEFAULT_EDITOR_SETTINGS.updateDownloadSource;editToolbarItems.value = { ...DEFAULT_EDITOR_SETTINGS.toolbarItems };editSnippets.value = DEFAULT_SQL_SNIPPETS.map((s) => ({ ...s }));+ editSqlShortcuts.value = [];}function addTableColumnTemplateRow() {@@ -5957,6 +6101,70 @@ onUnmounted(() => {</div></div></div>++ <div class="mt-6 border-t border-border/70 pt-6" data-settings-search-id="sql-shortcuts">+ <div class="mb-4 flex items-center justify-between gap-3">+ <div class="min-w-0">+ <h3 class="text-sm font-medium">{{ t("settings.sqlShortcutsTitle") }}</h3>+ <p class="mt-1 text-sm text-muted-foreground">+ {{ t("settings.sqlShortcutsDescription") }}+ </p>+ </div>+ <Button variant="outline" size="sm" class="shrink-0" @click="openAddSqlShortcutDialog">+ <Plus class="mr-2 h-4 w-4" />+ {{ t("settings.sqlShortcutsAdd") }}+ </Button>+ </div>++ <div v-if="editSqlShortcuts.length === 0" class="rounded-md border border-dashed border-border/70 px-3 py-8 text-center text-sm text-muted-foreground">+ {{ t("settings.sqlShortcutsEmpty") }}+ </div>+ <div v-else class="overflow-x-auto rounded-md border">+ <table class="w-full min-w-[720px] text-sm">+ <thead>+ <tr class="border-b bg-muted/50">+ <th class="px-3 py-2 text-left font-medium whitespace-nowrap">{{ t("settings.sqlShortcutsLabel") }}</th>+ <th class="px-3 py-2 text-left font-medium whitespace-nowrap">{{ t("settings.shortcutPressShortcut") }}</th>+ <th class="px-3 py-2 text-left font-medium whitespace-nowrap">{{ t("settings.snippetsStatus") }}</th>+ <th class="px-3 py-2 text-left font-medium whitespace-nowrap">{{ t("settings.sqlShortcutsSql") }}</th>+ <th class="px-3 py-2 w-20"></th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="action in editSqlShortcuts" :key="action.id" class="border-b last:border-b-0 hover:bg-muted/30" :class="action.enabled === false ? 'text-muted-foreground' : ''">+ <td class="px-3 py-2">{{ action.label }}</td>+ <td class="px-3 py-2">+ <Badge variant="outline" class="h-5 rounded-md px-1.5 font-mono text-[11px] text-muted-foreground">+ {{ action.shortcut ? formatShortcutPill(action.shortcut) : t("settings.sqlShortcutsUnbound") }}+ </Badge>+ </td>+ <td class="px-3 py-2">+ <div class="flex items-center gap-2">+ <Switch :id="`sql-shortcut-enabled-${action.id}`" :model-value="action.enabled !== false" size="sm" :aria-label="t('settings.sqlShortcutsToggle')" @update:model-value="(value: boolean) => setSqlShortcutEnabled(action.id, value)" />+ <Label :for="`sql-shortcut-enabled-${action.id}`" class="text-xs font-normal text-muted-foreground">+ {{ action.enabled === false ? t("settings.snippetsDisabled") : t("settings.snippetsEnabled") }}+ </Label>+ </div>+ </td>+ <td class="max-w-[300px] truncate px-3 py-2 font-mono text-xs text-muted-foreground">{{ action.sql }}</td>+ <td class="px-3 py-2">+ <div class="flex items-center gap-1">+ <Button variant="ghost" size="icon-xs" @click="openEditSqlShortcutDialog(action)">+ <Pencil class="size-3.5" />+ </Button>+ <Button variant="ghost" size="icon-xs" @click="confirmDeleteSqlShortcut(action)">+ <Trash2 class="size-3.5" />+ </Button>+ </div>+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ <p v-if="hasSqlShortcutConflicts" class="mt-2 text-xs text-destructive">+ {{ t("settings.shortcutConflict") }}+ </p>+ </div></section><!-- Snippets Tab -->@@ -7527,6 +7735,68 @@ onUnmounted(() => {</DialogContent></Dialog>+ <!-- SQL Shortcut Add/Edit Dialog -->+ <Dialog :open="sqlShortcutDialogOpen" @update:open="sqlShortcutDialogOpen = $event">+ <DialogContent class="sm:max-w-[560px]">+ <DialogHeader>+ <DialogTitle>+ {{ sqlShortcutEditingId ? t("settings.sqlShortcutsEditTitle") : t("settings.sqlShortcutsAddTitle") }}+ </DialogTitle>+ </DialogHeader>+ <div class="flex flex-col gap-4 py-2">+ <div class="flex flex-col gap-1.5">+ <Label for="sql-shortcut-label">{{ t("settings.sqlShortcutsLabel") }}</Label>+ <Input id="sql-shortcut-label" v-model="sqlShortcutForm.label" :placeholder="t('settings.sqlShortcutsLabelPlaceholder')" />+ <p v-if="sqlShortcutFormLabelError" class="text-xs text-destructive">+ {{ sqlShortcutFormLabelError }}+ </p>+ </div>+ <div class="flex flex-col gap-1.5">+ <Label for="sql-shortcut-binding">{{ t("settings.shortcutPressShortcut") }}</Label>+ <div class="flex items-center gap-2">+ <input+ id="sql-shortcut-binding"+ data-sql-shortcut-input="dialog"+ :value="editingSqlShortcutInputId === 'dialog' ? '' : formatShortcutPill(sqlShortcutForm.shortcut)"+ :style="{ width: editingSqlShortcutInputId === 'dialog' ? shortcutPressShortcutInputWidth : `${Math.max(4, formatShortcutPill(sqlShortcutForm.shortcut).length + 3)}ch` }"+ readonly+ :placeholder="t('settings.shortcutPressShortcut')"+ class="h-8 w-auto min-w-12 max-w-64 shrink-0 cursor-default rounded-[6px] border border-input bg-muted px-2.5 text-center font-mono text-[13px] font-semibold text-foreground/75 shadow-inner outline-none selection:bg-transparent placeholder:text-muted-foreground"+ :class="editingSqlShortcutInputId === 'dialog' ? 'max-w-64 cursor-text border-border/80 bg-background text-left text-foreground shadow-none focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/35' : ''"+ @keydown="(event: KeyboardEvent) => onSqlShortcutBindingKeydown('dialog', event)"+ />+ <Button v-if="editingSqlShortcutInputId !== 'dialog'" type="button" variant="ghost" size="icon" class="h-8 w-8 shrink-0" :aria-label="t('settings.shortcutPressShortcut')" @click="focusSqlShortcutInput('dialog')">+ <Pencil class="h-4 w-4" />+ </Button>+ <Button v-else type="button" variant="ghost" size="sm" class="h-8 shrink-0 px-2 text-sm font-medium text-muted-foreground hover:text-foreground" @click="cancelSqlShortcutInputEdit">+ {{ t("settings.cancel") }}+ </Button>+ <Button v-if="sqlShortcutForm.shortcut" type="button" variant="ghost" size="icon" class="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive" :aria-label="t('settings.shortcutClear')" @click="clearSqlShortcutBinding">+ <X class="h-4 w-4" />+ </Button>+ </div>+ </div>+ <div class="flex flex-col gap-1.5">+ <Label for="sql-shortcut-sql">{{ t("settings.sqlShortcutsSql") }}</Label>+ <textarea+ id="sql-shortcut-sql"+ v-model="sqlShortcutForm.sql"+ :placeholder="t('settings.sqlShortcutsSqlPlaceholder')"+ rows="6"+ class="flex min-h-[120px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm font-mono shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ />+ <p class="text-xs text-muted-foreground">+ {{ t("settings.sqlShortcutsVariableHint", { token: SQL_SHORTCUT_TABLE_TOKEN }) }}+ </p>+ </div>+ </div>+ <DialogFooter>+ <Button variant="outline" @click="sqlShortcutDialogOpen = false">{{ t("settings.cancel") }}</Button>+ <Button @click="saveSqlShortcut">{{ t("settings.save") }}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+<!-- AI Config Delete Confirmation --><DangerConfirmDialog v-model:open="aiDeleteConfirmOpen" :title="t('ai.deleteConfigTitle')" :message="t('ai.deleteConfigConfirm')" :confirm-label="t('common.delete')" @confirm="aiConfirmDeleteConfig" /><DangerConfirmDialogdiff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vueindex 14cfa90d49..0075e95ea8 100644--- a/apps/desktop/src/components/editor/QueryEditor.vue+++ b/apps/desktop/src/components/editor/QueryEditor.vue@@ -112,6 +112,7 @@ import { isPointOverElementRoot } from "@/lib/editor/tableReferenceDragFeedback"import type { SqlHighlighter } from "@/lib/sql/sqlHighlighter";import { EDITOR_FONT_FAMILY_CSS_VAR, EDITOR_FONT_SIZE_CSS_VAR, editorDiagnosticColors, editorThemeAppearanceFor, loadEditorTheme, editorFontTheme, shellLineCommentTheme, sqlCompletionTheme, sqlSemanticHighlightTheme } from "@/lib/editor/editorThemes";import { createStatementGutterMarkerDom, shouldShowStatementGutter } from "@/lib/editor/codemirrorStatementGutter";+import { createQueryEditorSqlShortcutDomHandler, isCharacterProducingShortcut } from "@/lib/editor/queryEditorSqlShortcut";import { createQueryEditorReplaceShortcutBindings, createQueryEditorReplaceShortcutHandler, createQueryEditorSearchKeymap } from "@/lib/editor/queryEditorSearchKeymap";import { buildQueryEditorLineNumbersExtension } from "@/lib/editor/queryEditorLineNumbers";import { searchKeymapWithoutModD } from "@/lib/editor/codemirrorSearchKeymap";@@ -119,6 +120,7 @@ import { defaultKeymapForGlobalShortcuts } from "@/lib/editor/codemirrorDefaultKimport { appendSqlCompletionSpace } from "@/lib/editor/sqlCompletionInsertion";import { compareSqlCompletions, completionLabelPresentation } from "@/lib/editor/sqlCompletionPresentation";import { clampEditorFontSize, createEditorWheelZoomGestureGuard, createEditorZoomCommitScheduler, fontSizeFromGestureScale, fontSizeFromWheelDelta } from "@/lib/editor/editorZoom";+import { enabledSqlShortcutActions, resolveSqlShortcutTemplate } from "@/lib/sql/sqlShortcutActions";import { normalizeShortcutSettings, shortcutToCodeMirrorKey } from "@/lib/editor/shortcutRegistry";import { trimmedSelectionLayer } from "@/lib/editor/codemirrorTrimmedSelectionLayer";import { currentStatementFrameLayer } from "@/lib/editor/codemirrorCurrentStatementFrameLayer";@@ -1927,6 +1929,18 @@ function handleSqlIntentionActions(currentView: EditorViewType): boolean {}}+function runSqlShortcutAction(action: ReturnType<typeof enabledSqlShortcutActions>[number], currentView: EditorViewType, event?: KeyboardEvent): boolean {+ if (shouldBlockExecutionShortcut(event, currentView)) return true;+ if (props.readOnly) return true;+ const { from, to, empty } = currentView.state.selection.main;+ if (empty) return false;+ const selected = currentView.state.sliceDoc(from, to).trim();+ if (!selected) return false;+ const sql = resolveSqlShortcutTemplate(action.sql, selected);+ emitExecutionRequest(sql);+ return true;+}+function runKeymapExtension(codeMirrorKeymap: (typeof import("@codemirror/view"))["keymap"]) {const shortcuts = normalizeShortcutSettings(settingsStore.editorSettings.shortcuts);const Prec = codeMirrorPrec;@@ -1947,11 +1961,22 @@ function runKeymapExtension(codeMirrorKeymap: (typeof import("@codemirror/view")openReplace,isReadOnly: () => !!props.readOnly,});+ const sqlShortcutActions = enabledSqlShortcutActions(settingsStore.editorSettings.sqlShortcuts);+ const sqlShortcutKeymapActions = sqlShortcutActions.filter((action) => !isCharacterProducingShortcut(action.shortcut));+ const sqlShortcutBindings = sqlShortcutKeymapActions.flatMap((action) => binding(action.shortcut, (currentView) => runSqlShortcutAction(action, currentView)));+ const sqlShortcutDomHandler = createQueryEditorSqlShortcutDomHandler(+ () => settingsStore.editorSettings.sqlShortcuts,+ (action, currentView, event) => runSqlShortcutAction(action, currentView, event),+ );+ const combinedDomKeydownHandler = (event: KeyboardEvent, view: EditorViewType) => {+ if (replaceShortcutHandler(event)) return true;+ return sqlShortcutDomHandler(event, view);+ };return [editorViewModule? (Prec?.high(editorViewModule.EditorView.domEventHandlers({- keydown: replaceShortcutHandler,+ keydown: combinedDomKeydownHandler,}),) ?? []): [],@@ -2018,6 +2043,7 @@ function runKeymapExtension(codeMirrorKeymap: (typeof import("@codemirror/view")openReplace,isReadOnly: () => !!props.readOnly,}),+ ...sqlShortcutBindings,]),) ?? [],codeMirrorKeymap.of(@@ -5967,10 +5993,19 @@ watch();watch(- () => settingsStore.editorSettings.shortcuts,+ () => [settingsStore.editorSettings.shortcuts, settingsStore.editorSettings.sqlShortcuts],() => {- if (!view.value || !defaultKeymapComp) return;- view.value.dispatch({ effects: defaultKeymapComp.reconfigure(defaultKeymapExtension()) });+ if (!view.value || !editorViewModule) return;+ const effects = [];+ if (defaultKeymapComp) {+ effects.push(defaultKeymapComp.reconfigure(defaultKeymapExtension()));+ }+ if (runKeymapComp) {+ effects.push(runKeymapComp.reconfigure(runKeymapExtension(editorViewModule.keymap)));+ }+ if (effects.length > 0) {+ view.value.dispatch({ effects });+ }},{ deep: true },);diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 6f0a9c463d..a2d6b3501f 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -6447,6 +6447,21 @@ export default {snippetsRestoreDefaults: "Restore Defaults",snippetsAddTitle: "Add Snippet",snippetsEditTitle: "Edit Snippet",+ sqlShortcutsTitle: "SQL Quick Actions",+ sqlShortcutsDescription: "Custom SQL templates executed after selecting a table name in the SQL editor. Select a table identifier first; shortcuts with Cmd/Ctrl are recommended.",+ sqlShortcutsAdd: "Add",+ sqlShortcutsAddTitle: "Add SQL Quick Action",+ sqlShortcutsEditTitle: "Edit SQL Quick Action",+ sqlShortcutsLabel: "Label",+ sqlShortcutsLabelPlaceholder: "e.g. Count rows",+ sqlShortcutsLabelRequired: "Label is required.",+ sqlShortcutsSql: "SQL Template",+ sqlShortcutsSqlPlaceholder: "SELECT COUNT(*) FROM ${table}",+ sqlShortcutsVariableHint: "Use {token} for the selected table name.",+ sqlShortcutsEmpty: "No SQL quick actions yet.",+ sqlShortcutsUnbound: "Unbound",+ sqlShortcutsToggle: "Enable or disable SQL shortcut",+ sqlShortcutsDeleteConfirm: 'Delete SQL shortcut "{name}"?',syncWebDavTitle: "WebDAV Sync",syncWebDavDescription: "Upload or restore a DBX snapshot, including saved SQL library entries, from a WebDAV-compatible storage service.",syncWebDavWebDescription: "In Web mode, the DBX server accesses WebDAV without browser CORS restrictions. Saved passwords remain in the current DBX instance.",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex eba91a949f..4c51ebb9e6 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -6141,6 +6141,21 @@ export default withEnglishFallback({snippetsRestoreDefaults: "Restaurar valores por defecto",snippetsAddTitle: "Agregar fragmento",snippetsEditTitle: "Editar fragmento",+ sqlShortcutsTitle: "Acciones rápidas SQL",+ sqlShortcutsDescription: "Plantillas SQL personalizadas que se ejecutan después de seleccionar un nombre de tabla en el editor SQL. Selecciona primero un identificador de tabla; se recomiendan atajos con Cmd/Ctrl.",+ sqlShortcutsAdd: "Agregar",+ sqlShortcutsAddTitle: "Agregar acción rápida SQL",+ sqlShortcutsEditTitle: "Editar acción rápida SQL",+ sqlShortcutsLabel: "Etiqueta",+ sqlShortcutsLabelPlaceholder: "p. ej. Contar filas",+ sqlShortcutsLabelRequired: "La etiqueta es obligatoria.",+ sqlShortcutsSql: "Plantilla SQL",+ sqlShortcutsSqlPlaceholder: "SELECT COUNT(*) FROM ${table}",+ sqlShortcutsVariableHint: "Usa {token} para el nombre de tabla seleccionado.",+ sqlShortcutsEmpty: "Aún no hay acciones rápidas SQL.",+ sqlShortcutsUnbound: "Sin asignar",+ sqlShortcutsToggle: "Activar o desactivar atajo SQL",+ sqlShortcutsDeleteConfirm: '¿Eliminar el atajo SQL "{name}"?',syncWebDavTitle: "Sincronización WebDAV",syncWebDavDescription: "Sube o restaura una instantánea de DBX, incluida la biblioteca SQL guardada, desde almacenamiento compatible con WebDAV.",syncWebDavWebDescription: "En modo Web, el servidor DBX accede a WebDAV sin las restricciones CORS del navegador. Las contraseñas guardadas permanecen en la instancia DBX actual.",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex b8736fb373..71557286b6 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -6141,6 +6141,21 @@ export default withEnglishFallback({snippetsRestoreDefaults: "Ripristina Predefiniti",snippetsAddTitle: "Aggiungi Snippet",snippetsEditTitle: "Modifica Snippet",+ sqlShortcutsTitle: "Azioni rapide SQL",+ sqlShortcutsDescription: "Modelli SQL personalizzati eseguiti dopo aver selezionato un nome di tabella nell'editor SQL. Seleziona prima un identificatore di tabella; si consigliano scorciatoie con Cmd/Ctrl.",+ sqlShortcutsAdd: "Aggiungi",+ sqlShortcutsAddTitle: "Aggiungi azione rapida SQL",+ sqlShortcutsEditTitle: "Modifica azione rapida SQL",+ sqlShortcutsLabel: "Etichetta",+ sqlShortcutsLabelPlaceholder: "es. Conta righe",+ sqlShortcutsLabelRequired: "L'etichetta è obbligatoria.",+ sqlShortcutsSql: "Modello SQL",+ sqlShortcutsSqlPlaceholder: "SELECT COUNT(*) FROM ${table}",+ sqlShortcutsVariableHint: "Usa {token} per il nome della tabella selezionata.",+ sqlShortcutsEmpty: "Nessuna azione rapida SQL ancora.",+ sqlShortcutsUnbound: "Non assegnato",+ sqlShortcutsToggle: "Attiva o disattiva scorciatoia SQL",+ sqlShortcutsDeleteConfirm: 'Eliminare la scorciatoia SQL "{name}"?',syncWebDavTitle: "Sincronizzazione WebDAV",syncWebDavDescription: "Carica o ripristina uno snapshot di DBX, inclusa la libreria SQL salvata, da un servizio di archiviazione compatibile con WebDAV.",syncWebDavWebDescription: "In modalità Web, il server DBX accede a WebDAV senza le limitazioni CORS del browser. Le password salvate restano nell'istanza DBX corrente.",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex d8cffd0521..65c76b6cca 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -6167,6 +6167,21 @@ export default withEnglishFallback({snippetsRestoreDefaults: "デフォルトに戻す",snippetsAddTitle: "スニペットを追加",snippetsEditTitle: "スニペットを編集",+ sqlShortcutsTitle: "SQLクイックアクション",+ sqlShortcutsDescription: "SQLエディターでテーブル名を選択した後に実行するカスタムSQLテンプレート。先にテーブル識別子を選択してください。Cmd/Ctrlを含むショートカットを推奨します。",+ sqlShortcutsAdd: "追加",+ sqlShortcutsAddTitle: "SQLクイックアクションを追加",+ sqlShortcutsEditTitle: "SQLクイックアクションを編集",+ sqlShortcutsLabel: "ラベル",+ sqlShortcutsLabelPlaceholder: "例: 行数をカウント",+ sqlShortcutsLabelRequired: "ラベルは必須です。",+ sqlShortcutsSql: "SQLテンプレート",+ sqlShortcutsSqlPlaceholder: "SELECT COUNT(*) FROM ${table}",+ sqlShortcutsVariableHint: "選択したテーブル名には {token} を使用します。",+ sqlShortcutsEmpty: "SQLクイックアクションはまだありません。",+ sqlShortcutsUnbound: "未割り当て",+ sqlShortcutsToggle: "SQLショートカットを有効または無効にする",+ sqlShortcutsDeleteConfirm: "SQLショートカット「{name}」を削除しますか?",syncWebDavTitle: "WebDAV同期",syncWebDavDescription: "保存済みSQLライブラリを含むDBXスナップショットをWebDAV互換ストレージへアップロードまたは復元します。",syncWebDavWebDescription: "WebモードではDBXサーバーがWebDAVへ接続するため、ブラウザーのCORS制限を受けません。保存したパスワードは現在のDBXインスタンス内に保持されます。",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex c42ef6d554..db63b6f6cf 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -5832,6 +5832,21 @@ export default withEnglishFallback({snippetsRestoreDefaults: "기본값 복원",snippetsAddTitle: "스니펫 추가",snippetsEditTitle: "스니펫 편집",+ sqlShortcutsTitle: "SQL 빠른 작업",+ sqlShortcutsDescription: "SQL 편집기에서 테이블 이름을 선택한 후 실행하는 사용자 지정 SQL 템플릿입니다. 먼저 테이블 식별자를 선택하세요. Cmd/Ctrl이 포함된 단축키를 권장합니다.",+ sqlShortcutsAdd: "추가",+ sqlShortcutsAddTitle: "SQL 빠른 작업 추가",+ sqlShortcutsEditTitle: "SQL 빠른 작업 편집",+ sqlShortcutsLabel: "라벨",+ sqlShortcutsLabelPlaceholder: "예: 행 수 세기",+ sqlShortcutsLabelRequired: "라벨은 필수입니다.",+ sqlShortcutsSql: "SQL 템플릿",+ sqlShortcutsSqlPlaceholder: "SELECT COUNT(*) FROM ${table}",+ sqlShortcutsVariableHint: "선택한 테이블 이름에는 {token}을 사용하세요.",+ sqlShortcutsEmpty: "아직 SQL 빠른 작업이 없습니다.",+ sqlShortcutsUnbound: "미할당",+ sqlShortcutsToggle: "SQL 단축키 활성화 또는 비활성화",+ sqlShortcutsDeleteConfirm: 'SQL 단축키 "{name}"을(를) 삭제하시겠습니까?',syncWebDavTitle: "WebDAV 동기화",syncWebDavDescription: "WebDAV 호환 저장 서비스에서 DBX 스냅샷을 업로드하거나 복원합니다(저장된 SQL 라이브러리 항목 포함).",syncWebDavWebDescription: "Web 모드에서는 DBX 서버가 WebDAV에 연결하므로 브라우저 CORS 제한을 받지 않습니다. 저장된 비밀번호는 현재 DBX 인스턴스에 유지됩니다.",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 302bd50ec2..083f7057e7 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -6143,6 +6143,21 @@ export default withEnglishFallback({snippetsRestoreDefaults: "Restaurar padrões",snippetsAddTitle: "Adicionar snippet",snippetsEditTitle: "Editar snippet",+ sqlShortcutsTitle: "Ações rápidas SQL",+ sqlShortcutsDescription: "Modelos SQL personalizados executados após selecionar um nome de tabela no editor SQL. Selecione primeiro um identificador de tabela; atalhos com Cmd/Ctrl são recomendados.",+ sqlShortcutsAdd: "Adicionar",+ sqlShortcutsAddTitle: "Adicionar ação rápida SQL",+ sqlShortcutsEditTitle: "Editar ação rápida SQL",+ sqlShortcutsLabel: "Rótulo",+ sqlShortcutsLabelPlaceholder: "ex.: Contar linhas",+ sqlShortcutsLabelRequired: "O rótulo é obrigatório.",+ sqlShortcutsSql: "Modelo SQL",+ sqlShortcutsSqlPlaceholder: "SELECT COUNT(*) FROM ${table}",+ sqlShortcutsVariableHint: "Use {token} para o nome da tabela selecionada.",+ sqlShortcutsEmpty: "Nenhuma ação rápida SQL ainda.",+ sqlShortcutsUnbound: "Não atribuído",+ sqlShortcutsToggle: "Ativar ou desativar atalho SQL",+ sqlShortcutsDeleteConfirm: 'Excluir o atalho SQL "{name}"?',syncWebDavTitle: "Sincronização WebDAV",syncWebDavDescription: "Envie ou restaure um snapshot do DBX, incluindo a biblioteca SQL salva, a partir de um serviço de armazenamento compatível com WebDAV.",syncWebDavWebDescription: "No modo Web, o servidor DBX acessa o WebDAV sem as restrições de CORS do navegador. As senhas salvas permanecem na instância DBX atual.",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 77e9ce60da..7edaea89ec 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -6430,6 +6430,21 @@ export default withEnglishFallback({snippetsRestoreDefaults: "恢复默认",snippetsAddTitle: "添加片段",snippetsEditTitle: "编辑片段",+ sqlShortcutsTitle: "SQL 快捷操作",+ sqlShortcutsDescription: "自定义在 SQL 编辑器中选中表名后执行的 SQL 模板。需先选中表名;建议使用含 Cmd/Ctrl 的组合键。",+ sqlShortcutsAdd: "添加",+ sqlShortcutsAddTitle: "添加 SQL 快捷键",+ sqlShortcutsEditTitle: "编辑 SQL 快捷键",+ sqlShortcutsLabel: "显示名",+ sqlShortcutsLabelPlaceholder: "如:统计行数",+ sqlShortcutsLabelRequired: "显示名为必填项。",+ sqlShortcutsSql: "SQL 模板",+ sqlShortcutsSqlPlaceholder: "SELECT COUNT(*) FROM ${table}",+ sqlShortcutsVariableHint: "使用 {token} 表示选中的表名。",+ sqlShortcutsEmpty: "暂无 SQL 快捷操作。",+ sqlShortcutsUnbound: "未绑定",+ sqlShortcutsToggle: "启用或关闭 SQL 快捷键",+ sqlShortcutsDeleteConfirm: "删除 SQL 快捷键「{name}」?",syncWebDavTitle: "WebDAV 同步",syncWebDavDescription: "将包含 SQL 库的 DBX 快照上传到兼容 WebDAV 的存储服务,或从远端恢复。",syncWebDavWebDescription: "Web 模式下由 DBX 服务端访问 WebDAV,不受浏览器 CORS 限制;保存的密码会留在当前 DBX 实例中。",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex b3793dbafc..c2481e5fd8 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -5459,6 +5459,21 @@ export default withEnglishFallback({snippetsRestoreDefaults: "還原預設",snippetsAddTitle: "新增片段",snippetsEditTitle: "編輯片段",+ sqlShortcutsTitle: "SQL 快捷操作",+ sqlShortcutsDescription: "自訂在 SQL 編輯器中選取表名後執行的 SQL 範本。需先選取表名;建議使用含 Cmd/Ctrl 的組合鍵。",+ sqlShortcutsAdd: "新增",+ sqlShortcutsAddTitle: "新增 SQL 快捷鍵",+ sqlShortcutsEditTitle: "編輯 SQL 快捷鍵",+ sqlShortcutsLabel: "顯示名",+ sqlShortcutsLabelPlaceholder: "如:統計行數",+ sqlShortcutsLabelRequired: "顯示名為必填項。",+ sqlShortcutsSql: "SQL 範本",+ sqlShortcutsSqlPlaceholder: "SELECT COUNT(*) FROM ${table}",+ sqlShortcutsVariableHint: "使用 {token} 表示選取的表名。",+ sqlShortcutsEmpty: "暫無 SQL 快捷操作。",+ sqlShortcutsUnbound: "未綁定",+ sqlShortcutsToggle: "啟用或關閉 SQL 快捷鍵",+ sqlShortcutsDeleteConfirm: "刪除 SQL 快捷鍵「{name}」?",syncWebDavTitle: "WebDAV 同步",syncWebDavDescription: "上傳包含 SQL 庫的 DBX 快照到相容 WebDAV 的儲存服務,或從該服務還原快照。",syncWebDavWebDescription: "Web 模式由 DBX 伺服器端存取 WebDAV,不受瀏覽器 CORS 限制;儲存的密碼會保留在目前 DBX 執行個體中。",diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorExecution.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorExecution.spec.tsindex 8600a63386..ed33c46fdc 100644--- a/apps/desktop/src/lib/__tests__/editor/queryEditorExecution.spec.ts+++ b/apps/desktop/src/lib/__tests__/editor/queryEditorExecution.spec.ts@@ -99,6 +99,18 @@ describe("QueryEditor execution routing", () => {expect(queryEditorSource).toContain("const cursor = line.to + insertion.length");expect(queryEditorSource).not.toMatch(/key:\s*"Enter"[\s\S]{0,180}shift:\s*codeMirrorInsertNewlineKeepIndent/);});++ it("routes custom SQL shortcuts through selection-aware execution with dual keymap and DOM handlers", () => {+ expect(queryEditorSource).toContain("function runSqlShortcutAction(");+ expect(queryEditorSource).toContain("resolveSqlShortcutTemplate(action.sql, selected)");+ expect(queryEditorSource).toContain("enabledSqlShortcutActions(settingsStore.editorSettings.sqlShortcuts)");+ expect(queryEditorSource).toContain("isCharacterProducingShortcut(action.shortcut)");+ expect(queryEditorSource).toContain("createQueryEditorSqlShortcutDomHandler(");+ expect(queryEditorSource).toContain("shouldBlockExecutionShortcut(event, currentView)");+ expect(queryEditorSource).toContain("if (props.readOnly) return true;");+ expect(queryEditorSource).toContain("settingsStore.editorSettings.sqlShortcuts");+ expect(queryEditorSource).toContain("runKeymapComp.reconfigure(runKeymapExtension(editorViewModule.keymap))");+ });});describe("QueryEditor execution viewport ownership", () => {diff --git a/apps/desktop/src/lib/__tests__/editor/queryEditorSqlShortcut.spec.ts b/apps/desktop/src/lib/__tests__/editor/queryEditorSqlShortcut.spec.tsnew file mode 100644index 0000000000..fec1e2cab7--- /dev/null+++ b/apps/desktop/src/lib/__tests__/editor/queryEditorSqlShortcut.spec.ts@@ -0,0 +1,78 @@+import { describe, expect, it, vi } from "vitest";+import { matchesShortcut } from "@/lib/editor/keyboardShortcuts";+import { createQueryEditorSqlShortcutDomHandler, isCharacterProducingShortcut } from "@/lib/editor/queryEditorSqlShortcut";+import type { SqlShortcutAction } from "@/types/database";+// pi-lens-ignore: typescript:2307+import type { EditorView } from "@codemirror/view";++function action(id: string, shortcut: string, overrides: Partial<SqlShortcutAction> = {}): SqlShortcutAction {+ return {+ id,+ label: id,+ shortcut,+ sql: "SELECT * FROM ${table}",+ enabled: true,+ ...overrides,+ };+}++describe("isCharacterProducingShortcut", () => {+ it("treats Shift+letter shortcuts as character-producing", () => {+ expect(isCharacterProducingShortcut("Shift+U")).toBe(true);+ expect(isCharacterProducingShortcut("u")).toBe(true);+ });++ it("treats modifier shortcuts as non character-producing", () => {+ expect(isCharacterProducingShortcut("Mod+Shift+9")).toBe(false);+ expect(isCharacterProducingShortcut("Shift+Alt+U")).toBe(false);+ expect(isCharacterProducingShortcut("Shift+Enter")).toBe(false);+ });+});++describe("matchesShortcut for Shift+U", () => {+ it("matches uppercase U with shift held", () => {+ expect(matchesShortcut({ key: "U", shiftKey: true }, "Shift+U", "MacIntel")).toBe(true);+ });+});++function keydownEvent(overrides: { key: string; shiftKey?: boolean; metaKey?: boolean; ctrlKey?: boolean; altKey?: boolean }) {+ return {+ ...overrides,+ preventDefault: vi.fn(),+ };+}++describe("createQueryEditorSqlShortcutDomHandler", () => {+ const view = {} as EditorView;++ it("runs the action and prevents default when there is a selection", () => {+ const runAction = vi.fn(() => true);+ const handler = createQueryEditorSqlShortcutDomHandler(() => [action("a", "Shift+U")], runAction, "MacIntel");+ const event = keydownEvent({ key: "U", shiftKey: true });++ expect(handler(event as unknown as KeyboardEvent, view)).toBe(true);+ expect(runAction).toHaveBeenCalledOnce();+ expect(runAction).toHaveBeenCalledWith(expect.objectContaining({ id: "a" }), view, event);+ expect(event.preventDefault).toHaveBeenCalled();+ });++ it("does not intercept when there is no selection", () => {+ const runAction = vi.fn(() => false);+ const handler = createQueryEditorSqlShortcutDomHandler(() => [action("a", "Shift+U")], runAction, "MacIntel");+ const event = keydownEvent({ key: "U", shiftKey: true });++ expect(handler(event as unknown as KeyboardEvent, view)).toBe(false);+ expect(runAction).toHaveBeenCalledOnce();+ expect(runAction).toHaveBeenCalledWith(expect.objectContaining({ id: "a" }), view, event);+ expect(event.preventDefault).not.toHaveBeenCalled();+ });++ it("ignores non character-producing shortcuts", () => {+ const runAction = vi.fn(() => true);+ const handler = createQueryEditorSqlShortcutDomHandler(() => [action("a", "Mod+Shift+9")], runAction, "MacIntel");+ const event = keydownEvent({ key: "9", metaKey: true, shiftKey: true });++ expect(handler(event as unknown as KeyboardEvent, view)).toBe(false);+ expect(runAction).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/lib/__tests__/sql/sqlShortcutActions.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlShortcutActions.spec.tsnew file mode 100644index 0000000000..1d4a83bdc3--- /dev/null+++ b/apps/desktop/src/lib/__tests__/sql/sqlShortcutActions.spec.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from "vitest";+import { DEFAULT_SHORTCUT_SETTINGS } from "@/lib/editor/shortcutRegistry";+import { enabledSqlShortcutActions, findSqlShortcutConflicts, hasSqlShortcutConflicts, resolveSqlShortcutTemplate } from "@/lib/sql/sqlShortcutActions";+import type { SqlShortcutAction } from "@/types/database";++function action(id: string, shortcut: string, overrides: Partial<SqlShortcutAction> = {}): SqlShortcutAction {+ return {+ id,+ label: id,+ shortcut,+ sql: "SELECT * FROM ${table}",+ enabled: true,+ ...overrides,+ };+}++describe("resolveSqlShortcutTemplate", () => {+ it("replaces ${table} with trimmed selection", () => {+ expect(resolveSqlShortcutTemplate("SELECT * FROM ${table}", " orders ")).toBe("SELECT * FROM orders");+ });++ it("replaces all occurrences", () => {+ expect(resolveSqlShortcutTemplate("SELECT * FROM ${table} JOIN ${table}", "public.users")).toBe("SELECT * FROM public.users JOIN public.users");+ });++ it("does not expand replacement patterns in the selection", () => {+ expect(resolveSqlShortcutTemplate("SELECT * FROM ${table}", "a$&b")).toBe("SELECT * FROM a$&b");+ expect(resolveSqlShortcutTemplate("SELECT * FROM ${table}", "x$'y")).toBe("SELECT * FROM x$'y");+ expect(resolveSqlShortcutTemplate("${table} ${table}", "$`1")).toBe("$`1 $`1");+ });+});++describe("enabledSqlShortcutActions", () => {+ it("filters disabled and unbound actions", () => {+ const actions = [action("a", "Mod+1"), action("b", "", { enabled: true }), action("c", "Mod+2", { enabled: false })];+ expect(enabledSqlShortcutActions(actions).map((item) => item.id)).toEqual(["a"]);+ });+});++describe("findSqlShortcutConflicts", () => {+ it("detects duplicate custom shortcuts", () => {+ const actions = [action("a", "Mod+Shift+1"), action("b", "Mod+Shift+1")];+ expect(findSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toEqual(expect.arrayContaining(["a", "b"]));+ expect(hasSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toBe(true);+ });++ it("detects duplicate custom shortcuts with different modifier order", () => {+ const actions = [action("a", "Mod+Shift+1"), action("b", "Shift+Mod+1")];+ expect(findSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toEqual(expect.arrayContaining(["a", "b"]));+ });++ it("detects conflicts with fixed editor shortcuts", () => {+ const actions = [action("a", DEFAULT_SHORTCUT_SETTINGS.formatSql)];+ expect(findSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toEqual(["a"]);+ });++ it("ignores disabled actions", () => {+ const actions = [action("a", "Mod+Shift+1", { enabled: false }), action("b", "Mod+Shift+1")];+ expect(findSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toEqual([]);+ });+});++describe("normalizeSqlShortcuts", () => {+ it("preserves a single shortcut through normalizeEditorSettings", async () => {+ const { normalizeEditorSettings } = await import("@/stores/settingsStore");+ const source = [action("count", "Mod+Shift+C", { label: "Count rows", sql: "SELECT COUNT(*) FROM ${table}" })];+ const normalized = normalizeEditorSettings({ sqlShortcuts: source }).sqlShortcuts;+ expect(normalized).toEqual([+ {+ id: "count",+ label: "Count rows",+ shortcut: "Mod+Shift+C",+ sql: "SELECT COUNT(*) FROM ${table}",+ enabled: true,+ },+ ]);+ });++ it("keeps modifier-order variants when loading settings", async () => {+ const { normalizeEditorSettings } = await import("@/stores/settingsStore");+ const normalized = normalizeEditorSettings({+ sqlShortcuts: [action("a", "Mod+Shift+1"), action("b", "Shift+Mod+1")],+ }).sqlShortcuts;+ expect(normalized).toHaveLength(2);+ expect(normalized.map((item) => item.id)).toEqual(["a", "b"]);+ });++ it("blocks saving when canonical duplicates conflict at validation time", () => {+ const actions = [action("a", "Mod+Shift+1"), action("b", "Shift+Mod+1")];+ expect(hasSqlShortcutConflicts(actions, DEFAULT_SHORTCUT_SETTINGS)).toBe(true);+ });+});diff --git a/apps/desktop/src/lib/editor/queryEditorSqlShortcut.ts b/apps/desktop/src/lib/editor/queryEditorSqlShortcut.tsnew file mode 100644index 0000000000..395f8f5ffa--- /dev/null+++ b/apps/desktop/src/lib/editor/queryEditorSqlShortcut.ts@@ -0,0 +1,30 @@+import { matchesShortcut } from "@/lib/editor/keyboardShortcuts";+import { parseShortcutParts } from "@/lib/editor/shortcutDisplay";+import { enabledSqlShortcutActions } from "@/lib/sql/sqlShortcutActions";+import type { SqlShortcutAction } from "@/types/database";+// pi-lens-ignore: typescript:2307+import type { EditorView } from "@codemirror/view";++const LETTER_KEY_RE = /^[A-Za-z]$/;++export function isCharacterProducingShortcut(shortcut: string): boolean {+ const parts = parseShortcutParts(shortcut.trim());+ if (parts.length === 0) return false;+ const key = parts[parts.length - 1] ?? "";+ if (!LETTER_KEY_RE.test(key)) return false;+ const modifiers = new Set(parts.slice(0, -1));+ return !modifiers.has("Mod") && !modifiers.has("Meta") && !modifiers.has("Ctrl") && !modifiers.has("Alt");+}++export function createQueryEditorSqlShortcutDomHandler(getActions: () => readonly SqlShortcutAction[], runAction: (action: SqlShortcutAction, view: EditorView, event: KeyboardEvent) => boolean, platform = globalThis.navigator?.platform || ""): (event: KeyboardEvent, view: EditorView) => boolean {+ return (event, view) => {+ for (const action of enabledSqlShortcutActions(getActions())) {+ if (!isCharacterProducingShortcut(action.shortcut)) continue;+ if (!matchesShortcut(event, action.shortcut, platform)) continue;+ if (!runAction(action, view, event)) return false;+ event.preventDefault();+ return true;+ }+ return false;+ };+}diff --git a/apps/desktop/src/lib/editor/shortcutDisplay.ts b/apps/desktop/src/lib/editor/shortcutDisplay.tsindex b82c63ba5e..4deb1ef3a0 100644--- a/apps/desktop/src/lib/editor/shortcutDisplay.ts+++ b/apps/desktop/src/lib/editor/shortcutDisplay.ts@@ -48,6 +48,17 @@ export function shortcutDisplayParts(shortcut?: string, platform = globalThis.nareturn shortcutDisplayOrder(parseShortcutParts(shortcut), platform);}+export function canonicalShortcutKey(shortcut: string): string {+ return shortcutDisplayParts(shortcut, "Win32")+ .map((part) => {+ if (part === "Mod") return "Ctrl";+ if (part === "Plus") return "+";+ return part;+ })+ .join("+")+ .toLowerCase();+}+export function shortcutDisplayStrokes(shortcut?: string, platform = globalThis.navigator?.platform || ""): string[][] {return parseShortcutStrokes(shortcut).map((parts) => shortcutDisplayOrder(parts, platform));}diff --git a/apps/desktop/src/lib/settings/editorSettingsDraft.ts b/apps/desktop/src/lib/settings/editorSettingsDraft.tsindex c91ba25ce9..80da4b2e22 100644--- a/apps/desktop/src/lib/settings/editorSettingsDraft.ts+++ b/apps/desktop/src/lib/settings/editorSettingsDraft.ts@@ -89,6 +89,7 @@ export const EDITOR_SETTINGS_DRAFT_KEYS = ["updateDownloadSource","toolbarItems","snippets",+ "sqlShortcuts","sqlVariableSubstitutionEnabled","sqlVariableSyntaxOverrides","continueOnErrorOnBatch",diff --git a/apps/desktop/src/lib/settings/settingsSearch.ts b/apps/desktop/src/lib/settings/settingsSearch.tsindex 19de12fa62..0f9715ac4b 100644--- a/apps/desktop/src/lib/settings/settingsSearch.ts+++ b/apps/desktop/src/lib/settings/settingsSearch.ts@@ -215,6 +215,7 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] ={ id: "backups", category: "backups", titleKey: "databaseBackup.title", targetId: "backups", visible: desktopOnly },{ id: "tunnels", category: "tunnels", titleKey: "settings.tunnelsTab", targetId: "tunnels" },{ id: "shortcuts", category: "shortcuts", titleKey: "settings.shortcutsTab", targetId: "shortcuts" },+ { id: "sql-shortcuts", category: "shortcuts", titleKey: "settings.sqlShortcutsTitle", descriptionKey: "settings.sqlShortcutsDescription", targetId: "sql-shortcuts" },{ id: "snippets", category: "snippets", titleKey: "settings.snippetsTab", descriptionKey: "settings.snippetsDescription", targetId: "snippets" },{ id: "sync-webdav", category: "sync", titleKey: "settings.syncWebDavTitle", descriptionKey: "settings.syncWebDavDescription", targetId: "sync-webdav", route: { syncMethodTab: "webdav" } },{ id: "sync-webdav-endpoint", category: "sync", titleKey: "settings.syncEndpoint", targetId: "sync-webdav", route: { syncMethodTab: "webdav" } },diff --git a/apps/desktop/src/lib/sql/sqlShortcutActions.ts b/apps/desktop/src/lib/sql/sqlShortcutActions.tsnew file mode 100644index 0000000000..6e42c84e18--- /dev/null+++ b/apps/desktop/src/lib/sql/sqlShortcutActions.ts@@ -0,0 +1,43 @@+import { canonicalShortcutKey } from "@/lib/editor/shortcutDisplay";+import { formatShortcut, SHORTCUT_DEFINITIONS, type ShortcutSettings } from "@/lib/editor/shortcutRegistry";+import type { SqlShortcutAction } from "@/types/database";++export const SQL_SHORTCUT_TABLE_TOKEN = "${table}";++export function resolveSqlShortcutTemplate(template: string, selectedTable: string): string {+ return template.replace(/\$\{table\}/g, () => selectedTable.trim());+}++export function enabledSqlShortcutActions(actions: readonly SqlShortcutAction[]): SqlShortcutAction[] {+ return actions.filter((action) => action.enabled !== false && action.shortcut.trim().length > 0);+}++function shortcutsUseSameKeys(first: string, second: string, platform = globalThis.navigator?.platform || ""): boolean {+ if (!first || !second) return false;+ if (canonicalShortcutKey(first) === canonicalShortcutKey(second)) return true;+ return formatShortcut(first, platform).toLowerCase() === formatShortcut(second, platform).toLowerCase();+}++export function findSqlShortcutConflicts(actions: readonly SqlShortcutAction[], fixedShortcuts: ShortcutSettings, platform = globalThis.navigator?.platform || ""): string[] {+ const conflicts = new Set<string>();+ const editorFixedShortcuts = SHORTCUT_DEFINITIONS.filter((item) => item.scope === "editor" || item.scope === "global");++ for (const action of actions) {+ if (action.enabled === false || !action.shortcut.trim()) continue;++ const duplicate = actions.find((other) => other.id !== action.id && other.enabled !== false && other.shortcut.trim() && shortcutsUseSameKeys(other.shortcut, action.shortcut, platform));+ if (duplicate) {+ conflicts.add(action.id);+ conflicts.add(duplicate.id);+ }++ const fixedConflict = editorFixedShortcuts.find((item) => fixedShortcuts[item.id] && shortcutsUseSameKeys(fixedShortcuts[item.id], action.shortcut, platform));+ if (fixedConflict) conflicts.add(action.id);+ }++ return [...conflicts];+}++export function hasSqlShortcutConflicts(actions: readonly SqlShortcutAction[], fixedShortcuts: ShortcutSettings, platform = globalThis.navigator?.platform || ""): boolean {+ return findSqlShortcutConflicts(actions, fixedShortcuts, platform).length > 0;+}diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.tsindex 8a7c90d135..6f7d2970e3 100644--- a/apps/desktop/src/stores/settingsStore.ts+++ b/apps/desktop/src/stores/settingsStore.ts@@ -26,7 +26,7 @@ import { type DataTabReuseMode, DEFAULT_DATA_TAB_REUSE_MODE, normalizeDataTabReuimport { normalizeCompletionTriggerMode, type SqlCompletionTriggerMode } from "@/lib/sql/sqlCompletionTriggerPolicy";import { configureMetadataRuntimeCache, METADATA_CACHE_DEFAULT_MEMORY_MB, normalizeMetadataCacheMemoryMb } from "@/lib/metadata/metadataRuntimeCache";import type { AiApiStyle, AiAssistantMode, AiAuthMethod, AiChatSelectionState, AiConfig, AiConfigItem, AiConfiguredModel, AiEffortLevel, AiEffortSelection, AiModelEffortPreference, AiProvider, AiReasoningLevel, AiTestConnectionResult } from "@/types/ai";-import type { SqlSnippet, TableInfoTab } from "@/types/database";+import type { SqlShortcutAction, SqlSnippet, TableInfoTab } from "@/types/database";export type { AiApiStyle, AiAuthMethod, AiChatSelectionState, AiConfig, AiConfigItem, AiConfiguredModel, AiEffortLevel, AiEffortSelection, AiProvider, AiReasoningLevel, AiTestConnectionResult, DataTabReuseMode, SavedSqlOpenTargetMode, SqlCompletionTriggerMode };@@ -628,6 +628,7 @@ export interface EditorSettings {globalDateTimeExportFormat: string;globalDateTimeImportFormat: string;snippets: SqlSnippet[];+ sqlShortcuts: SqlShortcutAction[];tableColumnTemplateFields: string[];exportBatchSize: number;/** Global Redis key-search templates; overridden by non-empty connection templates. */@@ -843,6 +844,7 @@ export const DEFAULT_EDITOR_SETTINGS: EditorSettings = {globalDateTimeExportFormat: "",globalDateTimeImportFormat: "",snippets: DEFAULT_SQL_SNIPPETS,+ sqlShortcuts: [],tableColumnTemplateFields: [...DEFAULT_TABLE_COLUMN_TEMPLATE_FIELDS],exportBatchSize: 2000,redisKeyTemplates: [],@@ -1043,6 +1045,24 @@ function normalizeSqlSnippets(value: unknown, existing?: SqlSnippet[]): SqlSnippreturn valid;}+function normalizeSqlShortcuts(value: unknown, existing?: SqlShortcutAction[]): SqlShortcutAction[] {+ if (!Array.isArray(value)) return existing ?? DEFAULT_EDITOR_SETTINGS.sqlShortcuts;+ const valid: SqlShortcutAction[] = [];+ for (const item of value) {+ if (!item || typeof item !== "object" || typeof item.id !== "string" || !item.id || typeof item.label !== "string" || !item.label || typeof item.shortcut !== "string" || typeof item.sql !== "string") {+ continue;+ }+ valid.push({+ id: item.id,+ label: item.label,+ shortcut: item.shortcut.trim(),+ sql: item.sql,+ enabled: item.enabled !== false,+ });+ }+ return valid;+}+function normalizeToolbarItems(items: Partial<ToolbarItems> | undefined): ToolbarItems {const defaults = DEFAULT_TOOLBAR_ITEMS;if (!items || typeof items !== "object") return { ...defaults };@@ -1264,6 +1284,7 @@ export function normalizeEditorSettings(settings: Partial<EditorSettings>, existglobalDateTimeExportFormat: normalizeGlobalDateTimePattern(settings.globalDateTimeExportFormat),globalDateTimeImportFormat: normalizeGlobalDateTimePattern(settings.globalDateTimeImportFormat),snippets: normalizeSqlSnippets(settings.snippets, existing?.snippets),+ sqlShortcuts: normalizeSqlShortcuts(settings.sqlShortcuts, existing?.sqlShortcuts),tableColumnTemplateFields: normalizeTableColumnTemplateFields(settings.tableColumnTemplateFields),exportBatchSize: typeof settings.exportBatchSize === "number" && settings.exportBatchSize >= 100 && settings.exportBatchSize <= 100000 ? Math.round(settings.exportBatchSize) : DEFAULT_EDITOR_SETTINGS.exportBatchSize,redisKeyTemplates: normalizeRedisKeyTemplates(settings.redisKeyTemplates),@@ -1844,6 +1865,7 @@ export const useSettingsStore = defineStore("settings", () => {if (partial.globalDateTimeExportFormat !== undefined) editorSettings.value.globalDateTimeExportFormat = normalizeGlobalDateTimePattern(partial.globalDateTimeExportFormat);if (partial.globalDateTimeImportFormat !== undefined) editorSettings.value.globalDateTimeImportFormat = normalizeGlobalDateTimePattern(partial.globalDateTimeImportFormat);if (partial.snippets !== undefined) editorSettings.value.snippets = normalizeSqlSnippets(partial.snippets);+ if (partial.sqlShortcuts !== undefined) editorSettings.value.sqlShortcuts = normalizeSqlShortcuts(partial.sqlShortcuts);if (partial.tableColumnTemplateFields !== undefined) editorSettings.value.tableColumnTemplateFields = normalizeTableColumnTemplateFields(partial.tableColumnTemplateFields);if (partial.exportBatchSize !== undefined) editorSettings.value.exportBatchSize = Math.min(100000, Math.max(100, Math.round(partial.exportBatchSize)));if (partial.redisKeyTemplates !== undefined) editorSettings.value.redisKeyTemplates = normalizeRedisKeyTemplates(partial.redisKeyTemplates);diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.tsindex 8754599076..ab9035ff72 100644--- a/apps/desktop/src/types/database.ts+++ b/apps/desktop/src/types/database.ts@@ -21,6 +21,14 @@ export interface SqlSnippet {enabled?: boolean;}+export interface SqlShortcutAction {+ id: string;+ label: string;+ shortcut: string;+ sql: string;+ enabled?: boolean;+}+export type CompletionAssistantObjectKind = "database" | "schema" | "table" | "view" | "routine" | "procedure" | "function" | "column" | "sequence";export type CompletionAssistantCandidateKind = "database" | "schema" | "table" | "view" | "procedure" | "function" | "column" | "sequence" | "object";diff --git a/docs/content/docs/keyboard-shortcuts.cn.mdx b/docs/content/docs/keyboard-shortcuts.cn.mdxindex f657949a90..0bf08294d9 100644--- a/docs/content/docs/keyboard-shortcuts.cn.mdx+++ b/docs/content/docs/keyboard-shortcuts.cn.mdx@@ -75,5 +75,6 @@ Windows/Linux 上 `Ctrl+Alt` 可能被键盘布局当作 AltGr;DBX 对相关<Cards><Card title="SQL 编辑器" href="/cn/docs/query-editor">了解执行范围、多结果标签页和编辑器行为。</Card>+ <Card title="SQL 快捷操作" href="/cn/docs/sql-quick-actions">选中表名后执行自定义 SQL 模板。</Card><Card title="SQL 格式化" href="/cn/docs/sql-formatter">配置格式化规则和格式化设置编辑器快捷键。</Card></Cards>diff --git a/docs/content/docs/keyboard-shortcuts.mdx b/docs/content/docs/keyboard-shortcuts.mdxindex bb2b5a338b..c8ffc3c01f 100644--- a/docs/content/docs/keyboard-shortcuts.mdx+++ b/docs/content/docs/keyboard-shortcuts.mdx@@ -75,5 +75,6 @@ On Windows/Linux, `Ctrl+Alt` may represent AltGr, so DBX matches those combinati<Cards><Card title="Query Editor" href="/en/docs/query-editor">Review execution ranges, result tabs, and editor behavior.</Card>+ <Card title="SQL Quick Actions" href="/en/docs/sql-quick-actions">Run custom SQL templates after selecting a table name.</Card><Card title="SQL Formatter" href="/en/docs/sql-formatter">Configure formatting rules and shortcuts for the formatter settings editor.</Card></Cards>diff --git a/docs/content/docs/meta.cn.json b/docs/content/docs/meta.cn.jsonindex 6d99633c98..5c05ca420b 100644--- a/docs/content/docs/meta.cn.json+++ b/docs/content/docs/meta.cn.json@@ -26,6 +26,7 @@"database-export","database-backup","sql-snippets",+ "sql-quick-actions","---AI 与自动化---","ai-assistant","cli",diff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.jsonindex b9c841ce1e..f5aeb52e15 100644--- a/docs/content/docs/meta.json+++ b/docs/content/docs/meta.json@@ -26,6 +26,7 @@"database-export","database-backup","sql-snippets",+ "sql-quick-actions","---AI & Automation---","ai-assistant","cli",diff --git a/docs/content/docs/sql-quick-actions.cn.mdx b/docs/content/docs/sql-quick-actions.cn.mdxnew file mode 100644index 0000000000..1d180c2fe0--- /dev/null+++ b/docs/content/docs/sql-quick-actions.cn.mdx@@ -0,0 +1,72 @@+---+title: SQL 快捷操作+description: 在查询编辑器中选中表名后,通过快捷键执行自定义 SQL 模板。+---++SQL 快捷操作允许你在查询编辑器中先选中表名(或限定标识符),再按快捷键执行可复用的 SQL 模板。++这与 [SQL 代码片段](/cn/docs/sql-snippets) 不同:代码片段通过补全把模板插入到光标处;快捷操作会根据当前选区生成 SQL,并走正常的执行流程。++## 管理快捷操作++打开 **设置 → 快捷键**,找到 **SQL 快捷操作** 区域。每条操作包含:++| 字段 | 作用 |+| --- | --- |+| 显示名 | 设置列表中显示的名称。 |+| 快捷键 | 触发该操作的按键组合。 |+| 状态 | 临时启用或停用,不需要删除模板。 |+| SQL 模板 | 执行前会把 `${table}` 替换为选中内容的 SQL。 |++你可以新增、编辑、启用、停用或删除操作。在编辑对话框中保存后会立即生效;也可以在设置窗口点击 **应用** 统一保存。++<Callout type="info">+ 建议使用包含 `Mod`(macOS 为 `Cmd`,Windows/Linux 为 `Ctrl`)的组合键,比单独使用 `Shift+字母` 更少干扰正常输入。+</Callout>++## 执行快捷操作++1. 在 SQL 编辑器中选中表名或限定标识符,例如 `orders` 或 `public.users`。+2. 按下已配置的快捷键。+3. DBX 会把模板中所有 `${table}` 替换为去除首尾空白后的选区文本,并执行展开后的 SQL。++示例模板:++```sql+SELECT COUNT(*) FROM ${table}+```++选中 `orders` 后,DBX 会执行:++```sql+SELECT COUNT(*) FROM orders+```++如果没有选中任何内容,快捷键不会触发,编辑器会保持正常输入行为。++## 快捷键冲突++DBX 会检查快捷操作是否与以下快捷键冲突:++- 列表中的其他快捷操作+- **设置 → 快捷键** 中的内置编辑器和全局快捷键++存在冲突时,设置界面会标红,并且在解决冲突前无法 **应用** 设置。++## 保存、同步与安全++快捷操作属于编辑器设置,保存在当前 DBX 运行环境中。桌面版的[配置云同步](/cn/docs/cloud-sync)可以连同其他编辑器设置一起同步;[连接配置迁移](/cn/docs/config-export)只处理数据库连接,不包含快捷操作。++快捷操作只是生成 SQL,不会绕过数据库权限或 DBX 的生产保护。执行包含写入或 DDL 的模板前,仍应检查展开后的完整 SQL,并遵循[生产安全](/cn/docs/production-safety)建议。++<Cards>+ <Card title="SQL 代码片段" href="/cn/docs/sql-snippets">+ 通过编辑器补全在光标处插入可复用模板。+ </Card>+ <Card title="快捷键" href="/cn/docs/keyboard-shortcuts">+ 查看内置编辑器快捷键与冲突规则。+ </Card>+ <Card title="查询编辑器" href="/cn/docs/query-editor">+ 了解执行范围、结果标签页和选区行为。+ </Card>+</Cards>diff --git a/docs/content/docs/sql-quick-actions.mdx b/docs/content/docs/sql-quick-actions.mdxnew file mode 100644index 0000000000..cd4b3d1141--- /dev/null+++ b/docs/content/docs/sql-quick-actions.mdx@@ -0,0 +1,72 @@+---+title: SQL Quick Actions+description: Run custom SQL templates from the editor after selecting a table name and pressing a shortcut.+---++SQL Quick Actions let you run reusable SQL templates against the text you have selected in the query editor. Select a table identifier first, then press the shortcut you configured in **Settings → Shortcuts**.++This is different from [SQL Snippets](/en/docs/sql-snippets), which insert templates at the cursor through completion. Quick Actions generate SQL from the current selection and send it through the normal execution path.++## Manage Quick Actions++Open **Settings → Shortcuts** and scroll to **SQL Quick Actions**. Each action contains:++| Field | Purpose |+| --- | --- |+| Label | Name shown in the settings list. |+| Shortcut | Key combination that runs the action. |+| Status | Enables or disables the action without deleting it. |+| SQL Template | SQL executed after `${table}` is replaced with the selected text. |++You can add, edit, enable, disable, or delete actions. Changes are saved immediately from the action dialog, or when you click **Apply** in the settings window.++<Callout type="info">+ Shortcuts that include `Mod` (`Cmd` on macOS, `Ctrl` on Windows/Linux) are recommended. They are less likely to interfere with normal typing than bare letter keys such as `Shift+U`.+</Callout>++## Run a Quick Action++1. Select a table name or qualified identifier in the SQL editor, for example `orders` or `public.users`.+2. Press the configured shortcut.+3. DBX replaces every `${table}` token with the trimmed selection and executes the expanded SQL.++Example template:++```sql+SELECT COUNT(*) FROM ${table}+```++With `orders` selected, DBX runs:++```sql+SELECT COUNT(*) FROM orders+```++If nothing is selected, the shortcut does not run and normal editor input continues.++## Shortcut Conflicts++DBX checks Quick Action shortcuts against:++- Other Quick Actions in your list+- Built-in editor and global shortcuts shown in **Settings → Shortcuts**++Conflicting bindings are highlighted and block **Apply** until you resolve them.++## Storage, Sync, and Safety++Quick Actions are editor settings stored in the current DBX runtime. On Desktop, [Configuration Cloud Sync](/en/docs/cloud-sync) can synchronize them with your other editor settings. [Connection Config Migration](/en/docs/config-export) only moves database connections and does not include Quick Actions.++A Quick Action only generates SQL; it does not bypass database permissions or DBX production protection. Review the fully expanded statement before running templates that contain writes or DDL, and follow the [Production Safety](/en/docs/production-safety) guidance.++<Cards>+ <Card title="SQL Snippets" href="/en/docs/sql-snippets">+ Insert reusable templates at the cursor through editor completion.+ </Card>+ <Card title="Keyboard Shortcuts" href="/en/docs/keyboard-shortcuts">+ Review built-in editor shortcuts and conflict rules.+ </Card>+ <Card title="Query Editor" href="/en/docs/query-editor">+ Learn how execution scope, result tabs, and selection work together.+ </Card>+</Cards>