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: support customizable SQL snippet templates with custom trigger keys

t8y2610777835858
diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
index 3b79ffc05f..d7710fdb87 100644
--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue
+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
@@ -2,7 +2,7 @@
import { ref, watch, shallowRef, computed } from "vue";
import type { EditorView as EditorViewType } from "@codemirror/view";
import { useI18n } from "vue-i18n";
-import { CircleHelp, ExternalLink, Loader2, RefreshCw, Settings } from "lucide-vue-next";
+import { CircleHelp, ExternalLink, Loader2, Pencil, RefreshCw, Settings, Trash2 } from "lucide-vue-next";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
@@ -37,6 +37,9 @@ import {
type ShortcutActionId,
} from "@/lib/shortcutRegistry";
import { normalizeSidebarHiddenTablePrefixes } from "@/lib/sidebarTableNameDisplay";
+import type { SqlSnippet } from "@/types/database";
+import { uuid } from "@/lib/utils";
+import { DEFAULT_SQL_SNIPPETS } from "@/lib/sqlCompletion";
import AiProviderLogo from "@/components/icons/AiProviderLogo.vue";
import type { AppThemeAppearance } from "@/lib/appTheme";
@@ -72,6 +75,78 @@ const systemFonts = ref<string[]>([]);
const systemFontsLoading = ref(false);
const systemFontsLoaded = ref(false);
+// --- Snippet state ---
+const editSnippets = ref<SqlSnippet[]>(
+ settingsStore.editorSettings.snippets.map((s) => ({ ...s })),
+);
+
+const snippetDialogOpen = ref(false);
+const snippetEditingId = ref<string | null>(null);
+const snippetForm = ref({ label: "", prefix: "", body: "" });
+const snippetFormPrefixError = ref("");
+
+function openAddSnippetDialog() {
+ snippetEditingId.value = null;
+ snippetForm.value = { label: "", prefix: "", body: "" };
+ snippetFormPrefixError.value = "";
+ snippetDialogOpen.value = true;
+}
+
+function openEditSnippetDialog(snippet: SqlSnippet) {
+ snippetEditingId.value = snippet.id;
+ snippetForm.value = { label: snippet.label, prefix: snippet.prefix, body: snippet.body };
+ snippetFormPrefixError.value = "";
+ snippetDialogOpen.value = true;
+}
+
+function saveSnippet() {
+ const prefix = snippetForm.value.prefix.trim();
+ if (!prefix) {
+ snippetFormPrefixError.value = "Prefix is required.";
+ return;
+ }
+ const duplicate = editSnippets.value.find(
+ (s) => s.prefix === prefix && s.id !== snippetEditingId.value,
+ );
+ if (duplicate) {
+ snippetFormPrefixError.value = "Prefix must be unique.";
+ return;
+ }
+ if (snippetEditingId.value) {
+ const idx = editSnippets.value.findIndex((s) => s.id === snippetEditingId.value);
+ if (idx !== -1) {
+ editSnippets.value[idx] = {
+ id: snippetEditingId.value,
+ label: snippetForm.value.label.trim() || prefix,
+ prefix,
+ body: snippetForm.value.body,
+ };
+ }
+ } else {
+ editSnippets.value.push({
+ id: uuid(),
+ label: snippetForm.value.label.trim() || prefix,
+ prefix,
+ body: snippetForm.value.body,
+ });
+ }
+ snippetDialogOpen.value = false;
+}
+
+function deleteSnippet(id: string) {
+ editSnippets.value = editSnippets.value.filter((s) => s.id !== id);
+}
+
+function confirmDeleteSnippet(snippet: SqlSnippet) {
+ if (window.confirm(`Delete snippet "${snippet.label}"?`)) {
+ deleteSnippet(snippet.id);
+ }
+}
+
+function restoreDefaultSnippets() {
+ editSnippets.value = DEFAULT_SQL_SNIPPETS.map((s) => ({ ...s }));
+}
+
const presetFontLabels = new Map(FONT_FAMILIES.map((font) => [font.value, font.label]));
function cssFontFamilyForName(name: string): string {
@@ -131,11 +206,20 @@ watch(
editSidebarActivation.value = settingsStore.editorSettings.sidebarActivation;
editAutoSelectActiveSidebarNode.value = settingsStore.editorSettings.autoSelectActiveSidebarNode;
editSidebarHiddenTablePrefixes.value = settingsStore.editorSettings.sidebarHiddenTablePrefixes.join("\n");
+ editSnippets.value = settingsStore.editorSettings.snippets.map((s) => ({ ...s }));
void loadSystemFontOptions();
}
},
);
+watch(
+ () => settingsStore.editorSettings.snippets,
+ (snippets) => {
+ editSnippets.value = snippets.map((s) => ({ ...s }));
+ },
+ { deep: true },
+);
+
const shortcutConflicts = computed(() =>
SHORTCUT_DEFINITIONS.flatMap((definition) => {
const conflict = findShortcutConflict(definition.id, editShortcuts.value[definition.id], editShortcuts.value);
@@ -162,7 +246,8 @@ function hasChanges(): boolean {
editSidebarActivation.value !== settingsStore.editorSettings.sidebarActivation ||
editAutoSelectActiveSidebarNode.value !== settingsStore.editorSettings.autoSelectActiveSidebarNode ||
JSON.stringify(normalizeSidebarHiddenTablePrefixes(editSidebarHiddenTablePrefixes.value)) !==
- JSON.stringify(settingsStore.editorSettings.sidebarHiddenTablePrefixes)
+ JSON.stringify(settingsStore.editorSettings.sidebarHiddenTablePrefixes) ||
+ JSON.stringify(editSnippets.value) !== JSON.stringify(settingsStore.editorSettings.snippets)
);
}
@@ -180,6 +265,7 @@ async function applySettings() {
sidebarActivation: editSidebarActivation.value,
autoSelectActiveSidebarNode: editAutoSelectActiveSidebarNode.value,
sidebarHiddenTablePrefixes: normalizeSidebarHiddenTablePrefixes(editSidebarHiddenTablePrefixes.value),
+ snippets: editSnippets.value,
});
await settingsStore.updateDesktopSettings({
show_tray_icon: editShowTrayIcon.value,
@@ -200,6 +286,7 @@ function resetDefaults() {
editSidebarActivation.value = DEFAULT_EDITOR_SETTINGS.sidebarActivation;
editAutoSelectActiveSidebarNode.value = DEFAULT_EDITOR_SETTINGS.autoSelectActiveSidebarNode;
editSidebarHiddenTablePrefixes.value = DEFAULT_EDITOR_SETTINGS.sidebarHiddenTablePrefixes.join("\n");
+ editSnippets.value = DEFAULT_SQL_SNIPPETS.map((s) => ({ ...s }));
}
function onExecuteModeChange(v: any) {
@@ -251,13 +338,14 @@ function setSidebarActivation(value: "single" | "double") {
const activeSettingsTab = ref("editor");
const isWeb = !isTauriRuntime();
const displayedAppVersion = computed(() => (props.appVersion ? `v${props.appVersion}` : ""));
-type SettingsCategory = "editor" | "appearance" | "navigation" | "redis" | "shortcuts" | "ai" | "security" | "about";
+type SettingsCategory = "editor" | "appearance" | "navigation" | "redis" | "shortcuts" | "snippets" | "ai" | "security" | "about";
const settingsCategoryNav = computed<{ value: SettingsCategory; label: string }[]>(() => [
{ value: "editor", label: t("settings.editorTab") },
{ value: "appearance", label: t("settings.appearanceTab") },
{ value: "navigation", label: t("settings.navigationTab") },
{ value: "redis", label: t("settings.redisTab") },
{ value: "shortcuts", label: t("settings.shortcutsTab") },
+ { value: "snippets", label: t("settings.snippetsTab") },
{ value: "ai", label: t("settings.aiTab") },
...(isWeb ? [{ value: "security" as const, label: t("settings.securityTab") }] : []),
{ value: "about", label: t("settings.aboutTab") },
@@ -268,6 +356,7 @@ const settingsTabsWithApplyFooter = new Set<SettingsCategory>([
"navigation",
"redis",
"shortcuts",
+ "snippets",
]);
function hasSettingsApplyFooter(value: SettingsCategory): boolean {
@@ -966,6 +1055,59 @@ watch(
</div>
</div>
</section>
+
+ <!-- Snippets Tab -->
+ <section v-else-if="activeSettingsTab === 'snippets'" class="flex flex-col gap-4 py-2">
+ <div class="flex items-center justify-between">
+ <p class="text-sm text-muted-foreground">{{ t('settings.snippetsDescription') }}</p>
+ <Button variant="outline" size="sm" @click="openAddSnippetDialog">
+ {{ t('settings.snippetsAdd') }}
+ </Button>
+ </div>
+
+ <div class="rounded-md border">
+ <table class="w-full text-sm">
+ <thead>
+ <tr class="border-b bg-muted/50">
+ <th class="px-3 py-2 text-left font-medium">{{ t('settings.snippetsLabel') }}</th>
+ <th class="px-3 py-2 text-left font-medium">{{ t('settings.snippetsPrefix') }}</th>
+ <th class="px-3 py-2 text-left font-medium">{{ t('settings.snippetsBody') }}</th>
+ <th class="px-3 py-2 w-20"></th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr
+ v-for="snippet in editSnippets"
+ :key="snippet.id"
+ class="border-b last:border-b-0 hover:bg-muted/30"
+ >
+ <td class="px-3 py-2">{{ snippet.label }}</td>
+ <td class="px-3 py-2 font-mono text-xs">{{ snippet.prefix }}</td>
+ <td class="px-3 py-2 font-mono text-xs text-muted-foreground max-w-[300px] truncate">
+ {{ snippet.body }}
+ </td>
+ <td class="px-3 py-2">
+ <div class="flex items-center gap-1">
+ <Button variant="ghost" size="icon-xs" @click="openEditSnippetDialog(snippet)">
+ <Pencil class="size-3.5" />
+ </Button>
+ <Button variant="ghost" size="icon-xs" @click="confirmDeleteSnippet(snippet)">
+ <Trash2 class="size-3.5" />
+ </Button>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ <div class="flex justify-end">
+ <Button variant="outline" size="sm" @click="restoreDefaultSnippets">
+ {{ t('settings.snippetsRestoreDefaults') }}
+ </Button>
+ </div>
+ </section>
+
<!-- AI Settings Tab -->
<section v-else-if="activeSettingsTab === 'ai'" class="flex flex-col gap-5 py-2">
<p class="text-xs text-muted-foreground">{{ t("ai.settingsHint") }}</p>
@@ -1348,5 +1490,41 @@ watch(
</div>
</div>
</DialogContent>
+
+ <!-- Snippet Add/Edit Dialog -->
+ <Dialog :open="snippetDialogOpen" @update:open="snippetDialogOpen = $event">
+ <DialogContent class="sm:max-w-[500px]">
+ <DialogHeader>
+ <DialogTitle>
+ {{ snippetEditingId ? t('settings.snippetsEditTitle') : t('settings.snippetsAddTitle') }}
+ </DialogTitle>
+ </DialogHeader>
+ <div class="flex flex-col gap-4 py-2">
+ <div class="flex flex-col gap-1.5">
+ <Label for="snippet-label">{{ t('settings.snippetsLabel') }}</Label>
+ <Input id="snippet-label" v-model="snippetForm.label" :placeholder="t('settings.snippetsLabelPlaceholder')" />
+ </div>
+ <div class="flex flex-col gap-1.5">
+ <Label for="snippet-prefix">{{ t('settings.snippetsPrefix') }}</Label>
+ <Input id="snippet-prefix" v-model="snippetForm.prefix" :placeholder="t('settings.snippetsPrefixPlaceholder')" />
+ <p v-if="snippetFormPrefixError" class="text-xs text-destructive">{{ snippetFormPrefixError }}</p>
+ </div>
+ <div class="flex flex-col gap-1.5">
+ <Label for="snippet-body">{{ t('settings.snippetsBody') }}</Label>
+ <textarea
+ id="snippet-body"
+ v-model="snippetForm.body"
+ :placeholder="t('settings.snippetsBodyPlaceholder')"
+ 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"
+ />
+ </div>
+ </div>
+ <DialogFooter>
+ <Button variant="outline" @click="snippetDialogOpen = false">{{ t('settings.cancel') }}</Button>
+ <Button @click="saveSnippet">{{ t('settings.save') }}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
</Dialog>
</template>
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue
index 358d216222..bc4b16f907 100644
--- a/apps/desktop/src/components/editor/QueryEditor.vue
+++ b/apps/desktop/src/components/editor/QueryEditor.vue
@@ -855,6 +855,7 @@ async function provideSqlCompletions(
columnsByTable,
schemas: schemaNames,
translations: completionTranslations.value,
+ snippets: settingsStore.editorSettings.snippets,
});
if (items.length === 0) return null;
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 92b9c6f099..a6158759e6 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -1273,6 +1273,7 @@ export default {
navigationTab: "Navigation",
redisTab: "Redis",
shortcutsTab: "Shortcuts",
+ snippetsTab: "Snippets",
aiTab: "AI",
jdbcTab: "JDBC Drivers",
securityTab: "Security",
@@ -1307,9 +1308,22 @@ export default {
sidebarHiddenTablePrefixesDescription:
"One prefix per line. Only sidebar table, view, and collection labels are shortened; tooltips and actions still use the full name.",
sidebarHiddenTablePrefixesPlaceholder: "Example:\nODS_\nT8Y2_LONG_",
+ snippetsDescription: "Customize SQL snippet templates triggered in the editor.",
+ snippetsAdd: "Add Snippet",
+ snippetsLabel: "Label",
+ snippetsPrefix: "Prefix",
+ snippetsBody: "SQL Body",
+ snippetsLabelPlaceholder: "e.g. select *",
+ snippetsPrefixPlaceholder: "e.g. sel",
+ snippetsBodyPlaceholder: "SELECT *\nFROM table\nLIMIT 100;",
+ snippetsRestoreDefaults: "Restore Defaults",
+ snippetsAddTitle: "Add Snippet",
+ snippetsEditTitle: "Edit Snippet",
apply: "Apply",
reset: "Reset",
resetDefaults: "Reset Defaults",
+ save: "Save",
+ cancel: "Cancel",
executeMode: "Execute Mode (Cmd+Enter)",
executeModeAll: "Execute all SQL",
executeModeCurrent: "Execute statement at cursor",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 219f048377..44ab37b60f 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -1250,6 +1250,7 @@ export default {
navigationTab: "导航",
redisTab: "Redis",
shortcutsTab: "快捷键",
+ snippetsTab: "代码片段",
aiTab: "AI",
jdbcTab: "JDBC 驱动",
securityTab: "安全",
@@ -1282,9 +1283,22 @@ export default {
sidebarHiddenTablePrefixesDescription:
"每行一个前缀,仅影响侧边栏表、视图和集合的显示名称,悬浮提示和实际操作仍使用完整名称。",
sidebarHiddenTablePrefixesPlaceholder: "例如:\nODS_\nT8Y2_LONG_",
+ snippetsDescription: "自定义编辑器中触发的 SQL 代码片段模板。",
+ snippetsAdd: "添加片段",
+ snippetsLabel: "显示名",
+ snippetsPrefix: "触发键",
+ snippetsBody: "SQL 内容",
+ snippetsLabelPlaceholder: "如:select *",
+ snippetsPrefixPlaceholder: "如:sel",
+ snippetsBodyPlaceholder: "SELECT *\nFROM table\nLIMIT 100;",
+ snippetsRestoreDefaults: "恢复默认",
+ snippetsAddTitle: "添加片段",
+ snippetsEditTitle: "编辑片段",
apply: "应用",
reset: "重置",
resetDefaults: "恢复默认",
+ save: "保存",
+ cancel: "取消",
executeMode: "执行模式 (Cmd+Enter)",
executeModeAll: "执行全部 SQL",
executeModeCurrent: "执行光标所在语句",
diff --git a/apps/desktop/src/lib/__tests__/sqlCompletion.snippet.spec.ts b/apps/desktop/src/lib/__tests__/sqlCompletion.snippet.spec.ts
new file mode 100644
index 0000000000..1e0a53cfa3
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/sqlCompletion.snippet.spec.ts
@@ -0,0 +1,33 @@
+import { describe, it, expect } from "vitest";
+import { buildSnippetItemsForTest } from "@/lib/sqlCompletion";
+import type { SqlSnippet } from "@/types/database";
+
+const TEST_SNIPPETS: SqlSnippet[] = [
+ { id: "1", label: "select all", prefix: "sel", body: "SELECT *\nFROM my_table;" },
+ { id: "2", label: "insert row", prefix: "ins", body: "INSERT INTO my_table VALUES (1);" },
+];
+
+describe("buildSnippetItems", () => {
+ it("returns matching snippet by prefix", () => {
+ const items = buildSnippetItemsForTest("sel", TEST_SNIPPETS);
+ expect(items).toHaveLength(1);
+ expect(items[0].label).toBe("select all");
+ expect(items[0].apply).toBe("SELECT *\nFROM my_table;");
+ });
+
+ it("returns matching snippet by label substring", () => {
+ const items = buildSnippetItemsForTest("select", TEST_SNIPPETS);
+ expect(items).toHaveLength(1);
+ expect(items[0].label).toBe("select all");
+ });
+
+ it("returns empty for no match", () => {
+ const items = buildSnippetItemsForTest("zzz", TEST_SNIPPETS);
+ expect(items).toEqual([]);
+ });
+
+ it("returns empty for empty prefix", () => {
+ const items = buildSnippetItemsForTest("", TEST_SNIPPETS);
+ expect(items).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/lib/sqlCompletion.ts b/apps/desktop/src/lib/sqlCompletion.ts
index 1ac1869667..9f98048e78 100644
--- a/apps/desktop/src/lib/sqlCompletion.ts
+++ b/apps/desktop/src/lib/sqlCompletion.ts
@@ -1,3 +1,5 @@
+import type { SqlSnippet } from "@/types/database";
+
const SQL_KEYWORDS = [
"SELECT",
"FROM",
@@ -381,72 +383,72 @@ function getFunctionDescriptions(t?: SqlCompletionTranslations): Map<string, str
]);
}
-const SQL_SNIPPETS: Array<{ label: string; prefix: string; apply: string; detail: string }> = [
+export const DEFAULT_SQL_SNIPPETS: SqlSnippet[] = [
{
+ id: "builtin-sel",
label: "select *",
prefix: "sel",
- apply: "SELECT *\nFROM ${table}\nLIMIT 100;",
- detail: "SELECT template",
+ body: "SELECT *\nFROM table\nLIMIT 100;",
},
{
+ id: "builtin-ins",
label: "insert into",
prefix: "ins",
- apply: "INSERT INTO ${table} (${columns})\nVALUES (${values});",
- detail: "INSERT template",
+ body: "INSERT INTO table (columns)\nVALUES (values);",
},
{
+ id: "builtin-upd",
label: "update set",
prefix: "upd",
- apply: "UPDATE ${table}\nSET ${column} = ${value}\nWHERE ${condition};",
- detail: "UPDATE template",
+ body: "UPDATE table\nSET column = value\nWHERE condition;",
},
{
+ id: "builtin-cte",
label: "common table expression",
prefix: "cte",
- apply: "WITH ${name} AS (\n SELECT ${columns}\n FROM ${table}\n)\nSELECT *\nFROM ${name};",
- detail: "CTE template",
+ body: "WITH name AS (\n SELECT columns\n FROM table\n)\nSELECT *\nFROM name;",
},
{
+ id: "builtin-join",
label: "join",
prefix: "join",
- apply: "JOIN ${table} ON ${left_column} = ${right_column}",
- detail: "JOIN template",
+ body: "JOIN table ON left_column = right_column",
},
{
+ id: "builtin-case",
label: "case when",
prefix: "case",
- apply: "CASE\n WHEN ${condition} THEN ${value}\n ELSE ${default}\nEND",
- detail: "CASE expression",
+ body: "CASE\n WHEN condition THEN value\n ELSE default\nEND",
},
{
+ id: "builtin-ct",
label: "create table",
prefix: "ct",
- apply: "CREATE TABLE ${table} (\n ${column} ${type}\n);",
- detail: "CREATE TABLE template",
+ body: "CREATE TABLE table (\n column type\n);",
},
{
+ id: "builtin-ex",
label: "exists",
prefix: "ex",
- apply: "EXISTS (\n SELECT 1\n FROM ${table}\n WHERE ${condition}\n)",
- detail: "EXISTS subquery",
+ body: "EXISTS (\n SELECT 1\n FROM table\n WHERE condition\n)",
},
{
+ id: "builtin-nex",
label: "not exists",
prefix: "nex",
- apply: "NOT EXISTS (\n SELECT 1\n FROM ${table}\n WHERE ${condition}\n)",
- detail: "NOT EXISTS subquery",
+ body: "NOT EXISTS (\n SELECT 1\n FROM table\n WHERE condition\n)",
},
{
+ id: "builtin-at",
label: "alter table add column",
prefix: "at",
- apply: "ALTER TABLE ${table}\nADD COLUMN ${column} ${type};",
- detail: "ALTER TABLE template",
+ body: "ALTER TABLE table\nADD COLUMN column type;",
},
{
+ id: "builtin-ci",
label: "create index",
prefix: "ci",
- apply: "CREATE INDEX ${idx_name}\nON ${table} (${column});",
- detail: "CREATE INDEX template",
+ body: "CREATE INDEX idx_name\nON table (column);",
},
];
@@ -639,13 +641,14 @@ export function buildSqlCompletionItemsFromContext(
columnsByTable: Map<string, SqlCompletionColumn[]>;
schemas?: string[];
translations?: SqlCompletionTranslations;
+ snippets?: SqlSnippet[];
},
): SqlCompletionItem[] {
const items: SqlCompletionItem[] = [];
const t = input.translations;
if (!context.exclusiveTableSuggestions && !context.exclusiveColumnSuggestions) {
- items.push(...buildSnippetItems(context.prefix));
+ items.push(...buildSnippetItems(context.prefix, input.snippets ?? DEFAULT_SQL_SNIPPETS));
items.push(...buildFunctionSnippetItems(context.prefix, getFunctionDescriptions(t)));
}
@@ -1879,21 +1882,27 @@ function singularTableName(name: string): string {
return lower;
}
-function buildSnippetItems(prefix: string): SqlCompletionItem[] {
+export function buildSnippetItemsForTest(prefix: string, snippets: SqlSnippet[]): SqlCompletionItem[] {
+ return buildSnippetItems(prefix, snippets);
+}
+
+function buildSnippetItems(prefix: string, snippets: SqlSnippet[]): SqlCompletionItem[] {
if (!prefix) return [];
- return SQL_SNIPPETS.filter(
- (snippet) => matchesPrefix(snippet.prefix, prefix) || matchesPrefix(snippet.label, prefix),
- ).map((snippet) => {
- const boostByPrefix = computeBoost(snippet.prefix, prefix);
- const boostByLabel = computeBoost(snippet.label, prefix);
- return {
- label: snippet.label,
- type: "snippet" as const,
- detail: snippet.detail,
- apply: snippet.apply,
- boost: Math.max(boostByPrefix, boostByLabel) - 1100,
- };
- });
+ return snippets
+ .filter(
+ (snippet) => matchesPrefix(snippet.prefix, prefix) || matchesPrefix(snippet.label, prefix),
+ )
+ .map((snippet) => {
+ const boostByPrefix = computeBoost(snippet.prefix, prefix);
+ const boostByLabel = computeBoost(snippet.label, prefix);
+ return {
+ label: snippet.label,
+ type: "snippet" as const,
+ detail: snippet.label,
+ apply: snippet.body,
+ boost: Math.max(boostByPrefix, boostByLabel) - 1100,
+ };
+ });
}
function buildFunctionSnippetItems(prefix: string, functionDescriptions: Map<string, string>): SqlCompletionItem[] {
diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.ts
index 22d5a52520..e76c1becfa 100644
--- a/apps/desktop/src/stores/settingsStore.ts
+++ b/apps/desktop/src/stores/settingsStore.ts
@@ -11,6 +11,8 @@ import { normalizeShortcutSettings, type ShortcutSettings } from "@/lib/shortcut
import { normalizeResultPageSize } from "@/lib/paginationPageSize";
import { normalizeSidebarHiddenTablePrefixes } from "@/lib/sidebarTableNameDisplay";
import type { SidebarActivation } from "@/lib/treeNodeClick";
+import type { SqlSnippet } from "@/types/database";
+import { DEFAULT_SQL_SNIPPETS } from "@/lib/sqlCompletion";
export type AiProvider =
| "claude"
@@ -184,6 +186,7 @@ export interface EditorSettings {
sidebarHiddenTablePrefixes: string[];
columnFormatters: Record<string, ColumnFormatterConfig>;
customColumnFormatters: Record<string, CustomColumnFormatterConfig>;
+ snippets: SqlSnippet[];
}
export const EDITOR_THEMES: { value: EditorTheme; label: string; dark: boolean }[] = [
@@ -228,6 +231,7 @@ export const DEFAULT_EDITOR_SETTINGS: EditorSettings = {
sidebarHiddenTablePrefixes: [],
columnFormatters: {},
customColumnFormatters: {},
+ snippets: DEFAULT_SQL_SNIPPETS,
};
export const STORAGE_KEY = "dbx-editor-settings";
@@ -253,7 +257,30 @@ function normalizeCustomColumnFormatters(value: unknown): Record<string, CustomC
return formatters;
}
-export function normalizeEditorSettings(settings: Partial<EditorSettings>): EditorSettings {
+function normalizeSqlSnippets(value: unknown, existing?: SqlSnippet[]): SqlSnippet[] {
+ if (!Array.isArray(value)) return existing ?? DEFAULT_SQL_SNIPPETS;
+ const valid: SqlSnippet[] = [];
+ const seenPrefixes = new Set<string>();
+ for (const item of value) {
+ if (
+ !item ||
+ typeof item !== "object" ||
+ typeof item.id !== "string" || !item.id ||
+ typeof item.label !== "string" || !item.label ||
+ typeof item.prefix !== "string" || !item.prefix ||
+ typeof item.body !== "string"
+ ) {
+ continue;
+ }
+ if (seenPrefixes.has(item.prefix)) continue;
+ seenPrefixes.add(item.prefix);
+ valid.push({ id: item.id, label: item.label, prefix: item.prefix, body: item.body });
+ }
+ if (valid.length === 0) return existing ?? DEFAULT_SQL_SNIPPETS;
+ return valid;
+}
+
+export function normalizeEditorSettings(settings: Partial<EditorSettings>, existing?: EditorSettings): EditorSettings {
return {
fontFamily: settings.fontFamily ?? DEFAULT_EDITOR_SETTINGS.fontFamily,
fontSize: settings.fontSize ?? DEFAULT_EDITOR_SETTINGS.fontSize,
@@ -275,6 +302,7 @@ export function normalizeEditorSettings(settings: Partial<EditorSettings>): Edit
sidebarHiddenTablePrefixes: normalizeSidebarHiddenTablePrefixes(settings.sidebarHiddenTablePrefixes),
columnFormatters: normalizeColumnFormatters(settings.columnFormatters),
customColumnFormatters: normalizeCustomColumnFormatters(settings.customColumnFormatters),
+ snippets: normalizeSqlSnippets(settings.snippets, existing?.snippets),
};
}
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index cf61109a36..5112bdeb36 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -43,6 +43,13 @@ export type DatabaseType =
| "tdengine"
| "jdbc";
+export interface SqlSnippet {
+ id: string;
+ label: string;
+ prefix: string;
+ body: string;
+}
+
export interface ConnectionConfig {
id: string;
name: string;