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。

Add configurable SQL formatter settings (#908)

SuLea-IT5138c1a702c0
diff --git a/.gitignore b/.gitignore
index fbbcce3cb2..a11181a738 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,6 +4,7 @@ node_modules/
.codex/
.superpowers/
.trellis/
+.worktrees/
openspec/
.mcp.json
AGENTS.md
diff --git a/apps/desktop/src/components/editor/EditorSettingsDialog.vue b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
index bafdb2659d..283a1b0306 100644
--- a/apps/desktop/src/components/editor/EditorSettingsDialog.vue
+++ b/apps/desktop/src/components/editor/EditorSettingsDialog.vue
@@ -77,11 +77,13 @@ import {
type ShortcutActionId,
} from "@/lib/shortcutRegistry";
import { normalizeSidebarHiddenTablePrefixes } from "@/lib/sidebarTableNameDisplay";
+import { normalizeSqlFormatterSettings, type SqlFormatterSettings } from "@/lib/sqlFormatterConfig";
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 AppLogo from "@/components/icons/AppLogo.vue";
+import SqlFormatterSettingsPanel from "./SqlFormatterSettingsPanel.vue";
import type { AppThemeAppearance } from "@/lib/appTheme";
import { useConnectionStore } from "@/stores/connectionStore";
import { currentLocale, setLocale, type Locale } from "@/i18n";
@@ -124,6 +126,10 @@ const editShowColumnTypesInHeader = ref(settingsStore.editorSettings.showColumnT
const editCompactColumnHeaderActions = ref(settingsStore.editorSettings.compactColumnHeaderActions);
const editRedisScanPageSize = ref(settingsStore.editorSettings.redisScanPageSize);
const editShortcuts = ref(normalizeShortcutSettings(settingsStore.editorSettings.shortcuts));
+const editSqlFormatter = ref<SqlFormatterSettings>(
+ normalizeSqlFormatterSettings(settingsStore.editorSettings.sqlFormatter),
+);
+const sqlFormatterConfigValid = ref(true);
const editingShortcutId = ref<ShortcutActionId | null>(null);
const editSidebarActivation = ref(settingsStore.editorSettings.sidebarActivation);
const editSidebarObjectDisplay = ref(settingsStore.editorSettings.sidebarObjectDisplay);
@@ -152,6 +158,8 @@ const disconnectTabHandlingModeDescriptionKey = computed(() => {
case "keep-tabs-keep-results":
return "disconnectTabHandlingModeKeepTabsKeepResultsDescription";
}
+
+ return "disconnectTabHandlingModeCloseTabsDescription";
});
// --- Snippet state ---
@@ -283,6 +291,8 @@ watch(
editCompactColumnHeaderActions.value = settingsStore.editorSettings.compactColumnHeaderActions;
editRedisScanPageSize.value = settingsStore.editorSettings.redisScanPageSize;
editShortcuts.value = normalizeShortcutSettings(settingsStore.editorSettings.shortcuts);
+ editSqlFormatter.value = normalizeSqlFormatterSettings(settingsStore.editorSettings.sqlFormatter);
+ sqlFormatterConfigValid.value = true;
editSidebarActivation.value = settingsStore.editorSettings.sidebarActivation;
editSidebarObjectDisplay.value = settingsStore.editorSettings.sidebarObjectDisplay;
editAutoSelectActiveSidebarNode.value = settingsStore.editorSettings.autoSelectActiveSidebarNode;
@@ -311,6 +321,10 @@ const shortcutsChanged = computed(
() => JSON.stringify(editShortcuts.value) !== JSON.stringify(settingsStore.editorSettings.shortcuts),
);
const hasBlockingShortcutConflicts = computed(() => shortcutsChanged.value && hasShortcutConflicts.value);
+const hasBlockingFormatterConfig = computed(
+ () => activeSettingsTab.value === "formatter" && !sqlFormatterConfigValid.value,
+);
+const hasApplyBlocker = computed(() => hasBlockingShortcutConflicts.value || hasBlockingFormatterConfig.value);
function hasChanges(): boolean {
return (
@@ -332,6 +346,8 @@ function hasChanges(): boolean {
editCompactColumnHeaderActions.value !== settingsStore.editorSettings.compactColumnHeaderActions ||
editRedisScanPageSize.value !== settingsStore.editorSettings.redisScanPageSize ||
JSON.stringify(editShortcuts.value) !== JSON.stringify(settingsStore.editorSettings.shortcuts) ||
+ JSON.stringify(editSqlFormatter.value) !==
+ JSON.stringify(normalizeSqlFormatterSettings(settingsStore.editorSettings.sqlFormatter)) ||
editSidebarActivation.value !== settingsStore.editorSettings.sidebarActivation ||
editSidebarObjectDisplay.value !== settingsStore.editorSettings.sidebarObjectDisplay ||
editAutoSelectActiveSidebarNode.value !== settingsStore.editorSettings.autoSelectActiveSidebarNode ||
@@ -348,7 +364,7 @@ function hasChanges(): boolean {
}
async function persistSettings() {
- if (hasBlockingShortcutConflicts.value) return;
+ if (hasApplyBlocker.value) return;
const sidebarObjectDisplayChanged =
editSidebarObjectDisplay.value !== settingsStore.editorSettings.sidebarObjectDisplay;
settingsStore.updateEditorSettings({
@@ -367,6 +383,7 @@ async function persistSettings() {
compactColumnHeaderActions: editCompactColumnHeaderActions.value,
redisScanPageSize: editRedisScanPageSize.value,
shortcuts: editShortcuts.value,
+ sqlFormatter: normalizeSqlFormatterSettings(editSqlFormatter.value),
sidebarActivation: editSidebarActivation.value,
sidebarObjectDisplay: editSidebarObjectDisplay.value,
autoSelectActiveSidebarNode: editAutoSelectActiveSidebarNode.value,
@@ -417,6 +434,8 @@ function resetDefaults() {
editCompactColumnHeaderActions.value = DEFAULT_EDITOR_SETTINGS.compactColumnHeaderActions;
editRedisScanPageSize.value = DEFAULT_EDITOR_SETTINGS.redisScanPageSize;
editShortcuts.value = normalizeShortcutSettings(DEFAULT_EDITOR_SETTINGS.shortcuts);
+ editSqlFormatter.value = normalizeSqlFormatterSettings(DEFAULT_EDITOR_SETTINGS.sqlFormatter);
+ sqlFormatterConfigValid.value = true;
editSidebarActivation.value = DEFAULT_EDITOR_SETTINGS.sidebarActivation;
editSidebarObjectDisplay.value = DEFAULT_EDITOR_SETTINGS.sidebarObjectDisplay;
editAutoSelectActiveSidebarNode.value = DEFAULT_EDITOR_SETTINGS.autoSelectActiveSidebarNode;
@@ -581,6 +600,7 @@ const isWeb = !isTauriRuntime();
const displayedAppVersion = computed(() => (props.appVersion ? `v${props.appVersion}` : ""));
type SettingsCategory =
| "editor"
+ | "formatter"
| "appearance"
| "navigation"
| "data"
@@ -594,6 +614,7 @@ type SettingsCategory =
| "about";
const settingsCategoryNav = computed<{ value: SettingsCategory; label: string }[]>(() => [
{ value: "editor", label: t("settings.editorTab") },
+ { value: "formatter", label: t("settings.sqlFormatterTab") },
{ value: "appearance", label: t("settings.appearanceTab") },
{ value: "navigation", label: t("settings.navigationTab") },
{ value: "data", label: t("settings.dataTab") },
@@ -608,6 +629,7 @@ const settingsCategoryNav = computed<{ value: SettingsCategory; label: string }[
]);
const settingsTabsWithApplyFooter = new Set<SettingsCategory>([
"editor",
+ "formatter",
"appearance",
"navigation",
"data",
@@ -1455,6 +1477,13 @@ watch(
</div>
</section>
+ <section v-else-if="activeSettingsTab === 'formatter'" class="flex flex-col gap-5 py-2">
+ <SqlFormatterSettingsPanel
+ v-model="editSqlFormatter"
+ @validity-change="(value: boolean) => (sqlFormatterConfigValid = value)"
+ />
+ </section>
+
<section v-else-if="activeSettingsTab === 'appearance'" class="flex flex-col gap-5 py-2">
<div class="space-y-2">
<Label>{{ t("settings.languageTitle") }}</Label>
@@ -2669,10 +2698,10 @@ watch(
<Button variant="outline" @click="emit('update:open', false)">
{{ t("common.close") }}
</Button>
- <Button :disabled="!hasChanges() || hasBlockingShortcutConflicts" @click="applySettings">
+ <Button :disabled="!hasChanges() || hasApplyBlocker" @click="applySettings">
{{ t("settings.apply") }}
</Button>
- <Button :disabled="!hasChanges() || hasBlockingShortcutConflicts" @click="applySettingsAndClose">
+ <Button :disabled="!hasChanges() || hasApplyBlocker" @click="applySettingsAndClose">
{{ t("settings.applyAndClose") }}
</Button>
</DialogFooter>
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue
index ca3f83169b..7395ef23b1 100644
--- a/apps/desktop/src/components/editor/QueryEditor.vue
+++ b/apps/desktop/src/components/editor/QueryEditor.vue
@@ -792,15 +792,27 @@ async function formatCurrentSql() {
const currentView = view.value;
if (!currentView) return;
- const selection = currentView.state.selection.main;
+ const originalState = currentView.state;
+ const selection = originalState.selection.main;
const formatsSelection = !selection.empty;
const from = formatsSelection ? selection.from : 0;
- const to = formatsSelection ? selection.to : currentView.state.doc.length;
- const source = currentView.state.sliceDoc(from, to);
+ const to = formatsSelection ? selection.to : originalState.doc.length;
+ const source = originalState.sliceDoc(from, to);
if (!source.trim()) return;
try {
- const formatted = await formatSqlText(source, props.formatDialect ?? props.dialect ?? "generic");
+ const formatted = await formatSqlText(
+ source,
+ props.formatDialect ?? props.dialect ?? "generic",
+ settingsStore.editorSettings.sqlFormatter,
+ );
+ if (
+ view.value !== currentView ||
+ currentView.state !== originalState ||
+ currentView.state.sliceDoc(from, to) !== source
+ ) {
+ return;
+ }
if (formatted === source) return;
currentView.dispatch({
changes: { from, to, insert: formatted },
diff --git a/apps/desktop/src/components/editor/SqlFormatterSettingsPanel.vue b/apps/desktop/src/components/editor/SqlFormatterSettingsPanel.vue
new file mode 100644
index 0000000000..4c67758308
--- /dev/null
+++ b/apps/desktop/src/components/editor/SqlFormatterSettingsPanel.vue
@@ -0,0 +1,617 @@
+<script setup lang="ts">
+import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";
+import { Upload, Download, RotateCcw, WandSparkles, Save } from "@lucide/vue";
+import { useI18n } from "vue-i18n";
+import { Button } from "@/components/ui/button";
+import { Label } from "@/components/ui/label";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { useToast } from "@/composables/useToast";
+import {
+ DEFAULT_SQL_FORMATTER_SETTINGS,
+ normalizeSqlFormatterSettings,
+ parseSqlFormatterConfig,
+ serializeSqlFormatterConfig,
+ syncSqlFormatterConfigDraft,
+ type SqlFormatterCase,
+ type SqlFormatterExpressionWidth,
+ type SqlFormatterLinesBetweenQueries,
+ type SqlFormatterLogicalOperatorNewline,
+ type SqlFormatterSettings,
+ type SqlFormatterTabWidth,
+} from "@/lib/sqlFormatterConfig";
+import { createSqlFormatterConfigKeymap, sqlFormatterConfigShortcutRows } from "@/lib/sqlFormatterConfigEditor";
+
+type EditorViewInstance = import("@codemirror/view").EditorView;
+type CodeMirrorModules = {
+ view: typeof import("@codemirror/view");
+ state: typeof import("@codemirror/state");
+ langJson: typeof import("@codemirror/lang-json");
+ commands: typeof import("@codemirror/commands");
+ search: typeof import("@codemirror/search");
+};
+
+const props = defineProps<{
+ modelValue: SqlFormatterSettings;
+}>();
+
+const emit = defineEmits<{
+ "update:modelValue": [value: SqlFormatterSettings];
+ validityChange: [value: boolean];
+}>();
+
+const { t } = useI18n();
+const { toast } = useToast();
+
+const activeMode = ref<"form" | "json">("form");
+const fileInputRef = ref<HTMLInputElement>();
+const jsonEditorRef = ref<HTMLDivElement>();
+const jsonDraft = ref(serializeSqlFormatterConfig(props.modelValue));
+const jsonValidationMessage = ref("");
+const importError = ref("");
+const jsonEditorLoading = ref(false);
+
+let cmView: EditorViewInstance | null = null;
+let cmModules: CodeMirrorModules | null = null;
+let lastValidity: boolean | null = null;
+
+const settings = computed(() => normalizeSqlFormatterSettings(props.modelValue));
+const shortcutRows = computed(() => sqlFormatterConfigShortcutRows(globalThis.navigator?.platform || ""));
+
+const caseOptions: { value: SqlFormatterCase; labelKey: string }[] = [
+ { value: "upper", labelKey: "settings.sqlFormatterCaseUpper" },
+ { value: "lower", labelKey: "settings.sqlFormatterCaseLower" },
+ { value: "preserve", labelKey: "settings.sqlFormatterCasePreserve" },
+];
+
+const logicalOperatorOptions: { value: SqlFormatterLogicalOperatorNewline; labelKey: string }[] = [
+ { value: "before", labelKey: "settings.sqlFormatterLogicalBefore" },
+ { value: "after", labelKey: "settings.sqlFormatterLogicalAfter" },
+];
+
+const tabWidthOptions: SqlFormatterTabWidth[] = [2, 4];
+const expressionWidthOptions: SqlFormatterExpressionWidth[] = [50, 80, 120];
+const linesBetweenQueriesOptions: SqlFormatterLinesBetweenQueries[] = [0, 1, 2];
+const sqlFormatterOptionLabelKeys: Record<keyof SqlFormatterSettings, string> = {
+ keywordCase: "settings.sqlFormatterKeywordCase",
+ dataTypeCase: "settings.sqlFormatterDataTypeCase",
+ functionCase: "settings.sqlFormatterFunctionCase",
+ useTabs: "settings.sqlFormatterIndent",
+ tabWidth: "settings.sqlFormatterTabWidth",
+ logicalOperatorNewline: "settings.sqlFormatterLogicalOperatorNewline",
+ expressionWidth: "settings.sqlFormatterExpressionWidth",
+ linesBetweenQueries: "settings.sqlFormatterLinesBetweenQueries",
+ denseOperators: "settings.sqlFormatterDenseOperators",
+ newlineBeforeSemicolon: "settings.sqlFormatterNewlineBeforeSemicolon",
+};
+const sqlFormatterConfigErrorKeys: Record<string, string> = {
+ "Invalid JSON.": "settings.sqlFormatterConfigErrorInvalidJson",
+ "Config must be a JSON object.": "settings.sqlFormatterConfigErrorObject",
+ "Unsupported config version.": "settings.sqlFormatterConfigErrorVersion",
+ "Unsupported formatter.": "settings.sqlFormatterConfigErrorFormatter",
+ "Config options must be a JSON object.": "settings.sqlFormatterConfigErrorOptionsObject",
+};
+
+function emitValidity(value: boolean) {
+ if (lastValidity === value) return;
+ lastValidity = value;
+ emit("validityChange", value);
+}
+
+function setJsonDraftText(text: string) {
+ jsonDraft.value = text;
+ if (!cmView || cmView.state.doc.toString() === text) return;
+ cmView.dispatch({
+ changes: { from: 0, to: cmView.state.doc.length, insert: text },
+ });
+}
+
+function localizeSqlFormatterConfigError(message: string): string {
+ const exactKey = sqlFormatterConfigErrorKeys[message];
+ if (exactKey) return t(exactKey);
+
+ const unknownOption = message.match(/^Unknown formatter option: (.+)\.$/);
+ if (unknownOption?.[1]) {
+ return t("settings.sqlFormatterConfigErrorUnknownOption", { option: unknownOption[1] });
+ }
+
+ const invalidOption = message.match(/^Invalid formatter option value: (.+)\.$/);
+ if (invalidOption?.[1]) {
+ const labelKey = sqlFormatterOptionLabelKeys[invalidOption[1] as keyof SqlFormatterSettings];
+ if (labelKey) {
+ return t("settings.sqlFormatterConfigErrorInvalidOptionValue", { option: t(labelKey) });
+ }
+ }
+
+ return t("settings.sqlFormatterConfigErrorInvalidConfig");
+}
+
+function validateJsonDraft(text = jsonDraft.value): boolean {
+ const result = parseSqlFormatterConfig(text);
+ jsonValidationMessage.value = result.ok ? "" : localizeSqlFormatterConfigError(result.message);
+ const valid = result.ok;
+ emitValidity(activeMode.value === "json" ? valid : true);
+ return valid;
+}
+
+function syncJsonDraft(text = jsonDraft.value): boolean {
+ const result = syncSqlFormatterConfigDraft(text, updateSettings);
+ jsonValidationMessage.value = result.ok ? "" : localizeSqlFormatterConfigError(result.message);
+ emitValidity(activeMode.value === "json" ? result.ok : true);
+ return result.ok;
+}
+
+function updateSettings(next: unknown) {
+ importError.value = "";
+ emit("update:modelValue", normalizeSqlFormatterSettings(next));
+}
+
+function updateOption<K extends keyof SqlFormatterSettings>(key: K, value: SqlFormatterSettings[K]) {
+ updateSettings({ ...settings.value, [key]: value });
+}
+
+function onCaseOption(key: "keywordCase" | "functionCase" | "dataTypeCase", value: any) {
+ if (value === "upper" || value === "lower" || value === "preserve") updateOption(key, value);
+}
+
+function onLogicalOperatorNewline(value: any) {
+ if (value === "before" || value === "after") updateOption("logicalOperatorNewline", value);
+}
+
+function onTabWidth(value: any) {
+ const next = Number(value);
+ if (next === 2 || next === 4) updateOption("tabWidth", next);
+}
+
+function onExpressionWidth(value: any) {
+ const next = Number(value);
+ if (next === 50 || next === 80 || next === 120) updateOption("expressionWidth", next);
+}
+
+function onLinesBetweenQueries(value: any) {
+ const next = Number(value);
+ if (next === 0 || next === 1 || next === 2) updateOption("linesBetweenQueries", next);
+}
+
+function restoreDefaults() {
+ updateSettings(DEFAULT_SQL_FORMATTER_SETTINGS);
+}
+
+function importConfig() {
+ importError.value = "";
+ fileInputRef.value?.click();
+}
+
+async function onImportFile(event: Event) {
+ const input = event.target as HTMLInputElement;
+ const file = input.files?.[0];
+ input.value = "";
+ if (!file) return;
+
+ try {
+ const text = await file.text();
+ const result = parseSqlFormatterConfig(text);
+ if (!result.ok) {
+ importError.value = localizeSqlFormatterConfigError(result.message);
+ return;
+ }
+ updateSettings(result.settings);
+ toast(t("settings.sqlFormatterImportSuccess"));
+ } catch (e: any) {
+ importError.value = e?.message || String(e);
+ }
+}
+
+function exportConfig() {
+ const blob = new Blob([serializeSqlFormatterConfig(settings.value)], { type: "application/json" });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = "dbx-sql-formatter.json";
+ document.body.appendChild(link);
+ link.click();
+ link.remove();
+ URL.revokeObjectURL(url);
+}
+
+function applyJsonDraft(): boolean {
+ const result = parseSqlFormatterConfig(jsonDraft.value);
+ if (!result.ok) {
+ jsonValidationMessage.value = localizeSqlFormatterConfigError(result.message);
+ emitValidity(false);
+ return true;
+ }
+
+ const pretty = serializeSqlFormatterConfig(result.settings);
+ updateSettings(result.settings);
+ setJsonDraftText(pretty);
+ jsonValidationMessage.value = "";
+ emitValidity(true);
+ return true;
+}
+
+function formatJsonDraft(): boolean {
+ const result = parseSqlFormatterConfig(jsonDraft.value);
+ if (!result.ok) {
+ jsonValidationMessage.value = localizeSqlFormatterConfigError(result.message);
+ emitValidity(false);
+ return true;
+ }
+
+ setJsonDraftText(serializeSqlFormatterConfig(result.settings));
+ jsonValidationMessage.value = "";
+ emitValidity(true);
+ return true;
+}
+
+async function loadCodeMirrorModules(): Promise<CodeMirrorModules> {
+ if (cmModules) return cmModules;
+ const [view, state, langJson, commands, search] = await Promise.all([
+ import("@codemirror/view"),
+ import("@codemirror/state"),
+ import("@codemirror/lang-json"),
+ import("@codemirror/commands"),
+ import("@codemirror/search"),
+ ]);
+ cmModules = { view, state, langJson, commands, search };
+ return cmModules;
+}
+
+function destroyJsonEditor() {
+ cmView?.destroy();
+ cmView = null;
+}
+
+async function initJsonEditor() {
+ if (cmView || !jsonEditorRef.value) return;
+ jsonEditorLoading.value = true;
+ try {
+ const modules = await loadCodeMirrorModules();
+ if (activeMode.value !== "json" || cmView || !jsonEditorRef.value) return;
+
+ const { EditorView, keymap, lineNumbers, highlightActiveLine, highlightActiveLineGutter } = modules.view;
+ const { EditorState } = modules.state;
+ const { json } = modules.langJson;
+ const commands = modules.commands;
+ const search = modules.search;
+
+ const customKeymap = createSqlFormatterConfigKeymap(
+ {
+ indentMore: commands.indentMore,
+ indentLess: commands.indentLess,
+ copyLineDown: commands.copyLineDown,
+ copyLineUp: commands.copyLineUp,
+ deleteLine: commands.deleteLine,
+ moveLineUp: commands.moveLineUp,
+ moveLineDown: commands.moveLineDown,
+ openSearchPanel: search.openSearchPanel,
+ },
+ {
+ apply: applyJsonDraft,
+ formatJson: formatJsonDraft,
+ },
+ );
+
+ const state = EditorState.create({
+ doc: jsonDraft.value,
+ extensions: [
+ lineNumbers(),
+ highlightActiveLineGutter(),
+ highlightActiveLine(),
+ commands.history(),
+ search.search({ top: true }),
+ json(),
+ keymap.of([...customKeymap, ...search.searchKeymap, ...commands.historyKeymap, ...commands.defaultKeymap]),
+ EditorView.lineWrapping,
+ EditorView.updateListener.of((update) => {
+ if (!update.docChanged) return;
+ jsonDraft.value = update.state.doc.toString();
+ syncJsonDraft(jsonDraft.value);
+ }),
+ EditorView.theme({
+ "&": {
+ minHeight: "260px",
+ maxHeight: "360px",
+ fontSize: "12px",
+ border: "1px solid hsl(var(--border))",
+ borderRadius: "var(--radius-md)",
+ backgroundColor: "hsl(var(--background))",
+ color: "hsl(var(--foreground))",
+ },
+ ".cm-scroller": {
+ fontFamily: "var(--font-mono), ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
+ },
+ ".cm-gutters": {
+ backgroundColor: "hsl(var(--muted) / 0.35)",
+ color: "hsl(var(--muted-foreground))",
+ borderRight: "1px solid hsl(var(--border))",
+ },
+ ".cm-activeLine, .cm-activeLineGutter": {
+ backgroundColor: "hsl(var(--muted) / 0.45)",
+ },
+ ".cm-focused": {
+ outline: "2px solid hsl(var(--ring) / 0.35)",
+ outlineOffset: "1px",
+ },
+ }),
+ ],
+ });
+
+ cmView = new EditorView({ state, parent: jsonEditorRef.value });
+ } finally {
+ jsonEditorLoading.value = false;
+ }
+}
+
+watch(
+ () => props.modelValue,
+ (value) => {
+ if (activeMode.value === "json") {
+ const currentDraft = parseSqlFormatterConfig(jsonDraft.value);
+ if (
+ currentDraft.ok &&
+ serializeSqlFormatterConfig(currentDraft.settings) === serializeSqlFormatterConfig(value)
+ ) {
+ validateJsonDraft(jsonDraft.value);
+ return;
+ }
+ }
+
+ const text = serializeSqlFormatterConfig(value);
+ setJsonDraftText(text);
+ if (activeMode.value === "json") validateJsonDraft(text);
+ },
+ { deep: true },
+);
+
+watch(
+ activeMode,
+ async (mode) => {
+ if (mode === "json") {
+ validateJsonDraft();
+ await nextTick();
+ await initJsonEditor();
+ return;
+ }
+ emitValidity(true);
+ destroyJsonEditor();
+ },
+ { immediate: true },
+);
+
+onBeforeUnmount(() => {
+ destroyJsonEditor();
+});
+</script>
+
+<template>
+ <div class="flex flex-col gap-4">
+ <div class="flex flex-wrap items-center gap-2">
+ <input ref="fileInputRef" type="file" accept="application/json,.json" class="hidden" @change="onImportFile" />
+ <Button type="button" variant="outline" size="sm" @click="importConfig">
+ <Upload class="mr-2 h-4 w-4" />
+ {{ t("settings.sqlFormatterImport") }}
+ </Button>
+ <Button type="button" variant="outline" size="sm" @click="exportConfig">
+ <Download class="mr-2 h-4 w-4" />
+ {{ t("settings.sqlFormatterExport") }}
+ </Button>
+ <Button type="button" variant="outline" size="sm" @click="restoreDefaults">
+ <RotateCcw class="mr-2 h-4 w-4" />
+ {{ t("settings.sqlFormatterRestoreDefaults") }}
+ </Button>
+ </div>
+
+ <p
+ v-if="importError"
+ class="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive"
+ >
+ {{ importError }}
+ </p>
+
+ <Tabs v-model="activeMode" class="min-h-0">
+ <TabsList class="grid w-full grid-cols-2">
+ <TabsTrigger value="form">{{ t("settings.sqlFormatterFormMode") }}</TabsTrigger>
+ <TabsTrigger value="json">{{ t("settings.sqlFormatterJsonMode") }}</TabsTrigger>
+ </TabsList>
+
+ <TabsContent value="form" class="m-0 flex flex-col gap-4 pt-2">
+ <div class="grid gap-4 md:grid-cols-3">
+ <div class="space-y-2">
+ <Label>{{ t("settings.sqlFormatterKeywordCase") }}</Label>
+ <Select
+ :model-value="settings.keywordCase"
+ @update:model-value="(value: any) => onCaseOption('keywordCase', value)"
+ >
+ <SelectTrigger class="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="option in caseOptions" :key="option.value" :value="option.value">
+ {{ t(option.labelKey) }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ <div class="space-y-2">
+ <Label>{{ t("settings.sqlFormatterFunctionCase") }}</Label>
+ <Select
+ :model-value="settings.functionCase"
+ @update:model-value="(value: any) => onCaseOption('functionCase', value)"
+ >
+ <SelectTrigger class="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="option in caseOptions" :key="option.value" :value="option.value">
+ {{ t(option.labelKey) }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ <div class="space-y-2">
+ <Label>{{ t("settings.sqlFormatterDataTypeCase") }}</Label>
+ <Select
+ :model-value="settings.dataTypeCase"
+ @update:model-value="(value: any) => onCaseOption('dataTypeCase', value)"
+ >
+ <SelectTrigger class="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="option in caseOptions" :key="option.value" :value="option.value">
+ {{ t(option.labelKey) }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+
+ <div class="grid gap-4 md:grid-cols-[minmax(0,1fr)_10rem]">
+ <div class="space-y-2">
+ <Label>{{ t("settings.sqlFormatterIndent") }}</Label>
+ <div class="grid grid-cols-2 gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ class="justify-center"
+ :class="!settings.useTabs ? 'border-blue-300 ring-2 ring-blue-300/50' : ''"
+ @click="updateOption('useTabs', false)"
+ >
+ {{ t("settings.sqlFormatterIndentSpaces") }}
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ class="justify-center"
+ :class="settings.useTabs ? 'border-blue-300 ring-2 ring-blue-300/50' : ''"
+ @click="updateOption('useTabs', true)"
+ >
+ {{ t("settings.sqlFormatterIndentTabs") }}
+ </Button>
+ </div>
+ </div>
+
+ <div class="space-y-2">
+ <Label>{{ t("settings.sqlFormatterTabWidth") }}</Label>
+ <Select :model-value="String(settings.tabWidth)" @update:model-value="onTabWidth">
+ <SelectTrigger class="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="width in tabWidthOptions" :key="width" :value="String(width)">
+ {{ width }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+
+ <div class="grid gap-4 md:grid-cols-3">
+ <div class="space-y-2">
+ <Label>{{ t("settings.sqlFormatterLogicalOperatorNewline") }}</Label>
+ <Select :model-value="settings.logicalOperatorNewline" @update:model-value="onLogicalOperatorNewline">
+ <SelectTrigger class="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="option in logicalOperatorOptions" :key="option.value" :value="option.value">
+ {{ t(option.labelKey) }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ <div class="space-y-2">
+ <Label>{{ t("settings.sqlFormatterExpressionWidth") }}</Label>
+ <Select :model-value="String(settings.expressionWidth)" @update:model-value="onExpressionWidth">
+ <SelectTrigger class="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="width in expressionWidthOptions" :key="width" :value="String(width)">
+ {{ width }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ <div class="space-y-2">
+ <Label>{{ t("settings.sqlFormatterLinesBetweenQueries") }}</Label>
+ <Select :model-value="String(settings.linesBetweenQueries)" @update:model-value="onLinesBetweenQueries">
+ <SelectTrigger class="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem v-for="count in linesBetweenQueriesOptions" :key="count" :value="String(count)">
+ {{ count }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+
+ <div class="grid gap-3 md:grid-cols-2">
+ <div class="flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
+ <Label for="sql-formatter-dense-operators">{{ t("settings.sqlFormatterDenseOperators") }}</Label>
+ <Switch
+ id="sql-formatter-dense-operators"
+ :model-value="settings.denseOperators"
+ @update:model-value="(value: boolean) => updateOption('denseOperators', value)"
+ />
+ </div>
+
+ <div class="flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
+ <Label for="sql-formatter-newline-before-semicolon">
+ {{ t("settings.sqlFormatterNewlineBeforeSemicolon") }}
+ </Label>
+ <Switch
+ id="sql-formatter-newline-before-semicolon"
+ :model-value="settings.newlineBeforeSemicolon"
+ @update:model-value="(value: boolean) => updateOption('newlineBeforeSemicolon', value)"
+ />
+ </div>
+ </div>
+ </TabsContent>
+
+ <TabsContent value="json" class="m-0 flex min-h-0 flex-col gap-3 pt-2">
+ <div class="flex flex-wrap items-center gap-2">
+ <Button type="button" variant="outline" size="sm" @click="formatJsonDraft">
+ <WandSparkles class="mr-2 h-4 w-4" />
+ {{ t("settings.sqlFormatterShortcutFormatJson") }}
+ </Button>
+ <Button type="button" size="sm" :disabled="!!jsonValidationMessage" @click="applyJsonDraft">
+ <Save class="mr-2 h-4 w-4" />
+ {{ t("settings.sqlFormatterShortcutApply") }}
+ </Button>
+ <span v-if="jsonEditorLoading" class="text-xs text-muted-foreground">{{ t("common.loading") }}</span>
+ </div>
+
+ <div ref="jsonEditorRef" class="min-h-[260px]" />
+
+ <p
+ v-if="jsonValidationMessage"
+ class="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive"
+ >
+ {{ jsonValidationMessage }}
+ </p>
+
+ <div class="grid gap-1 rounded-md border border-border/70 bg-muted/20 p-2 sm:grid-cols-2">
+ <div
+ v-for="row in shortcutRows"
+ :key="row.id"
+ class="flex min-w-0 items-center justify-between gap-2 rounded px-1.5 py-1 text-xs"
+ >
+ <span class="truncate text-muted-foreground">{{ t(row.labelKey) }}</span>
+ <span class="shrink-0 rounded border bg-background px-1.5 py-0.5 font-mono text-[11px]">
+ {{ row.shortcut }}
+ </span>
+ </div>
+ </div>
+ </TabsContent>
+ </Tabs>
+ </div>
+</template>
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 880c6575b1..970c061338 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -1708,6 +1708,48 @@ export default {
settings: {
title: "Settings",
editorTab: "Editor",
+ sqlFormatterTab: "SQL Formatter",
+ sqlFormatterImport: "Import config",
+ sqlFormatterExport: "Export config",
+ sqlFormatterImportSuccess: "Formatter config imported.",
+ sqlFormatterRestoreDefaults: "Restore defaults",
+ sqlFormatterFormMode: "Form",
+ sqlFormatterJsonMode: "JSON",
+ sqlFormatterKeywordCase: "Keyword case",
+ sqlFormatterFunctionCase: "Function case",
+ sqlFormatterDataTypeCase: "Data type case",
+ sqlFormatterCaseUpper: "Uppercase",
+ sqlFormatterCaseLower: "Lowercase",
+ sqlFormatterCasePreserve: "Preserve",
+ sqlFormatterIndent: "Indent",
+ sqlFormatterIndentSpaces: "Spaces",
+ sqlFormatterIndentTabs: "Tabs",
+ sqlFormatterTabWidth: "Tab width",
+ sqlFormatterLogicalOperatorNewline: "Logical operator newline",
+ sqlFormatterLogicalBefore: "Before operator",
+ sqlFormatterLogicalAfter: "After operator",
+ sqlFormatterExpressionWidth: "Expression width",
+ sqlFormatterLinesBetweenQueries: "Lines between queries",
+ sqlFormatterDenseOperators: "Dense operators",
+ sqlFormatterNewlineBeforeSemicolon: "Semicolon on new line",
+ sqlFormatterShortcutFind: "Find",
+ sqlFormatterShortcutReplace: "Replace",
+ sqlFormatterShortcutIndentMore: "Indent more",
+ sqlFormatterShortcutIndentLess: "Indent less",
+ sqlFormatterShortcutDuplicateLine: "Duplicate current line",
+ sqlFormatterShortcutDeleteLine: "Delete current line",
+ sqlFormatterShortcutMoveLine: "Move line",
+ sqlFormatterShortcutCopyLine: "Copy line",
+ sqlFormatterShortcutFormatJson: "Format JSON",
+ sqlFormatterShortcutApply: "Apply config",
+ sqlFormatterConfigErrorInvalidJson: "Invalid JSON.",
+ sqlFormatterConfigErrorObject: "Config must be a JSON object.",
+ sqlFormatterConfigErrorVersion: "Unsupported config version.",
+ sqlFormatterConfigErrorFormatter: "Unsupported formatter.",
+ sqlFormatterConfigErrorOptionsObject: "Config options must be a JSON object.",
+ sqlFormatterConfigErrorUnknownOption: "Unknown formatter option: {option}.",
+ sqlFormatterConfigErrorInvalidOptionValue: "Invalid value for {option}.",
+ sqlFormatterConfigErrorInvalidConfig: "Invalid formatter config.",
appearanceTab: "Appearance",
navigationTab: "Navigation",
dataTab: "Data",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 07d6fa7679..6057061056 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -1497,6 +1497,48 @@ export default {
settings: {
title: "Configuración",
editorTab: "Editor",
+ sqlFormatterTab: "Formateador SQL",
+ sqlFormatterImport: "Importar configuración",
+ sqlFormatterExport: "Exportar configuración",
+ sqlFormatterImportSuccess: "Configuración del formateador importada.",
+ sqlFormatterRestoreDefaults: "Restaurar valores por defecto",
+ sqlFormatterFormMode: "Formulario",
+ sqlFormatterJsonMode: "JSON",
+ sqlFormatterKeywordCase: "Mayúsculas/minúsculas de palabras clave",
+ sqlFormatterFunctionCase: "Mayúsculas/minúsculas de funciones",
+ sqlFormatterDataTypeCase: "Mayúsculas/minúsculas de tipos de datos",
+ sqlFormatterCaseUpper: "Mayúsculas",
+ sqlFormatterCaseLower: "Minúsculas",
+ sqlFormatterCasePreserve: "Conservar",
+ sqlFormatterIndent: "Sangría",
+ sqlFormatterIndentSpaces: "Espacios",
+ sqlFormatterIndentTabs: "Tabulaciones",
+ sqlFormatterTabWidth: "Ancho de tabulación",
+ sqlFormatterLogicalOperatorNewline: "Salto de línea en operador lógico",
+ sqlFormatterLogicalBefore: "Antes del operador",
+ sqlFormatterLogicalAfter: "Después del operador",
+ sqlFormatterExpressionWidth: "Ancho de expresión",
+ sqlFormatterLinesBetweenQueries: "Líneas entre consultas",
+ sqlFormatterDenseOperators: "Operadores compactos",
+ sqlFormatterNewlineBeforeSemicolon: "Punto y coma en nueva línea",
+ sqlFormatterShortcutFind: "Buscar",
+ sqlFormatterShortcutReplace: "Reemplazar",
+ sqlFormatterShortcutIndentMore: "Aumentar sangría",
+ sqlFormatterShortcutIndentLess: "Reducir sangría",
+ sqlFormatterShortcutDuplicateLine: "Duplicar línea actual",
+ sqlFormatterShortcutDeleteLine: "Eliminar línea actual",
+ sqlFormatterShortcutMoveLine: "Mover línea",
+ sqlFormatterShortcutCopyLine: "Copiar línea",
+ sqlFormatterShortcutFormatJson: "Formatear JSON",
+ sqlFormatterShortcutApply: "Aplicar configuración",
+ sqlFormatterConfigErrorInvalidJson: "JSON no válido.",
+ sqlFormatterConfigErrorObject: "La configuración debe ser un objeto JSON.",
+ sqlFormatterConfigErrorVersion: "Versión de configuración no compatible.",
+ sqlFormatterConfigErrorFormatter: "Formateador no compatible.",
+ sqlFormatterConfigErrorOptionsObject: "Las opciones de configuración deben ser un objeto JSON.",
+ sqlFormatterConfigErrorUnknownOption: "Opción desconocida del formateador: {option}.",
+ sqlFormatterConfigErrorInvalidOptionValue: "Valor no válido para {option}.",
+ sqlFormatterConfigErrorInvalidConfig: "Configuración del formateador no válida.",
appearanceTab: "Apariencia",
navigationTab: "Navegación",
dataTab: "Datos",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 77c5d48d3a..dbc4647fdd 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -1639,6 +1639,48 @@ export default {
settings: {
title: "Impostazioni",
editorTab: "Editor",
+ sqlFormatterTab: "Formattatore SQL",
+ sqlFormatterImport: "Importa configurazione",
+ sqlFormatterExport: "Esporta configurazione",
+ sqlFormatterImportSuccess: "Configurazione del formattatore importata.",
+ sqlFormatterRestoreDefaults: "Ripristina predefiniti",
+ sqlFormatterFormMode: "Modulo",
+ sqlFormatterJsonMode: "JSON",
+ sqlFormatterKeywordCase: "Maiuscole/minuscole parole chiave",
+ sqlFormatterFunctionCase: "Maiuscole/minuscole funzioni",
+ sqlFormatterDataTypeCase: "Maiuscole/minuscole tipi di dati",
+ sqlFormatterCaseUpper: "Maiuscolo",
+ sqlFormatterCaseLower: "Minuscolo",
+ sqlFormatterCasePreserve: "Mantieni",
+ sqlFormatterIndent: "Rientro",
+ sqlFormatterIndentSpaces: "Spazi",
+ sqlFormatterIndentTabs: "Tabulazioni",
+ sqlFormatterTabWidth: "Larghezza tab",
+ sqlFormatterLogicalOperatorNewline: "Nuova riga operatore logico",
+ sqlFormatterLogicalBefore: "Prima dell'operatore",
+ sqlFormatterLogicalAfter: "Dopo l'operatore",
+ sqlFormatterExpressionWidth: "Larghezza espressione",
+ sqlFormatterLinesBetweenQueries: "Righe tra query",
+ sqlFormatterDenseOperators: "Operatori compatti",
+ sqlFormatterNewlineBeforeSemicolon: "Punto e virgola su nuova riga",
+ sqlFormatterShortcutFind: "Trova",
+ sqlFormatterShortcutReplace: "Sostituisci",
+ sqlFormatterShortcutIndentMore: "Aumenta rientro",
+ sqlFormatterShortcutIndentLess: "Riduci rientro",
+ sqlFormatterShortcutDuplicateLine: "Duplica riga corrente",
+ sqlFormatterShortcutDeleteLine: "Elimina riga corrente",
+ sqlFormatterShortcutMoveLine: "Sposta riga",
+ sqlFormatterShortcutCopyLine: "Copia riga",
+ sqlFormatterShortcutFormatJson: "Formatta JSON",
+ sqlFormatterShortcutApply: "Applica configurazione",
+ sqlFormatterConfigErrorInvalidJson: "JSON non valido.",
+ sqlFormatterConfigErrorObject: "La configurazione deve essere un oggetto JSON.",
+ sqlFormatterConfigErrorVersion: "Versione configurazione non supportata.",
+ sqlFormatterConfigErrorFormatter: "Formattatore non supportato.",
+ sqlFormatterConfigErrorOptionsObject: "Le opzioni di configurazione devono essere un oggetto JSON.",
+ sqlFormatterConfigErrorUnknownOption: "Opzione del formattatore sconosciuta: {option}.",
+ sqlFormatterConfigErrorInvalidOptionValue: "Valore non valido per {option}.",
+ sqlFormatterConfigErrorInvalidConfig: "Configurazione del formattatore non valida.",
appearanceTab: "Aspetto",
navigationTab: "Navigazione",
dataTab: "Dati",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index cfbc7b0081..8939a0388e 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -1629,6 +1629,48 @@ export default {
settings: {
title: "Configurações",
editorTab: "Editor",
+ sqlFormatterTab: "Formatador SQL",
+ sqlFormatterImport: "Importar configuração",
+ sqlFormatterExport: "Exportar configuração",
+ sqlFormatterImportSuccess: "Configuração do formatador importada.",
+ sqlFormatterRestoreDefaults: "Restaurar padrões",
+ sqlFormatterFormMode: "Formulário",
+ sqlFormatterJsonMode: "JSON",
+ sqlFormatterKeywordCase: "Maiúsculas/minúsculas de palavras-chave",
+ sqlFormatterFunctionCase: "Maiúsculas/minúsculas de funções",
+ sqlFormatterDataTypeCase: "Maiúsculas/minúsculas de tipos de dados",
+ sqlFormatterCaseUpper: "Maiúsculas",
+ sqlFormatterCaseLower: "Minúsculas",
+ sqlFormatterCasePreserve: "Preservar",
+ sqlFormatterIndent: "Recuo",
+ sqlFormatterIndentSpaces: "Espaços",
+ sqlFormatterIndentTabs: "Tabulações",
+ sqlFormatterTabWidth: "Largura do tab",
+ sqlFormatterLogicalOperatorNewline: "Quebra de linha no operador lógico",
+ sqlFormatterLogicalBefore: "Antes do operador",
+ sqlFormatterLogicalAfter: "Depois do operador",
+ sqlFormatterExpressionWidth: "Largura da expressão",
+ sqlFormatterLinesBetweenQueries: "Linhas entre consultas",
+ sqlFormatterDenseOperators: "Operadores compactos",
+ sqlFormatterNewlineBeforeSemicolon: "Ponto e vírgula em nova linha",
+ sqlFormatterShortcutFind: "Localizar",
+ sqlFormatterShortcutReplace: "Substituir",
+ sqlFormatterShortcutIndentMore: "Aumentar recuo",
+ sqlFormatterShortcutIndentLess: "Reduzir recuo",
+ sqlFormatterShortcutDuplicateLine: "Duplicar linha atual",
+ sqlFormatterShortcutDeleteLine: "Excluir linha atual",
+ sqlFormatterShortcutMoveLine: "Mover linha",
+ sqlFormatterShortcutCopyLine: "Copiar linha",
+ sqlFormatterShortcutFormatJson: "Formatar JSON",
+ sqlFormatterShortcutApply: "Aplicar configuração",
+ sqlFormatterConfigErrorInvalidJson: "JSON inválido.",
+ sqlFormatterConfigErrorObject: "A configuração deve ser um objeto JSON.",
+ sqlFormatterConfigErrorVersion: "Versão de configuração não compatível.",
+ sqlFormatterConfigErrorFormatter: "Formatador não compatível.",
+ sqlFormatterConfigErrorOptionsObject: "As opções de configuração devem ser um objeto JSON.",
+ sqlFormatterConfigErrorUnknownOption: "Opção desconhecida do formatador: {option}.",
+ sqlFormatterConfigErrorInvalidOptionValue: "Valor inválido para {option}.",
+ sqlFormatterConfigErrorInvalidConfig: "Configuração do formatador inválida.",
appearanceTab: "Aparência",
navigationTab: "Navegação",
dataTab: "Dados",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 419517821a..bb0553de2a 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -1677,6 +1677,48 @@ export default {
settings: {
title: "设置",
editorTab: "编辑器",
+ sqlFormatterTab: "SQL 格式化",
+ sqlFormatterImport: "导入配置",
+ sqlFormatterExport: "导出配置",
+ sqlFormatterImportSuccess: "格式化配置已导入。",
+ sqlFormatterRestoreDefaults: "恢复默认",
+ sqlFormatterFormMode: "表单",
+ sqlFormatterJsonMode: "JSON",
+ sqlFormatterKeywordCase: "关键字大小写",
+ sqlFormatterFunctionCase: "函数名大小写",
+ sqlFormatterDataTypeCase: "数据类型大小写",
+ sqlFormatterCaseUpper: "大写",
+ sqlFormatterCaseLower: "小写",
+ sqlFormatterCasePreserve: "保持原样",
+ sqlFormatterIndent: "缩进",
+ sqlFormatterIndentSpaces: "空格",
+ sqlFormatterIndentTabs: "Tab",
+ sqlFormatterTabWidth: "缩进宽度",
+ sqlFormatterLogicalOperatorNewline: "逻辑运算符换行",
+ sqlFormatterLogicalBefore: "运算符前换行",
+ sqlFormatterLogicalAfter: "运算符后换行",
+ sqlFormatterExpressionWidth: "表达式宽度",
+ sqlFormatterLinesBetweenQueries: "查询之间空行",
+ sqlFormatterDenseOperators: "紧凑运算符",
+ sqlFormatterNewlineBeforeSemicolon: "分号单独换行",
+ sqlFormatterShortcutFind: "查找",
+ sqlFormatterShortcutReplace: "替换",
+ sqlFormatterShortcutIndentMore: "增加缩进",
+ sqlFormatterShortcutIndentLess: "减少缩进",
+ sqlFormatterShortcutDuplicateLine: "复制当前行",
+ sqlFormatterShortcutDeleteLine: "删除当前行",
+ sqlFormatterShortcutMoveLine: "移动行",
+ sqlFormatterShortcutCopyLine: "复制行",
+ sqlFormatterShortcutFormatJson: "格式化 JSON",
+ sqlFormatterShortcutApply: "应用配置",
+ sqlFormatterConfigErrorInvalidJson: "JSON 无效。",
+ sqlFormatterConfigErrorObject: "配置必须是 JSON 对象。",
+ sqlFormatterConfigErrorVersion: "不支持的配置版本。",
+ sqlFormatterConfigErrorFormatter: "不支持的格式化器。",
+ sqlFormatterConfigErrorOptionsObject: "配置选项必须是 JSON 对象。",
+ sqlFormatterConfigErrorUnknownOption: "未知格式化选项:{option}。",
+ sqlFormatterConfigErrorInvalidOptionValue: "“{option}”的值无效。",
+ sqlFormatterConfigErrorInvalidConfig: "格式化配置无效。",
appearanceTab: "外观",
navigationTab: "导航",
dataTab: "数据",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index d17e32b1d2..97fe362ade 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -1557,6 +1557,48 @@ export default {
settings: {
title: "設定",
editorTab: "編輯器",
+ sqlFormatterTab: "SQL 格式化",
+ sqlFormatterImport: "匯入設定",
+ sqlFormatterExport: "匯出設定",
+ sqlFormatterImportSuccess: "格式化設定已匯入。",
+ sqlFormatterRestoreDefaults: "還原預設",
+ sqlFormatterFormMode: "表單",
+ sqlFormatterJsonMode: "JSON",
+ sqlFormatterKeywordCase: "關鍵字大小寫",
+ sqlFormatterFunctionCase: "函式名稱大小寫",
+ sqlFormatterDataTypeCase: "資料型別大小寫",
+ sqlFormatterCaseUpper: "大寫",
+ sqlFormatterCaseLower: "小寫",
+ sqlFormatterCasePreserve: "保持原樣",
+ sqlFormatterIndent: "縮排",
+ sqlFormatterIndentSpaces: "空格",
+ sqlFormatterIndentTabs: "Tab",
+ sqlFormatterTabWidth: "縮排寬度",
+ sqlFormatterLogicalOperatorNewline: "邏輯運算子換行",
+ sqlFormatterLogicalBefore: "運算子前換行",
+ sqlFormatterLogicalAfter: "運算子後換行",
+ sqlFormatterExpressionWidth: "運算式寬度",
+ sqlFormatterLinesBetweenQueries: "查詢之間空行",
+ sqlFormatterDenseOperators: "緊湊運算子",
+ sqlFormatterNewlineBeforeSemicolon: "分號獨立換行",
+ sqlFormatterShortcutFind: "尋找",
+ sqlFormatterShortcutReplace: "取代",
+ sqlFormatterShortcutIndentMore: "增加縮排",
+ sqlFormatterShortcutIndentLess: "減少縮排",
+ sqlFormatterShortcutDuplicateLine: "複製目前行",
+ sqlFormatterShortcutDeleteLine: "刪除目前行",
+ sqlFormatterShortcutMoveLine: "移動行",
+ sqlFormatterShortcutCopyLine: "複製行",
+ sqlFormatterShortcutFormatJson: "格式化 JSON",
+ sqlFormatterShortcutApply: "套用設定",
+ sqlFormatterConfigErrorInvalidJson: "JSON 無效。",
+ sqlFormatterConfigErrorObject: "設定必須是 JSON 物件。",
+ sqlFormatterConfigErrorVersion: "不支援的設定版本。",
+ sqlFormatterConfigErrorFormatter: "不支援的格式化器。",
+ sqlFormatterConfigErrorOptionsObject: "設定選項必須是 JSON 物件。",
+ sqlFormatterConfigErrorUnknownOption: "未知格式化選項:{option}。",
+ sqlFormatterConfigErrorInvalidOptionValue: "「{option}」的值無效。",
+ sqlFormatterConfigErrorInvalidConfig: "格式化設定無效。",
appearanceTab: "外觀",
navigationTab: "導覽",
redisTab: "Redis",
diff --git a/apps/desktop/src/lib/sqlFormatter.ts b/apps/desktop/src/lib/sqlFormatter.ts
index 18214751ce..d54147dd77 100644
--- a/apps/desktop/src/lib/sqlFormatter.ts
+++ b/apps/desktop/src/lib/sqlFormatter.ts
@@ -1,7 +1,13 @@
-import { format } from "sql-formatter";
+import {
+ DEFAULT_SQL_FORMATTER_SETTINGS,
+ sqlFormatterOptions,
+ type SqlFormatterSettings,
+} from "@/lib/sqlFormatterConfig";
export type SqlFormatDialect = "mysql" | "postgres" | "sqlite" | "sqlserver" | "generic";
+export const MAX_SQL_FORMAT_CHARS = 1_000_000;
+
function formatterLanguage(dialect: SqlFormatDialect) {
switch (dialect) {
case "mysql":
@@ -17,10 +23,19 @@ function formatterLanguage(dialect: SqlFormatDialect) {
}
}
-export async function formatSqlText(sql: string, dialect: SqlFormatDialect = "generic"): Promise<string> {
+export async function formatSqlText(
+ sql: string,
+ dialect: SqlFormatDialect = "generic",
+ settings: SqlFormatterSettings = DEFAULT_SQL_FORMATTER_SETTINGS,
+): Promise<string> {
if (!sql.trim()) return sql;
+ if (sql.length > MAX_SQL_FORMAT_CHARS) {
+ throw new Error("SQL is too large to format safely.");
+ }
+
+ const { format } = await import("sql-formatter");
return format(sql, {
language: formatterLanguage(dialect),
- keywordCase: "upper",
+ ...sqlFormatterOptions(settings),
});
}
diff --git a/apps/desktop/src/lib/sqlFormatterConfig.ts b/apps/desktop/src/lib/sqlFormatterConfig.ts
new file mode 100644
index 0000000000..005b0a5c33
--- /dev/null
+++ b/apps/desktop/src/lib/sqlFormatterConfig.ts
@@ -0,0 +1,195 @@
+export const SQL_FORMATTER_CONFIG_VERSION = 1;
+export const SQL_FORMATTER_CONFIG_FORMATTER = "sql-formatter";
+
+const CASE_VALUES = ["preserve", "upper", "lower"] as const;
+const LOGICAL_OPERATOR_NEWLINE_VALUES = ["before", "after"] as const;
+const TAB_WIDTH_VALUES = [2, 4] as const;
+const EXPRESSION_WIDTH_VALUES = [50, 80, 120] as const;
+const LINES_BETWEEN_QUERIES_VALUES = [0, 1, 2] as const;
+
+export type SqlFormatterCase = (typeof CASE_VALUES)[number];
+export type SqlFormatterLogicalOperatorNewline = (typeof LOGICAL_OPERATOR_NEWLINE_VALUES)[number];
+export type SqlFormatterTabWidth = (typeof TAB_WIDTH_VALUES)[number];
+export type SqlFormatterExpressionWidth = (typeof EXPRESSION_WIDTH_VALUES)[number];
+export type SqlFormatterLinesBetweenQueries = (typeof LINES_BETWEEN_QUERIES_VALUES)[number];
+
+export interface SqlFormatterSettings {
+ keywordCase: SqlFormatterCase;
+ dataTypeCase: SqlFormatterCase;
+ functionCase: SqlFormatterCase;
+ useTabs: boolean;
+ tabWidth: SqlFormatterTabWidth;
+ logicalOperatorNewline: SqlFormatterLogicalOperatorNewline;
+ expressionWidth: SqlFormatterExpressionWidth;
+ linesBetweenQueries: SqlFormatterLinesBetweenQueries;
+ denseOperators: boolean;
+ newlineBeforeSemicolon: boolean;
+}
+
+export interface SqlFormatterConfigFile {
+ version: typeof SQL_FORMATTER_CONFIG_VERSION;
+ formatter: typeof SQL_FORMATTER_CONFIG_FORMATTER;
+ options: SqlFormatterSettings;
+}
+
+export type SqlFormatterConfigParseResult =
+ | { ok: true; settings: SqlFormatterSettings }
+ | { ok: false; message: string };
+
+export const DEFAULT_SQL_FORMATTER_SETTINGS: SqlFormatterSettings = {
+ keywordCase: "upper",
+ dataTypeCase: "preserve",
+ functionCase: "preserve",
+ useTabs: false,
+ tabWidth: 2,
+ logicalOperatorNewline: "before",
+ expressionWidth: 50,
+ linesBetweenQueries: 1,
+ denseOperators: false,
+ newlineBeforeSemicolon: false,
+};
+
+const SQL_FORMATTER_OPTION_KEYS = new Set<keyof SqlFormatterSettings>([
+ "keywordCase",
+ "dataTypeCase",
+ "functionCase",
+ "useTabs",
+ "tabWidth",
+ "logicalOperatorNewline",
+ "expressionWidth",
+ "linesBetweenQueries",
+ "denseOperators",
+ "newlineBeforeSemicolon",
+]);
+
+const SQL_FORMATTER_OPTION_VALIDATORS: Record<keyof SqlFormatterSettings, (value: unknown) => boolean> = {
+ keywordCase: (value) => isStringChoice(value, CASE_VALUES),
+ dataTypeCase: (value) => isStringChoice(value, CASE_VALUES),
+ functionCase: (value) => isStringChoice(value, CASE_VALUES),
+ useTabs: (value) => typeof value === "boolean",
+ tabWidth: (value) => isNumberChoice(value, TAB_WIDTH_VALUES),
+ logicalOperatorNewline: (value) => isStringChoice(value, LOGICAL_OPERATOR_NEWLINE_VALUES),
+ expressionWidth: (value) => isNumberChoice(value, EXPRESSION_WIDTH_VALUES),
+ linesBetweenQueries: (value) => isNumberChoice(value, LINES_BETWEEN_QUERIES_VALUES),
+ denseOperators: (value) => typeof value === "boolean",
+ newlineBeforeSemicolon: (value) => typeof value === "boolean",
+};
+
+function isObject(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === "object" && !Array.isArray(value);
+}
+
+function isStringChoice(value: unknown, values: readonly string[]): boolean {
+ return typeof value === "string" && values.includes(value);
+}
+
+function isNumberChoice(value: unknown, values: readonly number[]): boolean {
+ return typeof value === "number" && values.includes(value);
+}
+
+function normalizeChoice<T extends readonly string[]>(value: unknown, values: T, fallback: T[number]): T[number] {
+ return typeof value === "string" && values.includes(value) ? value : fallback;
+}
+
+function normalizeNumberChoice<T extends readonly number[]>(value: unknown, values: T, fallback: T[number]): T[number] {
+ return typeof value === "number" && values.includes(value) ? value : fallback;
+}
+
+function normalizeBoolean(value: unknown, fallback: boolean): boolean {
+ return typeof value === "boolean" ? value : fallback;
+}
+
+export function normalizeSqlFormatterSettings(value: unknown): SqlFormatterSettings {
+ const input = isObject(value) ? value : {};
+ return {
+ keywordCase: normalizeChoice(input.keywordCase, CASE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.keywordCase),
+ dataTypeCase: normalizeChoice(input.dataTypeCase, CASE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.dataTypeCase),
+ functionCase: normalizeChoice(input.functionCase, CASE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.functionCase),
+ useTabs: normalizeBoolean(input.useTabs, DEFAULT_SQL_FORMATTER_SETTINGS.useTabs),
+ tabWidth: normalizeNumberChoice(input.tabWidth, TAB_WIDTH_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.tabWidth),
+ logicalOperatorNewline: normalizeChoice(
+ input.logicalOperatorNewline,
+ LOGICAL_OPERATOR_NEWLINE_VALUES,
+ DEFAULT_SQL_FORMATTER_SETTINGS.logicalOperatorNewline,
+ ),
+ expressionWidth: normalizeNumberChoice(
+ input.expressionWidth,
+ EXPRESSION_WIDTH_VALUES,
+ DEFAULT_SQL_FORMATTER_SETTINGS.expressionWidth,
+ ),
+ linesBetweenQueries: normalizeNumberChoice(
+ input.linesBetweenQueries,
+ LINES_BETWEEN_QUERIES_VALUES,
+ DEFAULT_SQL_FORMATTER_SETTINGS.linesBetweenQueries,
+ ),
+ denseOperators: normalizeBoolean(input.denseOperators, DEFAULT_SQL_FORMATTER_SETTINGS.denseOperators),
+ newlineBeforeSemicolon: normalizeBoolean(
+ input.newlineBeforeSemicolon,
+ DEFAULT_SQL_FORMATTER_SETTINGS.newlineBeforeSemicolon,
+ ),
+ };
+}
+
+export function sqlFormatterConfigFile(settings: unknown): SqlFormatterConfigFile {
+ return {
+ version: SQL_FORMATTER_CONFIG_VERSION,
+ formatter: SQL_FORMATTER_CONFIG_FORMATTER,
+ options: normalizeSqlFormatterSettings(settings),
+ };
+}
+
+export function serializeSqlFormatterConfig(settings: unknown): string {
+ return JSON.stringify(sqlFormatterConfigFile(settings), null, 2);
+}
+
+export function parseSqlFormatterConfig(text: string): SqlFormatterConfigParseResult {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ return { ok: false, message: "Invalid JSON." };
+ }
+
+ if (!isObject(parsed)) return { ok: false, message: "Config must be a JSON object." };
+ if (parsed.version !== SQL_FORMATTER_CONFIG_VERSION) return { ok: false, message: "Unsupported config version." };
+ if (parsed.formatter !== SQL_FORMATTER_CONFIG_FORMATTER) return { ok: false, message: "Unsupported formatter." };
+ if (!isObject(parsed.options)) return { ok: false, message: "Config options must be a JSON object." };
+
+ const unknownOption = Object.keys(parsed.options).find(
+ (key) => !SQL_FORMATTER_OPTION_KEYS.has(key as keyof SqlFormatterSettings),
+ );
+ if (unknownOption) return { ok: false, message: `Unknown formatter option: ${unknownOption}.` };
+
+ const invalidOption = Object.entries(parsed.options).find(([key, value]) => {
+ const optionKey = key as keyof SqlFormatterSettings;
+ return !SQL_FORMATTER_OPTION_VALIDATORS[optionKey](value);
+ });
+ if (invalidOption) return { ok: false, message: `Invalid formatter option value: ${invalidOption[0]}.` };
+
+ return { ok: true, settings: normalizeSqlFormatterSettings(parsed.options) };
+}
+
+export function syncSqlFormatterConfigDraft(
+ text: string,
+ syncSettings: (settings: SqlFormatterSettings) => void,
+): SqlFormatterConfigParseResult {
+ const result = parseSqlFormatterConfig(text);
+ if (result.ok) syncSettings(result.settings);
+ return result;
+}
+
+export function sqlFormatterOptions(settings: unknown) {
+ const normalized = normalizeSqlFormatterSettings(settings);
+ return {
+ keywordCase: normalized.keywordCase,
+ dataTypeCase: normalized.dataTypeCase,
+ functionCase: normalized.functionCase,
+ useTabs: normalized.useTabs,
+ tabWidth: normalized.tabWidth,
+ logicalOperatorNewline: normalized.logicalOperatorNewline,
+ expressionWidth: normalized.expressionWidth,
+ linesBetweenQueries: normalized.linesBetweenQueries,
+ denseOperators: normalized.denseOperators,
+ newlineBeforeSemicolon: normalized.newlineBeforeSemicolon,
+ };
+}
diff --git a/apps/desktop/src/lib/sqlFormatterConfigEditor.ts b/apps/desktop/src/lib/sqlFormatterConfigEditor.ts
new file mode 100644
index 0000000000..79ae56afc0
--- /dev/null
+++ b/apps/desktop/src/lib/sqlFormatterConfigEditor.ts
@@ -0,0 +1,79 @@
+import type { Command, KeyBinding } from "@codemirror/view";
+
+export interface SqlFormatterConfigEditorCommands {
+ indentMore: Command;
+ indentLess: Command;
+ copyLineDown: Command;
+ copyLineUp: Command;
+ deleteLine: Command;
+ moveLineUp: Command;
+ moveLineDown: Command;
+ openSearchPanel: Command;
+}
+
+export interface SqlFormatterConfigEditorActions {
+ apply: Command;
+ formatJson: Command;
+}
+
+export function createSqlFormatterConfigKeymap(
+ commands: SqlFormatterConfigEditorCommands,
+ actions: SqlFormatterConfigEditorActions,
+): KeyBinding[] {
+ return [
+ { key: "Tab", run: commands.indentMore },
+ { key: "Shift-Tab", run: commands.indentLess },
+ { key: "Mod-d", run: commands.copyLineDown },
+ { key: "Shift-Mod-k", run: commands.deleteLine },
+ { key: "Alt-ArrowUp", run: commands.moveLineUp },
+ { key: "Alt-ArrowDown", run: commands.moveLineDown },
+ { key: "Shift-Alt-ArrowUp", run: commands.copyLineUp },
+ { key: "Shift-Alt-ArrowDown", run: commands.copyLineDown },
+ { key: "Ctrl-h", mac: "Mod-Alt-f", run: commands.openSearchPanel, preventDefault: true },
+ { key: "Shift-Alt-f", mac: "Shift-Mod-f", run: actions.formatJson, preventDefault: true },
+ { key: "Mod-s", run: actions.apply, preventDefault: true },
+ ];
+}
+
+export interface SqlFormatterConfigShortcutRow {
+ id: string;
+ labelKey: string;
+ shortcut: string;
+}
+
+function modLabel(platform = globalThis.navigator?.platform || ""): "Cmd" | "Ctrl" {
+ return platform.toLowerCase().includes("mac") ? "Cmd" : "Ctrl";
+}
+
+function altLabel(platform = globalThis.navigator?.platform || ""): "Option" | "Alt" {
+ return platform.toLowerCase().includes("mac") ? "Option" : "Alt";
+}
+
+export function sqlFormatterConfigShortcutRows(
+ platform = globalThis.navigator?.platform || "",
+): SqlFormatterConfigShortcutRow[] {
+ const isMac = platform.toLowerCase().includes("mac");
+ const mod = modLabel(platform);
+ const alt = altLabel(platform);
+
+ return [
+ { id: "find", labelKey: "settings.sqlFormatterShortcutFind", shortcut: `${mod}+F` },
+ {
+ id: "replace",
+ labelKey: "settings.sqlFormatterShortcutReplace",
+ shortcut: isMac ? "Cmd+Option+F" : "Ctrl+H",
+ },
+ { id: "indentMore", labelKey: "settings.sqlFormatterShortcutIndentMore", shortcut: "Tab" },
+ { id: "indentLess", labelKey: "settings.sqlFormatterShortcutIndentLess", shortcut: "Shift+Tab" },
+ { id: "duplicateLine", labelKey: "settings.sqlFormatterShortcutDuplicateLine", shortcut: `${mod}+D` },
+ { id: "deleteLine", labelKey: "settings.sqlFormatterShortcutDeleteLine", shortcut: `${mod}+Shift+K` },
+ { id: "moveLine", labelKey: "settings.sqlFormatterShortcutMoveLine", shortcut: `${alt}+Up/Down` },
+ { id: "copyLine", labelKey: "settings.sqlFormatterShortcutCopyLine", shortcut: `Shift+${alt}+Up/Down` },
+ {
+ id: "formatJson",
+ labelKey: "settings.sqlFormatterShortcutFormatJson",
+ shortcut: isMac ? "Shift+Cmd+F" : "Shift+Alt+F",
+ },
+ { id: "apply", labelKey: "settings.sqlFormatterShortcutApply", shortcut: `${mod}+S` },
+ ];
+}
diff --git a/apps/desktop/src/stores/settingsStore.ts b/apps/desktop/src/stores/settingsStore.ts
index cf883ffc4d..e5e1f59c03 100644
--- a/apps/desktop/src/stores/settingsStore.ts
+++ b/apps/desktop/src/stores/settingsStore.ts
@@ -10,6 +10,11 @@ import {
import { normalizeShortcutSettings, type ShortcutSettings } from "@/lib/shortcutRegistry";
import { normalizeResultPageSize } from "@/lib/paginationPageSize";
import { normalizeSidebarHiddenTablePrefixes } from "@/lib/sidebarTableNameDisplay";
+import {
+ DEFAULT_SQL_FORMATTER_SETTINGS,
+ normalizeSqlFormatterSettings,
+ type SqlFormatterSettings,
+} from "@/lib/sqlFormatterConfig";
import type { SidebarActivation } from "@/lib/treeNodeClick";
import type { SqlSnippet } from "@/types/database";
import { DEFAULT_SQL_SNIPPETS } from "@/lib/sqlCompletion";
@@ -258,6 +263,7 @@ export interface EditorSettings {
cellDetailDrawerWidth: number;
cellDetailPanelLayout: CellDetailPanelLayout;
shortcuts: ShortcutSettings;
+ sqlFormatter: SqlFormatterSettings;
sidebarActivation: SidebarActivation;
sidebarObjectDisplay: "grouped" | "simple";
autoSelectActiveSidebarNode: boolean;
@@ -324,6 +330,7 @@ export const DEFAULT_EDITOR_SETTINGS: EditorSettings = {
cellDetailDrawerWidth: 320,
cellDetailPanelLayout: "bottom",
shortcuts: normalizeShortcutSettings(),
+ sqlFormatter: { ...DEFAULT_SQL_FORMATTER_SETTINGS },
sidebarActivation: "single",
sidebarObjectDisplay: "grouped",
autoSelectActiveSidebarNode: false,
@@ -489,6 +496,7 @@ export function normalizeEditorSettings(settings: Partial<EditorSettings>, exist
),
cellDetailPanelLayout: normalizeCellDetailPanelLayout(settings.cellDetailPanelLayout),
shortcuts: normalizeShortcutSettings(settings.shortcuts),
+ sqlFormatter: normalizeSqlFormatterSettings(settings.sqlFormatter),
sidebarActivation:
settings.sidebarActivation === "single" || settings.sidebarActivation === "double"
? settings.sidebarActivation
@@ -540,10 +548,7 @@ function loadEditorSettings(): EditorSettings {
if (oldSize) {
const parsed = parseInt(oldSize, 10);
if (!isNaN(parsed)) {
- const migrated: EditorSettings = {
- ...DEFAULT_EDITOR_SETTINGS,
- fontSize: parsed,
- };
+ const migrated = normalizeEditorSettings({ fontSize: parsed });
saveEditorSettings(migrated);
localStorage.removeItem(OLD_FONT_SIZE_KEY);
return migrated;
@@ -553,7 +558,7 @@ function loadEditorSettings(): EditorSettings {
/* ignore */
}
- return { ...DEFAULT_EDITOR_SETTINGS };
+ return normalizeEditorSettings({});
}
function saveEditorSettings(settings: EditorSettings) {
@@ -673,6 +678,8 @@ export const useSettingsStore = defineStore("settings", () => {
if (partial.cellDetailPanelLayout !== undefined)
editorSettings.value.cellDetailPanelLayout = normalizeCellDetailPanelLayout(partial.cellDetailPanelLayout);
if (partial.shortcuts !== undefined) editorSettings.value.shortcuts = normalizeShortcutSettings(partial.shortcuts);
+ if (partial.sqlFormatter !== undefined)
+ editorSettings.value.sqlFormatter = normalizeSqlFormatterSettings(partial.sqlFormatter);
if (partial.sidebarActivation !== undefined) editorSettings.value.sidebarActivation = partial.sidebarActivation;
if (partial.sidebarObjectDisplay !== undefined)
editorSettings.value.sidebarObjectDisplay = partial.sidebarObjectDisplay;
diff --git a/docs/superpowers/specs/2026-06-08-sql-formatter-config-design.md b/docs/superpowers/specs/2026-06-08-sql-formatter-config-design.md
new file mode 100644
index 0000000000..7d1a4d0a6e
--- /dev/null
+++ b/docs/superpowers/specs/2026-06-08-sql-formatter-config-design.md
@@ -0,0 +1,169 @@
+# SQL Formatter Configuration Design
+
+## Summary
+
+DBX will add a lightweight SQL formatter configuration experience. Users can tune formatter options in a settings window, import and export a small JSON configuration file, and use a capable JSON editor inside that window. The editor shortcuts are part of the configuration window experience only; they are not stored in the SQL formatter configuration file.
+
+## Goals
+
+- Let users customize SQL formatting without replacing the existing `sql-formatter` dependency.
+- Keep startup and idle memory low by loading formatter and advanced JSON editor code only when needed.
+- Support importing and exporting a dedicated SQL formatter configuration file.
+- Provide a comfortable JSON configuration editor in the SQL formatter settings window.
+- Make editor shortcuts work consistently on Windows, Linux, and macOS.
+- Validate imported configuration before applying it to stored editor settings.
+
+## Non-Goals
+
+- Do not introduce Monaco, Prettier, WASM parsers, or multiple formatter engines.
+- Do not turn this into a full editor profile export system.
+- Do not store configuration-window shortcuts in the SQL formatter configuration file.
+- Do not run SQL formatting automatically while typing.
+- Do not implement per-connection formatter profiles in the first version.
+
+## Current Context
+
+The current formatter path is intentionally small:
+
+- `apps/desktop/src/lib/sqlFormatter.ts` imports `format` from `sql-formatter`.
+- `formatSqlText(sql, dialect)` maps the DBX dialect to the formatter language.
+- The only current formatting option is `keywordCase: "upper"`.
+- `QueryEditor.vue` calls `formatSqlText()` only when the user triggers SQL formatting.
+- Editor settings already live in `settingsStore.editorSettings` and are persisted through `localStorage`.
+
+This design keeps that structure and adds a typed formatter settings object to the existing editor settings.
+
+## Configuration File
+
+The imported and exported file is a dedicated SQL formatter config:
+
+```json
+{
+ "version": 1,
+ "formatter": "sql-formatter",
+ "options": {
+ "keywordCase": "upper",
+ "functionCase": "preserve",
+ "dataTypeCase": "preserve",
+ "indentStyle": "spaces",
+ "tabWidth": 2,
+ "linesBetweenQueries": 1,
+ "expressionWidth": 80,
+ "semicolonNewline": false
+ }
+}
+```
+
+`version` enables future migrations. `formatter` must be `sql-formatter` in the first version. `options` contains only validated SQL formatter options. Unknown top-level fields are ignored during import. Unknown option fields are rejected with a validation message so users can find mistakes in hand-edited files.
+
+## Stored Settings
+
+Add `sqlFormatter` to `EditorSettings`:
+
+```ts
+interface SqlFormatterSettings {
+ keywordCase: "upper" | "lower" | "preserve";
+ functionCase: "upper" | "lower" | "preserve";
+ dataTypeCase: "upper" | "lower" | "preserve";
+ indentStyle: "spaces" | "tabs";
+ tabWidth: 2 | 4;
+ linesBetweenQueries: 0 | 1 | 2;
+ expressionWidth: 50 | 80 | 120;
+ semicolonNewline: boolean;
+}
+```
+
+Normalization clamps every field to a known value. Missing fields fall back to defaults. Existing users get the current behavior by default: uppercase keywords and two-space readable formatting.
+
+The exact mapping to `sql-formatter` options should be confirmed against the installed `[email protected]` type definitions during implementation. Unsupported options are hidden rather than simulated with fragile string rewriting.
+
+## Settings Window
+
+The SQL formatter settings window has two modes:
+
+- Form mode: select controls for common options such as keyword case, indentation, line spacing, and expression width.
+- Advanced JSON mode: a JSON editor for the same configuration envelope used by import and export.
+
+Both modes edit the same local draft. Applying settings normalizes and persists the draft. Canceling closes the dialog without touching stored settings.
+
+The window includes:
+
+- Import config
+- Export config
+- Restore defaults
+- Validate
+- Apply
+
+Import reads the file once, validates it, updates the local draft, and shows validation errors without applying partial invalid state. Export writes the normalized draft as pretty JSON.
+
+## JSON Editor Shortcuts
+
+The advanced JSON editor should reuse CodeMirror instead of adding a heavier editor. It supports common editing actions with platform-aware shortcuts:
+
+| Action | Windows/Linux | macOS |
+| --- | --- | --- |
+| Undo | `Ctrl+Z` | `Cmd+Z` |
+| Redo | `Ctrl+Y`, `Ctrl+Shift+Z` | `Cmd+Shift+Z` |
+| Find | `Ctrl+F` | `Cmd+F` |
+| Replace | `Ctrl+H` | `Cmd+Alt+F` or an in-window button |
+| Select all | `Ctrl+A` | `Cmd+A` |
+| Indent more | `Tab` | `Tab` |
+| Indent less | `Shift+Tab` | `Shift+Tab` |
+| Duplicate current line | `Ctrl+D` | `Cmd+D` |
+| Delete current line | `Ctrl+Shift+K` | `Cmd+Shift+K` |
+| Move line up/down | `Alt+Up/Down` | `Option+Up/Down` |
+| Copy line up/down | `Shift+Alt+Up/Down` | `Shift+Option+Up/Down` |
+| Format config JSON | `Shift+Alt+F` | `Shift+Option+F` |
+| Apply config | `Ctrl+S` | `Cmd+S` |
+
+Most of these actions come from CodeMirror's existing commands and keymaps. `Duplicate current line` can use `copyLineDown`. `Indent less` can use `indentLess`. The JSON editor uses platform-sensitive display labels, while the command mapping uses CodeMirror's `Mod` abstraction where appropriate.
+
+These shortcuts are local to the SQL formatter configuration window. They do not change the main SQL editor shortcut settings and are not written into exported formatter config files.
+
+## Low-Memory Strategy
+
+- Keep `sql-formatter` as the only SQL formatting engine.
+- Lazy-load `sql-formatter` when the user formats SQL or opens the formatter settings preview.
+- Lazy-load CodeMirror JSON support only when the user opens Advanced JSON mode.
+- Store only a small normalized settings object, not generated formatter state.
+- Format only on explicit user action.
+- Add a size guard for SQL text. Very large SQL should prompt before formatting or skip formatting with a clear message.
+- Avoid background workers in the first version unless formatting proves to block the UI on realistic input.
+
+## Data Flow
+
+1. User opens SQL formatter settings.
+2. The window copies `settingsStore.editorSettings.sqlFormatter` into a local draft.
+3. Form controls or JSON editor update the draft.
+4. Validation normalizes the draft and reports errors.
+5. Apply persists the normalized settings through `settingsStore.updateEditorSettings()`.
+6. SQL formatting calls `formatSqlText(sql, dialect, sqlFormatterSettings)`.
+7. `formatSqlText()` maps DBX settings to `sql-formatter` options and returns formatted SQL.
+
+## Error Handling
+
+- Blank SQL remains unchanged.
+- Invalid JSON in Advanced mode shows a local validation error and disables Apply.
+- Invalid imported files do not mutate stored settings.
+- Unsupported formatter names are rejected.
+- Unsupported option values are rejected with field-specific messages.
+- Formatter runtime errors keep the existing `formatError` event path and toast behavior.
+
+## Testing
+
+Add focused tests for:
+
+- Default SQL formatter settings preserve current formatting behavior.
+- Settings normalization clamps invalid values to defaults.
+- Exported config is stable and contains only allowed fields.
+- Imported config accepts valid files and rejects invalid files.
+- `formatSqlText()` maps settings to formatter options.
+- Blank SQL remains unchanged.
+- Advanced JSON editor keymap includes `Shift+Tab`, duplicate line, delete line, move line, copy line, and apply shortcuts.
+
+Manual verification should include:
+
+- Windows/Linux shortcut behavior using `Ctrl`.
+- macOS shortcut behavior using `Cmd`.
+- Import/export round trip.
+- No large formatter/editor code loaded before formatting or opening Advanced JSON mode, checked through the built bundle chunks.
diff --git a/packages/app-tests/settingsStore.test.ts b/packages/app-tests/settingsStore.test.ts
index 73b0922572..d75de82113 100644
--- a/packages/app-tests/settingsStore.test.ts
+++ b/packages/app-tests/settingsStore.test.ts
@@ -1,12 +1,49 @@
import { test } from "vitest";
import assert from "node:assert/strict";
+import { createPinia, setActivePinia } from "pinia";
+import { DEFAULT_SQL_FORMATTER_SETTINGS } from "../../apps/desktop/src/lib/sqlFormatterConfig.ts";
import {
AI_PROVIDER_PRESETS,
DEFAULT_EDITOR_SETTINGS,
normalizeAiConfig,
normalizeEditorSettings,
+ useSettingsStore,
} from "../../apps/desktop/src/stores/settingsStore.ts";
+const OLD_FONT_SIZE_KEY = "dbx-query-editor-font-size";
+
+function withMockLocalStorage(initial: Record<string, string>, run: () => void) {
+ const previousDescriptor = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
+ const values = new Map(Object.entries(initial));
+ const localStorageMock = {
+ getItem: (key: string) => values.get(key) ?? null,
+ setItem: (key: string, value: string) => {
+ values.set(key, value);
+ },
+ removeItem: (key: string) => {
+ values.delete(key);
+ },
+ clear: () => {
+ values.clear();
+ },
+ };
+
+ Object.defineProperty(globalThis, "localStorage", {
+ configurable: true,
+ value: localStorageMock,
+ });
+
+ try {
+ run();
+ } finally {
+ if (previousDescriptor) {
+ Object.defineProperty(globalThis, "localStorage", previousDescriptor);
+ } else {
+ delete (globalThis as any).localStorage;
+ }
+ }
+}
+
test("defaults Redis scan page size to 1000 keys", () => {
assert.equal(DEFAULT_EDITOR_SETTINGS.redisScanPageSize, 1000);
assert.equal(normalizeEditorSettings({}).redisScanPageSize, 1000);
@@ -266,3 +303,101 @@ test("normalizeEditorSettings clamps UI scale into the supported range", () => {
test("normalizeEditorSettings keeps valid UI scales with two-decimal precision", () => {
assert.equal(normalizeEditorSettings({ uiScale: 1.125 }).uiScale, 1.13);
});
+
+test("defaults SQL formatter settings", () => {
+ assert.deepEqual(DEFAULT_EDITOR_SETTINGS.sqlFormatter, {
+ keywordCase: "upper",
+ dataTypeCase: "preserve",
+ functionCase: "preserve",
+ useTabs: false,
+ tabWidth: 2,
+ logicalOperatorNewline: "before",
+ expressionWidth: 50,
+ linesBetweenQueries: 1,
+ denseOperators: false,
+ newlineBeforeSemicolon: false,
+ });
+ assert.deepEqual(normalizeEditorSettings({}).sqlFormatter, DEFAULT_EDITOR_SETTINGS.sqlFormatter);
+});
+
+test("normalizes saved SQL formatter settings", () => {
+ assert.deepEqual(
+ normalizeEditorSettings({
+ sqlFormatter: {
+ keywordCase: "lower",
+ functionCase: "upper",
+ dataTypeCase: "upper",
+ useTabs: true,
+ tabWidth: 4,
+ logicalOperatorNewline: "after",
+ expressionWidth: 120,
+ linesBetweenQueries: 2,
+ denseOperators: true,
+ newlineBeforeSemicolon: true,
+ },
+ } as any).sqlFormatter,
+ {
+ keywordCase: "lower",
+ functionCase: "upper",
+ dataTypeCase: "upper",
+ useTabs: true,
+ tabWidth: 4,
+ logicalOperatorNewline: "after",
+ expressionWidth: 120,
+ linesBetweenQueries: 2,
+ denseOperators: true,
+ newlineBeforeSemicolon: true,
+ },
+ );
+});
+
+test("keeps SQL formatter default objects distinct", () => {
+ const normalized = normalizeEditorSettings({});
+
+ assert.notEqual(DEFAULT_EDITOR_SETTINGS.sqlFormatter, DEFAULT_SQL_FORMATTER_SETTINGS);
+ assert.notEqual(normalized.sqlFormatter, DEFAULT_EDITOR_SETTINGS.sqlFormatter);
+ assert.notEqual(normalized.sqlFormatter, DEFAULT_SQL_FORMATTER_SETTINGS);
+});
+
+test("does not leak default-loaded SQL formatter mutations into defaults", () => {
+ withMockLocalStorage({}, () => {
+ setActivePinia(createPinia());
+ const store = useSettingsStore();
+ const editorDefaultKeywordCase = DEFAULT_EDITOR_SETTINGS.sqlFormatter.keywordCase;
+ const formatterDefaultKeywordCase = DEFAULT_SQL_FORMATTER_SETTINGS.keywordCase;
+
+ try {
+ store.editorSettings.sqlFormatter.keywordCase = "lower";
+
+ assert.notEqual(store.editorSettings.sqlFormatter, DEFAULT_EDITOR_SETTINGS.sqlFormatter);
+ assert.notEqual(store.editorSettings.sqlFormatter, DEFAULT_SQL_FORMATTER_SETTINGS);
+ assert.equal(DEFAULT_EDITOR_SETTINGS.sqlFormatter.keywordCase, editorDefaultKeywordCase);
+ assert.equal(DEFAULT_SQL_FORMATTER_SETTINGS.keywordCase, formatterDefaultKeywordCase);
+ } finally {
+ DEFAULT_EDITOR_SETTINGS.sqlFormatter.keywordCase = editorDefaultKeywordCase;
+ DEFAULT_SQL_FORMATTER_SETTINGS.keywordCase = formatterDefaultKeywordCase;
+ }
+ });
+});
+
+test("does not leak migrated SQL formatter mutations into defaults", () => {
+ withMockLocalStorage({ [OLD_FONT_SIZE_KEY]: "18" }, () => {
+ setActivePinia(createPinia());
+ const store = useSettingsStore();
+ const editorDefaultKeywordCase = DEFAULT_EDITOR_SETTINGS.sqlFormatter.keywordCase;
+ const formatterDefaultKeywordCase = DEFAULT_SQL_FORMATTER_SETTINGS.keywordCase;
+
+ try {
+ assert.equal(store.editorSettings.fontSize, 18);
+ store.editorSettings.sqlFormatter.keywordCase = "lower";
+
+ assert.notEqual(store.editorSettings.sqlFormatter, DEFAULT_EDITOR_SETTINGS.sqlFormatter);
+ assert.notEqual(store.editorSettings.sqlFormatter, DEFAULT_SQL_FORMATTER_SETTINGS);
+ assert.equal(DEFAULT_EDITOR_SETTINGS.sqlFormatter.keywordCase, editorDefaultKeywordCase);
+ assert.equal(DEFAULT_SQL_FORMATTER_SETTINGS.keywordCase, formatterDefaultKeywordCase);
+ } finally {
+ DEFAULT_EDITOR_SETTINGS.sqlFormatter.keywordCase = editorDefaultKeywordCase;
+ DEFAULT_SQL_FORMATTER_SETTINGS.keywordCase = formatterDefaultKeywordCase;
+ }
+ });
+});
diff --git a/packages/app-tests/sqlFormatter.test.ts b/packages/app-tests/sqlFormatter.test.ts
index fae9de2adf..9ab95ce142 100644
--- a/packages/app-tests/sqlFormatter.test.ts
+++ b/packages/app-tests/sqlFormatter.test.ts
@@ -1,8 +1,29 @@
import { strict as assert } from "node:assert";
-import { test } from "vitest";
-import { formatSqlText } from "../../apps/desktop/src/lib/sqlFormatter.ts";
+import { afterEach, test, vi } from "vitest";
+import { formatSqlText, MAX_SQL_FORMAT_CHARS } from "../../apps/desktop/src/lib/sqlFormatter.ts";
-test("formats SQL with uppercase keywords and readable line breaks", async () => {
+afterEach(() => {
+ vi.doUnmock("sql-formatter");
+});
+
+test("rejects very large SQL before importing formatter", async () => {
+ vi.resetModules();
+ vi.doMock("sql-formatter", () => {
+ throw new Error("formatter should not load");
+ });
+
+ const {
+ formatSqlText: isolatedFormatSqlText,
+ MAX_SQL_FORMAT_CHARS: isolatedMaxSqlFormatChars,
+ } = await import("../../apps/desktop/src/lib/sqlFormatter.ts");
+
+ await assert.rejects(
+ () => isolatedFormatSqlText("x".repeat(isolatedMaxSqlFormatChars + 1), "generic"),
+ /too large/i,
+ );
+});
+
+test("formats SQL with uppercase keywords and readable line breaks by default", async () => {
const formatted = await formatSqlText("select id, name from users where active = 1 order by name", "postgres");
assert.match(formatted, /^SELECT\b/);
@@ -11,6 +32,32 @@ test("formats SQL with uppercase keywords and readable line breaks", async () =>
assert.match(formatted, /\nORDER BY\b/);
});
+test("formats SQL with custom keyword case and indentation settings", async () => {
+ const formatted = await formatSqlText("select id from users where active = 1", "postgres", {
+ keywordCase: "lower",
+ dataTypeCase: "preserve",
+ functionCase: "preserve",
+ useTabs: true,
+ tabWidth: 2,
+ logicalOperatorNewline: "before",
+ expressionWidth: 50,
+ linesBetweenQueries: 1,
+ denseOperators: false,
+ newlineBeforeSemicolon: false,
+ });
+
+ assert.match(formatted, /^select\b/);
+ assert.match(formatted, /\nfrom\b/);
+ assert.doesNotMatch(formatted, /^SELECT\b/);
+});
+
test("leaves blank SQL unchanged", async () => {
assert.equal(await formatSqlText(" \n\t", "mysql"), " \n\t");
});
+
+test("rejects very large SQL before loading formatter work", async () => {
+ await assert.rejects(
+ () => formatSqlText("x".repeat(MAX_SQL_FORMAT_CHARS + 1), "generic"),
+ /too large/i,
+ );
+});
diff --git a/packages/app-tests/sqlFormatterConfig.test.ts b/packages/app-tests/sqlFormatterConfig.test.ts
new file mode 100644
index 0000000000..b01da62fa5
--- /dev/null
+++ b/packages/app-tests/sqlFormatterConfig.test.ts
@@ -0,0 +1,214 @@
+import assert from "node:assert/strict";
+import { test } from "vitest";
+import {
+ DEFAULT_SQL_FORMATTER_SETTINGS,
+ parseSqlFormatterConfig,
+ serializeSqlFormatterConfig,
+ normalizeSqlFormatterSettings,
+ syncSqlFormatterConfigDraft,
+ sqlFormatterOptions,
+} from "../../apps/desktop/src/lib/sqlFormatterConfig.ts";
+
+test("normalizes empty formatter settings to defaults", () => {
+ assert.deepEqual(normalizeSqlFormatterSettings({}), DEFAULT_SQL_FORMATTER_SETTINGS);
+});
+
+test("keeps valid formatter settings and clamps invalid values", () => {
+ const settings = normalizeSqlFormatterSettings({
+ keywordCase: "lower",
+ dataTypeCase: "upper",
+ functionCase: "lower",
+ useTabs: true,
+ tabWidth: 4,
+ logicalOperatorNewline: "after",
+ expressionWidth: 120,
+ linesBetweenQueries: 2,
+ denseOperators: true,
+ newlineBeforeSemicolon: true,
+ });
+
+ assert.deepEqual(settings, {
+ keywordCase: "lower",
+ dataTypeCase: "upper",
+ functionCase: "lower",
+ useTabs: true,
+ tabWidth: 4,
+ logicalOperatorNewline: "after",
+ expressionWidth: 120,
+ linesBetweenQueries: 2,
+ denseOperators: true,
+ newlineBeforeSemicolon: true,
+ });
+
+ assert.deepEqual(
+ normalizeSqlFormatterSettings({
+ keywordCase: "camel",
+ dataTypeCase: "invalid",
+ functionCase: "invalid",
+ useTabs: "yes",
+ tabWidth: 99,
+ logicalOperatorNewline: "middle",
+ expressionWidth: -1,
+ linesBetweenQueries: 9,
+ denseOperators: "true",
+ newlineBeforeSemicolon: "false",
+ }),
+ DEFAULT_SQL_FORMATTER_SETTINGS,
+ );
+});
+
+test("serializes formatter config as a stable versioned envelope", () => {
+ const json = serializeSqlFormatterConfig({
+ ...DEFAULT_SQL_FORMATTER_SETTINGS,
+ keywordCase: "lower",
+ });
+ assert.equal(
+ json,
+ JSON.stringify(
+ {
+ version: 1,
+ formatter: "sql-formatter",
+ options: {
+ ...DEFAULT_SQL_FORMATTER_SETTINGS,
+ keywordCase: "lower",
+ },
+ },
+ null,
+ 2,
+ ),
+ );
+});
+
+test("parses valid formatter config files", () => {
+ const result = parseSqlFormatterConfig(
+ JSON.stringify({
+ version: 1,
+ formatter: "sql-formatter",
+ ignoredTopLevelField: "ok",
+ options: {
+ keywordCase: "lower",
+ functionCase: "upper",
+ dataTypeCase: "preserve",
+ useTabs: false,
+ tabWidth: 4,
+ logicalOperatorNewline: "after",
+ expressionWidth: 80,
+ linesBetweenQueries: 0,
+ denseOperators: false,
+ newlineBeforeSemicolon: true,
+ },
+ }),
+ );
+
+ assert.equal(result.ok, true);
+ assert.deepEqual(result.settings, {
+ keywordCase: "lower",
+ functionCase: "upper",
+ dataTypeCase: "preserve",
+ useTabs: false,
+ tabWidth: 4,
+ logicalOperatorNewline: "after",
+ expressionWidth: 80,
+ linesBetweenQueries: 0,
+ denseOperators: false,
+ newlineBeforeSemicolon: true,
+ });
+});
+
+test("rejects malformed formatter config files", () => {
+ assert.deepEqual(parseSqlFormatterConfig("{bad json").ok, false);
+ assert.deepEqual(parseSqlFormatterConfig(JSON.stringify({ version: 2, formatter: "sql-formatter", options: {} })).ok, false);
+ assert.deepEqual(parseSqlFormatterConfig(JSON.stringify({ version: 1, formatter: "prettier", options: {} })).ok, false);
+ assert.deepEqual(
+ parseSqlFormatterConfig(JSON.stringify({ version: 1, formatter: "sql-formatter", options: { unknown: true } })).ok,
+ false,
+ );
+});
+
+test("rejects invalid known formatter option values when parsing config files", () => {
+ const invalidKeywordCase = parseSqlFormatterConfig(
+ JSON.stringify({ version: 1, formatter: "sql-formatter", options: { keywordCase: "camel" } }),
+ );
+ assert.equal(invalidKeywordCase.ok, false);
+ if (!invalidKeywordCase.ok) assert.match(invalidKeywordCase.message, /keywordCase/);
+
+ const invalidBoolean = parseSqlFormatterConfig(
+ JSON.stringify({ version: 1, formatter: "sql-formatter", options: { useTabs: "yes" } }),
+ );
+ assert.equal(invalidBoolean.ok, false);
+ if (!invalidBoolean.ok) assert.match(invalidBoolean.message, /useTabs/);
+
+ const invalidNumericChoice = parseSqlFormatterConfig(
+ JSON.stringify({ version: 1, formatter: "sql-formatter", options: { tabWidth: 3 } }),
+ );
+ assert.equal(invalidNumericChoice.ok, false);
+ if (!invalidNumericChoice.ok) assert.match(invalidNumericChoice.message, /tabWidth/);
+});
+
+test("syncs valid JSON drafts so outer settings apply can persist them", () => {
+ let synced = DEFAULT_SQL_FORMATTER_SETTINGS;
+ const result = syncSqlFormatterConfigDraft(
+ JSON.stringify({
+ version: 1,
+ formatter: "sql-formatter",
+ options: {
+ ...DEFAULT_SQL_FORMATTER_SETTINGS,
+ keywordCase: "lower",
+ tabWidth: 4,
+ },
+ }),
+ (settings) => {
+ synced = settings;
+ },
+ );
+
+ assert.equal(result.ok, true);
+ assert.deepEqual(synced, {
+ ...DEFAULT_SQL_FORMATTER_SETTINGS,
+ keywordCase: "lower",
+ tabWidth: 4,
+ });
+});
+
+test("does not sync invalid JSON drafts", () => {
+ let synced = DEFAULT_SQL_FORMATTER_SETTINGS;
+ const result = syncSqlFormatterConfigDraft(
+ JSON.stringify({
+ version: 1,
+ formatter: "sql-formatter",
+ options: {
+ ...DEFAULT_SQL_FORMATTER_SETTINGS,
+ keywordCase: "camel",
+ },
+ }),
+ (settings) => {
+ synced = settings;
+ },
+ );
+
+ assert.equal(result.ok, false);
+ assert.deepEqual(synced, DEFAULT_SQL_FORMATTER_SETTINGS);
+});
+
+test("maps DBX formatter settings to sql-formatter options", () => {
+ assert.deepEqual(
+ sqlFormatterOptions({
+ ...DEFAULT_SQL_FORMATTER_SETTINGS,
+ keywordCase: "lower",
+ useTabs: true,
+ newlineBeforeSemicolon: true,
+ }),
+ {
+ keywordCase: "lower",
+ dataTypeCase: "preserve",
+ functionCase: "preserve",
+ useTabs: true,
+ tabWidth: 2,
+ logicalOperatorNewline: "before",
+ expressionWidth: 50,
+ linesBetweenQueries: 1,
+ denseOperators: false,
+ newlineBeforeSemicolon: true,
+ },
+ );
+});
diff --git a/packages/app-tests/sqlFormatterConfigEditor.test.ts b/packages/app-tests/sqlFormatterConfigEditor.test.ts
new file mode 100644
index 0000000000..85af0cfcfc
--- /dev/null
+++ b/packages/app-tests/sqlFormatterConfigEditor.test.ts
@@ -0,0 +1,85 @@
+import assert from "node:assert/strict";
+import { test } from "vitest";
+import { createSqlFormatterConfigKeymap, sqlFormatterConfigShortcutRows } from "../../apps/desktop/src/lib/sqlFormatterConfigEditor.ts";
+
+const commands = {
+ indentMore: () => true,
+ indentLess: () => true,
+ copyLineDown: () => true,
+ copyLineUp: () => true,
+ deleteLine: () => true,
+ moveLineUp: () => true,
+ moveLineDown: () => true,
+ openSearchPanel: () => true,
+};
+const actions = {
+ apply: () => true,
+ formatJson: () => true,
+};
+const otherCommand = () => true;
+
+function createBindings() {
+ return createSqlFormatterConfigKeymap(commands, actions);
+}
+
+test("builds common SQL formatter config editor key bindings", () => {
+ const bindings = createBindings();
+
+ assert.deepEqual(
+ bindings.map((binding) => binding.key),
+ [
+ "Tab",
+ "Shift-Tab",
+ "Mod-d",
+ "Shift-Mod-k",
+ "Alt-ArrowUp",
+ "Alt-ArrowDown",
+ "Shift-Alt-ArrowUp",
+ "Shift-Alt-ArrowDown",
+ "Ctrl-h",
+ "Shift-Alt-f",
+ "Mod-s",
+ ],
+ );
+});
+
+test("sets search, format, and apply binding details", () => {
+ const bindings = createBindings();
+ const searchBinding = bindings.find((binding) => binding.key === "Ctrl-h");
+ const formatBinding = bindings.find((binding) => binding.key === "Shift-Alt-f");
+ const applyBinding = bindings.find((binding) => binding.key === "Mod-s");
+
+ assert.equal(searchBinding?.mac, "Mod-Alt-f");
+ assert.equal(searchBinding?.preventDefault, true);
+ assert.equal(searchBinding?.run, commands.openSearchPanel);
+ assert.equal(formatBinding?.mac, "Shift-Mod-f");
+ assert.equal(formatBinding?.preventDefault, true);
+ assert.equal(formatBinding?.run, actions.formatJson);
+ assert.equal(applyBinding?.preventDefault, true);
+ assert.equal(applyBinding?.run, actions.apply);
+});
+
+test("keeps duplicate line before later Mod-d search bindings", () => {
+ const bindings = [...createBindings(), { key: "Mod-d", run: otherCommand }];
+ const duplicateLineIndex = bindings.findIndex(
+ (binding) => binding.key === "Mod-d" && binding.run === commands.copyLineDown,
+ );
+ const searchKeymapIndex = bindings.findIndex((binding) => binding.key === "Mod-d" && binding.run === otherCommand);
+
+ assert.notEqual(duplicateLineIndex, -1);
+ assert.notEqual(searchKeymapIndex, -1);
+ assert.equal(bindings[duplicateLineIndex]?.run, commands.copyLineDown);
+ assert.ok(duplicateLineIndex < searchKeymapIndex);
+});
+
+test("shows platform-aware shortcut labels", () => {
+ const windowsRows = sqlFormatterConfigShortcutRows("Win32");
+ const macRows = sqlFormatterConfigShortcutRows("MacIntel");
+
+ assert.equal(windowsRows.find((row) => row.id === "duplicateLine")?.shortcut, "Ctrl+D");
+ assert.equal(macRows.find((row) => row.id === "duplicateLine")?.shortcut, "Cmd+D");
+ assert.equal(windowsRows.find((row) => row.id === "formatJson")?.shortcut, "Shift+Alt+F");
+ assert.equal(macRows.find((row) => row.id === "formatJson")?.shortcut, "Shift+Cmd+F");
+ assert.equal(windowsRows.find((row) => row.id === "apply")?.shortcut, "Ctrl+S");
+ assert.equal(macRows.find((row) => row.id === "apply")?.shortcut, "Cmd+S");
+});