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: 增加可配置 SQL 格式化规则 (#8570) (#12772)

efeire6c2b5ec8b28d
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue
index a0ce40757a..f9936228cf 100644
--- a/apps/desktop/src/components/editor/QueryEditor.vue
+++ b/apps/desktop/src/components/editor/QueryEditor.vue
@@ -71,7 +71,7 @@ import { statementNavigationTarget, type StatementNavigationDirection } from "@/
import { looksLikeDmlStatement } from "@/lib/sql/dmlChangePreview";
-import { canFormatSqlForDatabaseType, formatSqlText, compressSqlText } from "@/lib/sql/sqlFormatter";
+import { canFormatSqlForDatabaseType, formatSqlText, compressSqlText, type SqlFormatterDiagnostic } from "@/lib/sql/sqlFormatter";
import { applySqlKeywordCase, loadSqlKeywordSpans } from "@/lib/sql/sqlKeywordCase";
import { detectAndFormatStructured } from "@/lib/sql/autoFormat";
import { restoreSqlFromSourcePaste } from "@/lib/sql/sqlSourcePaste";
@@ -1768,6 +1768,7 @@ async function formatCurrentSql() {
try {
let formatted: string;
let formattedAsSql = false;
+ let formatDiagnostic: SqlFormatterDiagnostic | undefined;
if (props.databaseType === "mongodb") {
formatted = formatMongoShellText(source, settingsStore.editorSettings.sqlFormatter);
} else {
@@ -1796,13 +1797,16 @@ async function formatCurrentSql() {
// contract for format-on-save, which must never fail), which turned
// this command into a silent no-op. A thrown error reaches the
// `formatError` toast below.
- formatted = await formatSqlText(source, formatDialect, settingsStore.editorSettings.sqlFormatter);
+ formatted = await formatSqlText(source, formatDialect, settingsStore.editorSettings.sqlFormatter, (diagnostic) => {
+ formatDiagnostic = diagnostic;
+ });
}
}
}
if (view.value !== currentView || currentView.state !== originalState || currentView.state.sliceDoc(from, to) !== source) {
return;
}
+ if (formatDiagnostic === "custom-rules-fallback") toast(t("settings.sqlFormatterFallbackNotice"), 4000);
if (formatted === source) return;
// The semantic mapper's contract is SQL-only. Mongo shell, Elasticsearch,
// JSON, and XML keep the replacement selection behavior used before the
diff --git a/apps/desktop/src/components/editor/SqlFormatterSettingsPanel.vue b/apps/desktop/src/components/editor/SqlFormatterSettingsPanel.vue
index 8387e6f4b7..d85d5fb1fc 100644
--- a/apps/desktop/src/components/editor/SqlFormatterSettingsPanel.vue
+++ b/apps/desktop/src/components/editor/SqlFormatterSettingsPanel.vue
@@ -11,6 +11,7 @@ import { useToast } from "@/composables/useToast";
import { copyToClipboard } from "@/lib/common/clipboard";
import { saveTextFile } from "@/lib/export/saveTextFile";
import { searchKeymapWithoutModD } from "@/lib/editor/codemirrorSearchKeymap";
+import { formatSqlText, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
import {
DEFAULT_SQL_FORMATTER_SETTINGS,
SQL_FORMATTER_CONFIG_FORMATTER,
@@ -66,6 +67,15 @@ const jsonEditorReady = ref(false);
const jsonEditorLoadError = ref("");
const paramTypesDraft = ref("");
const focusedAdvancedOption = ref<"paramTypes" | null>(null);
+const previewSql = ref("SELECT id, name, created_at FROM users WHERE active = 1 AND role = 'admin';\n\nINSERT INTO users (id, name) VALUES (1, 'Ada');\n\nUPDATE users SET name = 'Ada', active = 1 WHERE id = 1;");
+const previewDialect = ref<SqlFormatDialect>("oracle");
+const previewResult = ref("");
+const previewError = ref("");
+const previewDiagnostic = ref(false);
+const previewStale = ref(false);
+const previewLoading = ref(false);
+let previewRequestId = 0;
+let previewTimer: ReturnType<typeof setTimeout> | undefined;
let cmView: EditorViewInstance | null = null;
let cmModules: CodeMirrorModules | null = null;
@@ -89,6 +99,7 @@ const commaPositionOptions: { value: SqlFormatterCommaPosition; labelKey: string
{ value: "after", labelKey: "settings.sqlFormatterCommaPositionAfter" },
{ value: "before", labelKey: "settings.sqlFormatterCommaPositionBefore" },
];
+const dmlCommaPositionOptions = [{ value: "inherit", labelKey: "settings.sqlFormatterRule_inherit" }, ...commaPositionOptions];
const fromClauseLayoutOptions: { value: SqlFormatterFromClauseLayout; labelKey: string }[] = [
{ value: "newLine", labelKey: "settings.sqlFormatterFromNewLine" },
@@ -107,7 +118,6 @@ const layoutStyleOptions: { value: SqlFormatterLayoutStyle; labelKey: string }[]
];
const tabWidthOptions: SqlFormatterTabWidth[] = [2, 4];
-const expressionWidthOptions: SqlFormatterExpressionWidth[] = [50, 80, 120];
const linesBetweenQueriesOptions: SqlFormatterLinesBetweenQueries[] = [0, 1, 2];
const sqlFormatterOptionLabelKeys: Record<keyof SqlFormatterOptionSettings, string> = {
layoutStyle: "settings.sqlFormatterLayoutStyle",
@@ -127,6 +137,23 @@ const sqlFormatterOptionLabelKeys: Record<keyof SqlFormatterOptionSettings, stri
denseOperators: "settings.sqlFormatterDenseOperators",
newlineBeforeSemicolon: "settings.sqlFormatterNewlineBeforeSemicolon",
paramTypes: "settings.sqlFormatterParamTypes",
+ customRulesEnabled: "settings.sqlFormatterCustomRules",
+ listLayout: "settings.sqlFormatterListLayout",
+ selectListLayout: "settings.sqlFormatterSelectListLayout",
+ insertListLayout: "settings.sqlFormatterInsertListLayout",
+ updateListLayout: "settings.sqlFormatterUpdateListLayout",
+ listItemAlignment: "settings.sqlFormatterListItemAlignment",
+ alignSelectAliases: "settings.sqlFormatterAlignSelectAliases",
+ alignUpdateAssignments: "settings.sqlFormatterAlignUpdateAssignments",
+ selectCommaPosition: "settings.sqlFormatterSelectCommaPosition",
+ insertCommaPosition: "settings.sqlFormatterInsertCommaPosition",
+ updateCommaPosition: "settings.sqlFormatterUpdateCommaPosition",
+ whereLogicalOperatorNewline: "settings.sqlFormatterWhereLogicalOperatorNewline",
+ onLogicalOperatorNewline: "settings.sqlFormatterOnLogicalOperatorNewline",
+ expressionLogicalOperatorNewline: "settings.sqlFormatterExpressionLogicalOperatorNewline",
+ newlineBeforeJoinOn: "settings.sqlFormatterNewlineBeforeJoinOn",
+ collapseShortStatements: "settings.sqlFormatterCollapseShortStatements",
+ emptyLineMode: "settings.sqlFormatterEmptyLineMode",
};
const sqlFormatterConfigErrorKeys: Record<string, string> = {
"Invalid JSON.": "settings.sqlFormatterConfigErrorInvalidJson",
@@ -231,8 +258,55 @@ function onTabWidth(value: any) {
function onExpressionWidth(value: any) {
const next = Number(value);
- if (next === 50 || next === 80 || next === 120) updateOption("expressionWidth", next);
+ if (Number.isInteger(next) && next >= 20 && next <= 500) updateOption("expressionWidth", next as SqlFormatterExpressionWidth);
+}
+
+const ruleEnums = {
+ layout: ["singleLine", "fit", "vertical", "wrap"],
+ layoutOverride: ["inherit", "singleLine", "fit", "vertical", "wrap"],
+ alignment: ["firstItem", "indent"],
+ logical: ["inherit", "before", "after", "none"],
+ empty: ["inherit", "remove", "single", "preserve"],
+} as const;
+const dmlCommaRules: { key: "selectCommaPosition" | "insertCommaPosition" | "updateCommaPosition"; titleKey: string }[] = [
+ { key: "selectCommaPosition", titleKey: "sqlFormatterSelectCommaPosition" },
+ { key: "insertCommaPosition", titleKey: "sqlFormatterInsertCommaPosition" },
+ { key: "updateCommaPosition", titleKey: "sqlFormatterUpdateCommaPosition" },
+];
+const dmlToggleRules: { key: "alignSelectAliases" | "alignUpdateAssignments" | "collapseShortStatements"; titleKey: string }[] = [
+ { key: "alignSelectAliases", titleKey: "sqlFormatterAlignSelectAliases" },
+ { key: "alignUpdateAssignments", titleKey: "sqlFormatterAlignUpdateAssignments" },
+ { key: "collapseShortStatements", titleKey: "sqlFormatterCollapseShortStatements" },
+];
+const conditionRules: { key: "whereLogicalOperatorNewline" | "onLogicalOperatorNewline" | "expressionLogicalOperatorNewline"; titleKey: string }[] = [
+ { key: "whereLogicalOperatorNewline", titleKey: "sqlFormatterWhereLogicalOperatorNewline" },
+ { key: "onLogicalOperatorNewline", titleKey: "sqlFormatterOnLogicalOperatorNewline" },
+ { key: "expressionLogicalOperatorNewline", titleKey: "sqlFormatterExpressionLogicalOperatorNewline" },
+];
+function schedulePreview() {
+ previewStale.value = !!previewResult.value;
+ if (previewTimer) clearTimeout(previewTimer);
+ const requestId = ++previewRequestId;
+ previewTimer = setTimeout(async () => {
+ previewLoading.value = true;
+ previewError.value = "";
+ let diagnostic: "custom-rules-fallback" | undefined;
+ try {
+ const result = await formatSqlText(previewSql.value, previewDialect.value, settings.value, (value) => (diagnostic = value));
+ if (requestId !== previewRequestId) return;
+ previewResult.value = result;
+ previewDiagnostic.value = diagnostic === "custom-rules-fallback";
+ previewStale.value = false;
+ } catch (error) {
+ if (requestId !== previewRequestId) return;
+ previewError.value = error instanceof Error ? error.message : String(error);
+ previewStale.value = !!previewResult.value;
+ } finally {
+ if (requestId === previewRequestId) previewLoading.value = false;
+ }
+ }, 180);
}
+watch([settings, previewSql, previewDialect], schedulePreview, { deep: true, immediate: true });
function onLinesBetweenQueries(value: any) {
const next = Number(value);
@@ -498,6 +572,8 @@ watch(
);
onBeforeUnmount(() => {
+ previewRequestId += 1;
+ if (previewTimer) clearTimeout(previewTimer);
destroyJsonEditor();
});
</script>
@@ -691,17 +767,8 @@ onBeforeUnmount(() => {
<div class="grid gap-4 md:grid-cols-2">
<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>
+ <Label for="sql-formatter-expression-width">{{ t("settings.sqlFormatterExpressionWidth") }}</Label>
+ <input id="sql-formatter-expression-width" type="number" min="20" max="500" step="1" :value="settings.expressionWidth" class="h-9 w-full rounded-md border border-input bg-background px-3" @change="onExpressionWidth(($event.target as HTMLInputElement).value)" />
</div>
<div class="space-y-2">
@@ -739,6 +806,101 @@ onBeforeUnmount(() => {
</div>
<div class="space-y-3 rounded-md border border-border/70 bg-muted/10 p-3">
+ <div class="flex items-center justify-between gap-3">
+ <Label for="sql-formatter-custom-rules">{{ t("settings.sqlFormatterCustomRules") }}</Label>
+ <Switch id="sql-formatter-custom-rules" :model-value="settings.customRulesEnabled" @update:model-value="(value: boolean) => updateOption('customRulesEnabled', value)" />
+ </div>
+ <p class="text-sm text-muted-foreground">{{ t("settings.sqlFormatterCustomRulesHint") }}</p>
+ <div v-if="settings.customRulesEnabled" class="grid gap-4">
+ <div class="grid gap-3 md:grid-cols-3">
+ <label class="space-y-1 text-sm"
+ >{{ t("settings.sqlFormatterListLayout")
+ }}<select class="h-9 w-full rounded-md border bg-background px-2" :value="settings.listLayout" @change="updateOption('listLayout', ($event.target as HTMLSelectElement).value as any)">
+ <option v-for="value in ruleEnums.layout" :key="value" :value="value">{{ t(`settings.sqlFormatterRule_${value}`) }}</option>
+ </select></label
+ >
+ <label class="space-y-1 text-sm"
+ >{{ t("settings.sqlFormatterSelectListLayout")
+ }}<select class="h-9 w-full rounded-md border bg-background px-2" :value="settings.selectListLayout" @change="updateOption('selectListLayout', ($event.target as HTMLSelectElement).value as any)">
+ <option v-for="value in ruleEnums.layoutOverride" :key="value" :value="value">{{ t(`settings.sqlFormatterRule_${value}`) }}</option>
+ </select></label
+ >
+ <label class="space-y-1 text-sm"
+ >{{ t("settings.sqlFormatterInsertListLayout")
+ }}<select class="h-9 w-full rounded-md border bg-background px-2" :value="settings.insertListLayout" @change="updateOption('insertListLayout', ($event.target as HTMLSelectElement).value as any)">
+ <option v-for="value in ruleEnums.layoutOverride" :key="value" :value="value">{{ t(`settings.sqlFormatterRule_${value}`) }}</option>
+ </select></label
+ >
+ <label class="space-y-1 text-sm"
+ >{{ t("settings.sqlFormatterUpdateListLayout")
+ }}<select class="h-9 w-full rounded-md border bg-background px-2" :value="settings.updateListLayout" @change="updateOption('updateListLayout', ($event.target as HTMLSelectElement).value as any)">
+ <option v-for="value in ruleEnums.layoutOverride" :key="value" :value="value">{{ t(`settings.sqlFormatterRule_${value}`) }}</option>
+ </select></label
+ >
+ <label class="space-y-1 text-sm"
+ >{{ t("settings.sqlFormatterListItemAlignment")
+ }}<select class="h-9 w-full rounded-md border bg-background px-2" :value="settings.listItemAlignment" @change="updateOption('listItemAlignment', ($event.target as HTMLSelectElement).value as any)">
+ <option v-for="value in ruleEnums.alignment" :key="value" :value="value">{{ t(`settings.sqlFormatterRule_${value}`) }}</option>
+ </select></label
+ >
+ <label class="space-y-1 text-sm"
+ >{{ t("settings.sqlFormatterEmptyLineMode")
+ }}<select class="h-9 w-full rounded-md border bg-background px-2" :value="settings.emptyLineMode" @change="updateOption('emptyLineMode', ($event.target as HTMLSelectElement).value as any)">
+ <option v-for="value in ruleEnums.empty" :key="value" :value="value">{{ t(`settings.sqlFormatterRule_${value}`) }}</option>
+ </select></label
+ >
+ </div>
+ <details class="space-y-3">
+ <summary class="cursor-pointer text-sm font-medium">{{ t("settings.sqlFormatterDmlRules") }}</summary>
+ <div class="grid gap-3 pt-2 md:grid-cols-3">
+ <label v-for="{ key, titleKey } in dmlCommaRules" :key="key" class="space-y-1 text-sm"
+ >{{ t(`settings.${titleKey}`)
+ }}<select class="h-9 w-full rounded-md border bg-background px-2" :value="settings[key]" @change="updateOption(key, ($event.target as HTMLSelectElement).value as any)">
+ <option v-for="option in dmlCommaPositionOptions" :key="option.value" :value="option.value">{{ t(option.labelKey) }}</option>
+ </select></label
+ >
+ <div v-for="{ key, titleKey } in dmlToggleRules" :key="key" class="flex items-center justify-between gap-3 rounded border px-3 py-2">
+ <Label :for="`sql-formatter-${key}`">{{ t(`settings.${titleKey}`) }}</Label
+ ><Switch :id="`sql-formatter-${key}`" :model-value="settings[key]" @update:model-value="(value: boolean) => updateOption(key, value as any)" />
+ </div>
+ </div>
+ </details>
+ <details class="space-y-3">
+ <summary class="cursor-pointer text-sm font-medium">{{ t("settings.sqlFormatterConditionRules") }}</summary>
+ <div class="grid gap-3 pt-2 md:grid-cols-2">
+ <label v-for="{ key, titleKey } in conditionRules" :key="key" class="space-y-1 text-sm"
+ >{{ t(`settings.${titleKey}`)
+ }}<select class="h-9 w-full rounded-md border bg-background px-2" :value="settings[key]" @change="updateOption(key, ($event.target as HTMLSelectElement).value as any)">
+ <option v-for="value in ruleEnums.logical" :key="value" :value="value">{{ t(`settings.sqlFormatterRule_${value}`) }}</option>
+ </select></label
+ >
+ <div class="flex items-center justify-between gap-3 rounded border px-3 py-2">
+ <Label for="sql-formatter-newline-before-join-on">{{ t("settings.sqlFormatterNewlineBeforeJoinOn") }}</Label
+ ><Switch id="sql-formatter-newline-before-join-on" :model-value="settings.newlineBeforeJoinOn" @update:model-value="(value: boolean) => updateOption('newlineBeforeJoinOn', value)" />
+ </div>
+ </div>
+ </details>
+ </div>
+ <div class="space-y-3 border-t pt-3">
+ <div class="flex items-center justify-between">
+ <h3 class="text-sm font-medium">{{ t("settings.sqlFormatterPreview") }}</h3>
+ <label class="text-sm"
+ >{{ t("settings.sqlFormatterPreviewDialect") }}
+ <select v-model="previewDialect" class="h-8 rounded border bg-background px-2">
+ <option value="oracle">Oracle</option>
+ <option value="postgres">PostgreSQL</option>
+ <option value="mysql">MySQL</option>
+ <option value="sqlserver">SQL Server</option>
+ </select></label
+ >
+ </div>
+ <textarea v-model="previewSql" :aria-label="t('settings.sqlFormatterPreviewSource')" class="min-h-28 w-full resize-y rounded-md border bg-background p-3 font-mono text-sm" spellcheck="false" />
+ <p v-if="previewError" role="alert" class="text-sm text-destructive">{{ t("settings.sqlFormatterPreviewFailed", { message: previewError }) }}</p>
+ <p v-if="previewDiagnostic" role="status" class="text-sm text-amber-700">{{ t("settings.sqlFormatterFallbackNotice") }}</p>
+ <p v-if="previewStale" class="text-sm text-amber-700">{{ t("settings.sqlFormatterPreviewStale") }}</p>
+ <p v-if="previewLoading" role="status" class="text-sm text-muted-foreground">{{ t("settings.sqlFormatterPreviewUpdating") }}</p>
+ <pre class="max-h-64 overflow-auto rounded-md border bg-background p-3 font-mono text-sm whitespace-pre-wrap">{{ previewResult }}</pre>
+ </div>
<div class="text-sm font-medium">{{ t("settings.sqlFormatterAdvancedOptions") }}</div>
<div class="space-y-2">
<Label for="sql-formatter-param-types">{{ t("settings.sqlFormatterParamTypes") }}</Label>
diff --git a/apps/desktop/src/components/editor/SqlPreviewPanel.vue b/apps/desktop/src/components/editor/SqlPreviewPanel.vue
index 3b6f78b032..8bce4934dc 100644
--- a/apps/desktop/src/components/editor/SqlPreviewPanel.vue
+++ b/apps/desktop/src/components/editor/SqlPreviewPanel.vue
@@ -132,8 +132,12 @@ async function toggleFormat() {
formatting.value = true;
try {
- formattedSql.value = await formatSqlText(props.sql, props.sqlFormatDialect ?? "generic", settingsStore.editorSettings.sqlFormatter);
+ let diagnostic: "custom-rules-fallback" | undefined;
+ formattedSql.value = await formatSqlText(props.sql, props.sqlFormatDialect ?? "generic", settingsStore.editorSettings.sqlFormatter, (value) => {
+ diagnostic = value;
+ });
isFormatted.value = true;
+ if (diagnostic === "custom-rules-fallback") toast(t("settings.sqlFormatterFallbackNotice"), 4000);
await highlightSql();
} catch {
toast(t("toolbar.formatSqlFailed"), 3000);
diff --git a/apps/desktop/src/components/editor/__tests__/QueryEditor.formatCompressRequestReplay.spec.ts b/apps/desktop/src/components/editor/__tests__/QueryEditor.formatCompressRequestReplay.spec.ts
index 66c8eb1405..8b3207497b 100644
--- a/apps/desktop/src/components/editor/__tests__/QueryEditor.formatCompressRequestReplay.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/QueryEditor.formatCompressRequestReplay.spec.ts
@@ -6,12 +6,16 @@ import { EditorView } from "@codemirror/view";
import { createPinia, setActivePinia } from "pinia";
import { createI18n } from "vue-i18n";
import { afterEach, describe, expect, it, vi } from "vitest";
+import { useSettingsStore } from "@/stores/settingsStore";
import QueryEditor from "@/components/editor/QueryEditor.vue";
-import { compressSqlText, formatSqlForEditing } from "@/lib/sql/sqlFormatter";
+import { compressSqlText, formatSqlForEditing, formatSqlText, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
import { DEFAULT_SQL_FORMATTER_SETTINGS } from "@/lib/sql/sqlFormatterConfig";
import type { DatabaseType } from "@/types/database";
+const mocks = vi.hoisted(() => ({ toast: vi.fn() }));
+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
+
// The request ids are per-kind global counters in App.vue, so ids keep
// increasing for the lifetime of the process. The module-scope replay cursor in
// QueryEditor.vue survives across the editor mounts in this file, so every test
@@ -38,9 +42,21 @@ type EditorState = {
const WAIT = { timeout: 5000, interval: 20 };
-function mountEditor(initial: { modelValue: string; tabId: string; databaseType?: DatabaseType; formatRequestId?: number; compressRequestId?: number; keywordCaseRequestId?: number; keywordCaseRequestMode?: "upper" | "lower" }) {
+function mountEditor(initial: {
+ modelValue: string;
+ tabId: string;
+ databaseType?: DatabaseType;
+ formatDialect?: SqlFormatDialect;
+ formatterSettings?: typeof DEFAULT_SQL_FORMATTER_SETTINGS;
+ formatRequestId?: number;
+ compressRequestId?: number;
+ keywordCaseRequestId?: number;
+ keywordCaseRequestMode?: "upper" | "lower";
+}) {
const pinia = createPinia();
setActivePinia(pinia);
+ const settings = useSettingsStore(pinia);
+ if (initial.formatterSettings) settings.editorSettings.sqlFormatter = initial.formatterSettings;
const state = reactive<EditorState>({
tabId: initial.tabId,
modelValue: initial.modelValue,
@@ -57,8 +73,8 @@ function mountEditor(initial: { modelValue: string; tabId: string; databaseType?
modelValue: state.modelValue,
tabId: state.tabId,
databaseType: initial.databaseType ?? "mysql",
- dialect: "mysql",
- formatDialect: "mysql",
+ dialect: initial.formatDialect ?? "mysql",
+ formatDialect: initial.formatDialect ?? "mysql",
autoFocus: false,
formatRequestId: state.formatRequestId,
compressRequestId: state.compressRequestId,
@@ -85,7 +101,7 @@ function mountEditor(initial: { modelValue: string; tabId: string; databaseType?
app.unmount();
host.remove();
});
- return { state, emits, formatErrors, host, unmount: () => app.unmount() };
+ return { state, emits, formatErrors, host, settings, unmount: () => app.unmount() };
}
async function waitForEditor(host: HTMLElement) {
@@ -106,6 +122,7 @@ async function settle() {
describe("QueryEditor format/compress request replay", () => {
afterEach(() => {
for (const cleanup of cleanups.splice(0)) cleanup();
+ mocks.toast.mockClear();
});
it("does not replay the stale compress/format requests when the ids re-arm after a tab switch", async () => {
@@ -209,9 +226,27 @@ describe("QueryEditor format/compress request replay", () => {
expect(editorView.state.selection.main.head).toBe(caret);
});
+ it("reports custom-rule fallback even when a procedure block already matches the base output", async () => {
+ const procedure =
+ "create or replace function department_label(p_id number) return varchar2 is\n v_id number;\n v_name varchar2(100);\nbegin\n select deptno,dname into v_id,v_name from dept where deptno=p_id and loc='Boston';\n v_name := trim(v_name);\n return v_name;\nexception when no_data_found then return 'unknown';\nend;";
+ const settings = { ...DEFAULT_SQL_FORMATTER_SETTINGS, layoutStyle: "classic" as const };
+ const baseFormatted = await formatSqlText(procedure, "oracle", settings);
+ const diagnostics: string[] = [];
+ expect(await formatSqlText(baseFormatted, "oracle", { ...settings, customRulesEnabled: true }, (value) => diagnostics.push(value))).toBe(baseFormatted);
+ expect(diagnostics).toEqual(["custom-rules-fallback"]);
+
+ const mounted = mountEditor({ modelValue: baseFormatted, tabId: "procedure-fallback", databaseType: "oracle", formatDialect: "oracle", formatterSettings: { ...settings, customRulesEnabled: true } });
+ await waitForEditor(mounted.host);
+
+ mounted.state.formatRequestId = 15;
+ await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith("settings.sqlFormatterFallbackNotice", 4000), WAIT);
+ expect(mounted.emits).toEqual([]);
+ expect(EditorView.findFromDOM(mounted.host.querySelector(".cm-editor") as HTMLElement)!.state.doc.toString()).toBe(baseFormatted);
+ });
+
it.each([
- ["forward", 0, COMPRESSED_SQL.length, 0, FORMATTED_SQL.length, 6],
- ["reverse", COMPRESSED_SQL.length, 0, FORMATTED_SQL.length, 0, 7],
+ ["forward", 0, COMPRESSED_SQL.length, 0, FORMATTED_SQL.length, 16],
+ ["reverse", COMPRESSED_SQL.length, 0, FORMATTED_SQL.length, 0, 17],
] as const)("keeps a %s formatted SQL selection complete and in its original direction", async (_direction, anchor, head, expectedAnchor, expectedHead, requestId) => {
const { state, emits, host } = mountEditor({ modelValue: COMPRESSED_SQL, tabId: "tab-a" });
await waitForEditor(host);
@@ -231,28 +266,28 @@ describe("QueryEditor format/compress request replay", () => {
databaseType: "mongodb",
source: 'db.items.find({name:"Ada",age:42});',
formatted: 'db.items.find({\n name: "Ada",\n age: 42\n});',
- requestId: 8,
+ requestId: 18,
},
{
name: "Elasticsearch request",
databaseType: "elasticsearch",
source: 'GET /items/_search {"query":{"match_all":{}}}',
formatted: 'GET /items/_search\n{\n "query": {\n "match_all": {}\n }\n}',
- requestId: 9,
+ requestId: 19,
},
{
name: "JSON",
databaseType: "mysql",
source: '{"name":"Ada","items":[1,2]}',
formatted: '{\n "name": "Ada",\n "items": [\n 1,\n 2\n ]\n}',
- requestId: 10,
+ requestId: 20,
},
{
name: "XML",
databaseType: "mysql",
source: '<root><item id="1"/><item id="2"/></root>',
formatted: '<root>\n <item id="1"/>\n <item id="2"/>\n</root>',
- requestId: 11,
+ requestId: 21,
},
] as const)("keeps the existing whole-document caret behavior for $name formatting", async ({ databaseType, source, formatted, requestId }) => {
const { state, emits, host } = mountEditor({ modelValue: source, tabId: "tab-a", databaseType });
@@ -275,7 +310,7 @@ describe("QueryEditor format/compress request replay", () => {
const editorView = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!;
editorView.dispatch({ selection: { anchor: source.length, head: 0 } });
- state.formatRequestId = 12;
+ state.formatRequestId = 22;
await vi.waitFor(() => expect(emits.at(-1)).toBe(formatted), WAIT);
expect(editorView.state.selection.main.anchor).toBe(0);
@@ -283,8 +318,8 @@ describe("QueryEditor format/compress request replay", () => {
});
it.each([
- ["whole document", false, 13],
- ["full selection", true, 14],
+ ["whole document", false, 23],
+ ["full selection", true, 24],
] as const)("formats MySQL view CASE/REPLACE calls through the %s toolbar request", async (_name, selectAll, requestId) => {
const source = "ALTER ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_format_repro` AS SELECT CASE WHEN 1 THEN REPLACE('a','a','b') END AS `结果`;";
const { state, emits, host } = mountEditor({ modelValue: source, tabId: "mysql-view" });
diff --git a/apps/desktop/src/components/editor/__tests__/SqlFormatterSettingsPanel.spec.ts b/apps/desktop/src/components/editor/__tests__/SqlFormatterSettingsPanel.spec.ts
new file mode 100644
index 0000000000..244bbb58db
--- /dev/null
+++ b/apps/desktop/src/components/editor/__tests__/SqlFormatterSettingsPanel.spec.ts
@@ -0,0 +1,222 @@
+// @vitest-environment happy-dom
+
+import { createApp, defineComponent, h, nextTick, type App } from "vue";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { DEFAULT_SQL_FORMATTER_SETTINGS, serializeSqlFormatterConfig } from "@/lib/sql/sqlFormatterConfig";
+import { formatSqlText } from "@/lib/sql/sqlFormatter";
+
+vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string, values?: Record<string, unknown>) => (values ? `${key}: ${values.option ?? values.message ?? ""}` : key) }) }));
+vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: vi.fn() }) }));
+vi.mock("@/lib/common/clipboard", () => ({ copyToClipboard: vi.fn() }));
+vi.mock("@/lib/export/saveTextFile", () => ({ saveTextFile: vi.fn() }));
+vi.mock("@/lib/editor/codemirrorSearchKeymap", () => ({ searchKeymapWithoutModD: vi.fn() }));
+vi.mock("@lucide/vue", async () => {
+ const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
+ const icon = createPassthroughStub("Icon", "i");
+ return { Upload: icon, Download: icon, RotateCcw: icon, WandSparkles: icon, Save: icon, Copy: icon };
+});
+vi.mock("@/components/ui/button", async () => ({ Button: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Button", "button") }));
+vi.mock("@/components/ui/label", async () => ({ Label: (await import("@/components/grid/__tests__/vueHostHarness")).createPassthroughStub("Label", "label") }));
+vi.mock("@/components/ui/select", async () => {
+ const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
+ const Select = defineComponent({
+ props: { modelValue: { type: [String, Number], default: "" } },
+ emits: ["update:modelValue"],
+ setup(_props, { emit, slots }) {
+ return () => h("div", { onPick: (event: CustomEvent<{ value: string }>) => emit("update:modelValue", event.detail.value) }, [slots.default?.()]);
+ },
+ });
+ return { Select, SelectContent: createPassthroughStub("SelectContent"), SelectItem: createPassthroughStub("SelectItem", "button"), SelectTrigger: createPassthroughStub("SelectTrigger", "button"), SelectValue: createPassthroughStub("SelectValue", "span") };
+});
+vi.mock("@/components/ui/switch", () => ({
+ Switch: defineComponent({
+ props: { id: String, modelValue: Boolean },
+ emits: ["update:modelValue"],
+ setup(props, { emit }) {
+ return () => h("input", { type: "checkbox", id: props.id, checked: props.modelValue, onChange: (event: Event) => emit("update:modelValue", (event.target as HTMLInputElement).checked) });
+ },
+ }),
+}));
+vi.mock("@/components/ui/tabs", async () => {
+ const { createPassthroughStub } = await import("@/components/grid/__tests__/vueHostHarness");
+ const Tabs = defineComponent({
+ props: { modelValue: String },
+ emits: ["update:modelValue"],
+ setup(_props, { emit, slots }) {
+ return () =>
+ h(
+ "div",
+ {
+ onClick: (event: MouseEvent) => {
+ const trigger = (event.target as HTMLElement).closest("button");
+ if (trigger?.textContent?.includes("settings.sqlFormatterJsonMode")) emit("update:modelValue", "json");
+ else if (trigger?.textContent?.includes("settings.sqlFormatterFormMode")) emit("update:modelValue", "form");
+ },
+ },
+ [slots.default?.()],
+ );
+ },
+ });
+ return { Tabs, TabsContent: createPassthroughStub("TabsContent"), TabsList: createPassthroughStub("TabsList"), TabsTrigger: createPassthroughStub("TabsTrigger", "button") };
+});
+
+import SqlFormatterSettingsPanel from "@/components/editor/SqlFormatterSettingsPanel.vue";
+
+describe("SQL formatter settings panel rules and preview", () => {
+ let app: App<Element> | null = null;
+ let host: HTMLDivElement | null = null;
+
+ function mountPanel(value = DEFAULT_SQL_FORMATTER_SETTINGS) {
+ const update = vi.fn();
+ host = document.createElement("div");
+ document.body.append(host);
+ app = createApp(SqlFormatterSettingsPanel, { modelValue: value, "onUpdate:modelValue": update });
+ app.mount(host);
+ return { root: host, update };
+ }
+
+ afterEach(() => {
+ vi.useRealTimers();
+ app?.unmount();
+ app = null;
+ host?.remove();
+ host = null;
+ });
+
+ it("emits real rule values and keeps them when the feature is switched off", async () => {
+ const current = { ...DEFAULT_SQL_FORMATTER_SETTINGS, selectListLayout: "wrap" as const, customRulesEnabled: true };
+ const { root, update } = mountPanel(current);
+ const selectLayout = Array.from(root.querySelectorAll("label"))
+ .find((label) => label.textContent?.includes("settings.sqlFormatterSelectListLayout"))
+ ?.querySelector("select");
+ expect(selectLayout).not.toBeNull();
+ selectLayout!.value = "fit";
+ selectLayout!.dispatchEvent(new Event("change", { bubbles: true }));
+ expect(update).toHaveBeenLastCalledWith({ ...current, selectListLayout: "fit" });
+
+ const enabled = root.querySelector<HTMLInputElement>("#sql-formatter-custom-rules")!;
+ enabled.checked = false;
+ enabled.dispatchEvent(new Event("change", { bubbles: true }));
+ expect(update).toHaveBeenLastCalledWith({ ...current, customRulesEnabled: false });
+ expect(selectLayout!.value).toBe("fit");
+ });
+
+ it("labels DML comma positions as comma placement and associates the width label", () => {
+ const { root } = mountPanel({ ...DEFAULT_SQL_FORMATTER_SETTINGS, customRulesEnabled: true });
+ const commaSelect = Array.from(root.querySelectorAll("label"))
+ .find((label) => label.textContent?.includes("settings.sqlFormatterSelectCommaPosition"))
+ ?.querySelector("select");
+ expect(Array.from(commaSelect!.options).map((option) => [option.value, option.textContent])).toEqual([
+ ["inherit", "settings.sqlFormatterRule_inherit"],
+ ["after", "settings.sqlFormatterCommaPositionAfter"],
+ ["before", "settings.sqlFormatterCommaPositionBefore"],
+ ]);
+ expect(root.querySelector('label[for="sql-formatter-expression-width"]')?.textContent).toBe("settings.sqlFormatterExpressionWidth");
+ expect(root.querySelector("#sql-formatter-expression-width")).not.toBeNull();
+ });
+
+ it("uses the new option label when JSON config contains an invalid rule value", async () => {
+ const { root, update } = mountPanel();
+ Array.from(root.querySelectorAll("button"))
+ .find((button) => button.textContent?.includes("settings.sqlFormatterJsonMode"))
+ ?.click();
+ await nextTick();
+ const config = JSON.parse(serializeSqlFormatterConfig(DEFAULT_SQL_FORMATTER_SETTINGS));
+ config.options.selectListLayout = "invalid";
+ const jsonEditor = root.querySelector<HTMLTextAreaElement>("textarea:not([aria-label]):not(#sql-formatter-param-types)")!;
+ jsonEditor.value = JSON.stringify(config);
+ jsonEditor.dispatchEvent(new Event("input", { bubbles: true }));
+ await nextTick();
+
+ expect(root.textContent).toContain("settings.sqlFormatterConfigErrorInvalidOptionValue: settings.sqlFormatterSelectListLayout");
+ expect(update).not.toHaveBeenCalled();
+ });
+
+ it.each([20, 76, 500])("accepts expression width %i", async (width) => {
+ const { root, update } = mountPanel();
+ const input = root.querySelector<HTMLInputElement>('input[type="number"]')!;
+ input.value = String(width);
+ input.dispatchEvent(new Event("change", { bubbles: true }));
+ expect(update).toHaveBeenLastCalledWith({ ...DEFAULT_SQL_FORMATTER_SETTINGS, expressionWidth: width });
+ });
+
+ it.each([19, 501, 76.5])("does not emit out-of-range or fractional width %s", (width) => {
+ const { root, update } = mountPanel();
+ const input = root.querySelector<HTMLInputElement>('input[type="number"]')!;
+ input.value = String(width);
+ input.dispatchEvent(new Event("change", { bubbles: true }));
+ expect(update).not.toHaveBeenCalled();
+ });
+
+ it("previews through the production formatter and retains old output after an error, then recovers", async () => {
+ vi.useFakeTimers();
+ const { root } = mountPanel({ ...DEFAULT_SQL_FORMATTER_SETTINGS, customRulesEnabled: true, selectListLayout: "vertical" });
+ const source = root.querySelector<HTMLTextAreaElement>('textarea[aria-label="settings.sqlFormatterPreviewSource"]')!;
+ source.value = "SELECT id, name FROM users;";
+ source.dispatchEvent(new Event("input", { bubbles: true }));
+ await vi.advanceTimersByTimeAsync(200);
+ const expected = await formatSqlText(source.value, "oracle", { ...DEFAULT_SQL_FORMATTER_SETTINGS, customRulesEnabled: true, selectListLayout: "vertical" });
+ await nextTick();
+ expect(root.querySelector("pre")?.textContent).toBe(expected);
+
+ source.value = "<root/>";
+ source.dispatchEvent(new Event("input", { bubbles: true }));
+ await vi.advanceTimersByTimeAsync(200);
+ await nextTick();
+ expect(root.querySelector('[role="alert"]')?.textContent).toContain("settings.sqlFormatterPreviewFailed");
+ expect(root.querySelector("pre")?.textContent).toBe(expected);
+ expect(root.textContent).toContain("settings.sqlFormatterPreviewStale");
+
+ source.value = "SELECT 2 FROM dual;";
+ source.dispatchEvent(new Event("input", { bubbles: true }));
+ await vi.advanceTimersByTimeAsync(200);
+ await nextTick();
+ expect(root.querySelector("pre")?.textContent).toBe(await formatSqlText(source.value, "oracle", { ...DEFAULT_SQL_FORMATTER_SETTINGS, customRulesEnabled: true, selectListLayout: "vertical" }));
+ expect(root.querySelector('[role="alert"]')).toBeNull();
+ });
+
+ it("shows a fallback diagnostic for a procedure block and clears it after PostgreSQL SQL succeeds", async () => {
+ vi.useFakeTimers();
+ const { root } = mountPanel({ ...DEFAULT_SQL_FORMATTER_SETTINGS, customRulesEnabled: true, selectListLayout: "vertical" });
+ const source = root.querySelector<HTMLTextAreaElement>('textarea[aria-label="settings.sqlFormatterPreviewSource"]')!;
+ const dialect = Array.from(root.querySelectorAll("select")).find((select) => Array.from(select.options).some((option) => option.value === "postgres"))!;
+ source.value = "BEGIN\n UPDATE users SET name = 'Ada' WHERE id = 1;\nEND;";
+ source.dispatchEvent(new Event("input", { bubbles: true }));
+ await vi.advanceTimersByTimeAsync(200);
+ await nextTick();
+ expect(root.querySelector('[role="status"]')?.textContent).toContain("settings.sqlFormatterFallbackNotice");
+
+ dialect.value = "postgres";
+ dialect.dispatchEvent(new Event("change", { bubbles: true }));
+ source.value = "SELECT id, name FROM users;";
+ source.dispatchEvent(new Event("input", { bubbles: true }));
+ await vi.advanceTimersByTimeAsync(200);
+ await nextTick();
+ const expected = await formatSqlText(source.value, "postgres", { ...DEFAULT_SQL_FORMATTER_SETTINGS, customRulesEnabled: true, selectListLayout: "vertical" });
+ expect(root.querySelector("pre")?.textContent).toBe(expected);
+ expect(root.querySelector('[role="status"]')).toBeNull();
+ });
+
+ it("takes only the latest scheduled preview and invalidates pending work on unmount", async () => {
+ vi.useFakeTimers();
+ const { root } = mountPanel();
+ const source = root.querySelector<HTMLTextAreaElement>('textarea[aria-label="settings.sqlFormatterPreviewSource"]')!;
+ source.value = "SELECT 1 FROM dual;";
+ source.dispatchEvent(new Event("input", { bubbles: true }));
+ // Start the first production formatter request at its async module boundary,
+ // then supersede it before the promise resolves.
+ vi.advanceTimersByTime(180);
+ source.value = "SELECT 2 FROM dual;";
+ source.dispatchEvent(new Event("input", { bubbles: true }));
+ await vi.advanceTimersByTimeAsync(200);
+ await nextTick();
+ expect(root.querySelector("pre")?.textContent).toBe(await formatSqlText(source.value, "oracle", DEFAULT_SQL_FORMATTER_SETTINGS));
+
+ source.value = "SELECT 3 FROM dual;";
+ source.dispatchEvent(new Event("input", { bubbles: true }));
+ app?.unmount();
+ app = null;
+ await vi.advanceTimersByTimeAsync(500);
+ expect(root.textContent).not.toContain("SELECT 3");
+ });
+});
diff --git a/apps/desktop/src/components/editor/__tests__/SqlPreviewPanel.spec.ts b/apps/desktop/src/components/editor/__tests__/SqlPreviewPanel.spec.ts
index 840d89f35f..9895af766f 100644
--- a/apps/desktop/src/components/editor/__tests__/SqlPreviewPanel.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/SqlPreviewPanel.spec.ts
@@ -7,12 +7,13 @@ const mocks = vi.hoisted(() => ({
highlight: vi.fn<(content: string) => string>(() => ""),
copyToClipboard: vi.fn<(_text: string) => Promise<void>>(async () => {}),
toast: vi.fn(),
+ formatterSettings: {} as Record<string, unknown>,
}));
vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
vi.mock("@/composables/useTheme", () => ({ useTheme: () => ({ isDark: { value: false } }) }));
vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
-vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => ({ editorSettings: { sqlFormatter: {} } }) }));
+vi.mock("@/stores/settingsStore", () => ({ useSettingsStore: () => ({ editorSettings: { sqlFormatter: mocks.formatterSettings } }) }));
vi.mock("@/lib/sql/sqlHighlighter", () => ({
createShikiSqlHighlighter: async () => (content: string) => mocks.highlight(content),
}));
@@ -47,6 +48,8 @@ vi.mock("@/components/ui/tooltip", async () => {
});
import SqlPreviewPanel from "@/components/editor/SqlPreviewPanel.vue";
+import { formatSqlText } from "@/lib/sql/sqlFormatter";
+import { DEFAULT_SQL_FORMATTER_SETTINGS } from "@/lib/sql/sqlFormatterConfig";
const SQL = "UPDATE users SET name = 'Ada' WHERE id = 1;";
@@ -60,10 +63,10 @@ async function flushUi() {
}
}
-async function mountPanel(sql = SQL) {
+async function mountPanel(sql = SQL, sqlFormatDialect = "generic") {
host = document.createElement("div");
document.body.append(host);
- app = createApp(SqlPreviewPanel, { sql });
+ app = createApp(SqlPreviewPanel, { sql, sqlFormatDialect });
app.mount(host);
await flushUi();
return host;
@@ -105,6 +108,7 @@ beforeEach(() => {
mocks.copyToClipboard.mockClear();
mocks.copyToClipboard.mockImplementation(async () => {});
mocks.toast.mockClear();
+ mocks.formatterSettings = {};
});
afterEach(() => {
@@ -173,6 +177,23 @@ describe("SqlPreviewPanel select all", () => {
});
});
+describe("SqlPreviewPanel formatter fallback", () => {
+ it("shows a fallback toast while retaining the production formatter's base output", async () => {
+ const sql =
+ "create or replace function department_label(p_id number) return varchar2 is\n v_id number;\n v_name varchar2(100);\nbegin\n select deptno,dname into v_id,v_name from dept where deptno=p_id and loc='Boston';\n v_name := trim(v_name);\n return v_name;\nexception when no_data_found then return 'unknown';\nend;";
+ const baseSettings = { ...DEFAULT_SQL_FORMATTER_SETTINGS, layoutStyle: "classic" as const };
+ const base = await formatSqlText(sql, "oracle", baseSettings);
+ mocks.formatterSettings = { ...baseSettings, customRulesEnabled: true };
+ const mounted = await mountPanel(sql, "oracle");
+
+ mounted.querySelector<HTMLButtonElement>('[aria-label="toolbar.formatSql"]')!.click();
+ await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith("settings.sqlFormatterFallbackNotice", 4000), { timeout: 5000 });
+ await flushUi();
+
+ expect(previewText(mounted).textContent).toBe(base);
+ });
+});
+
describe("SqlPreviewPanel copy", () => {
it("copies a Ctrl+A selection through the app clipboard instead of the unreliable native path", async () => {
const mounted = await mountPanel();
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 2c600ee7b3..48c7667aa0 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -7373,6 +7373,46 @@ export default withEnglishFallback({
sqlFormatterPreserveEmptyLines: "Boş sətirləri qoru",
sqlFormatterDenseOperators: "Sıx operatorlar",
sqlFormatterNewlineBeforeSemicolon: "Nöqtəli vergül yeni sətirdə",
+ sqlFormatterCustomRules: "Xüsusi SQL qaydaları",
+ sqlFormatterCustomRulesHint: "Aktiv olduqda xüsusi qayda düzülüşü işlədilir, söndürüldükdə seçilmiş əsas düzülüş bərpa olunur. Prosedur blokları əsas formatlaşdırmanı saxlayır.",
+ sqlFormatterListLayout: "Ümumi siyahı düzülüşü",
+ sqlFormatterSelectListLayout: "SELECT siyahısı",
+ sqlFormatterInsertListLayout: "INSERT siyahısı",
+ sqlFormatterUpdateListLayout: "UPDATE siyahısı",
+ sqlFormatterListItemAlignment: "Siyahı davamının düzülüşü",
+ sqlFormatterEmptyLineMode: "Boş sətirlər",
+ sqlFormatterDmlRules: "DML qaydaları",
+ sqlFormatterConditionRules: "Şərt qaydaları",
+ sqlFormatterSelectCommaPosition: "SELECT vergülü",
+ sqlFormatterInsertCommaPosition: "INSERT vergülü",
+ sqlFormatterUpdateCommaPosition: "UPDATE vergülü",
+ sqlFormatterAlignSelectAliases: "SELECT aliaslarını düzlə",
+ sqlFormatterAlignUpdateAssignments: "UPDATE təyinatlarını düzlə",
+ sqlFormatterCollapseShortStatements: "Qısa ifadələri birləşdir",
+ sqlFormatterWhereLogicalOperatorNewline: "WHERE məntiqi operatorları",
+ sqlFormatterOnLogicalOperatorNewline: "JOIN ON məntiqi operatorları",
+ sqlFormatterExpressionLogicalOperatorNewline: "Digər ifadələrin məntiqi operatorları",
+ sqlFormatterNewlineBeforeJoinOn: "JOIN ON-dan əvvəl yeni sətir",
+ sqlFormatterPreview: "Formatlama önbaxışı",
+ sqlFormatterPreviewDialect: "Dialekt",
+ sqlFormatterPreviewSource: "Önbaxış SQL-i",
+ sqlFormatterPreviewFailed: "Önbaxışı formatlamaq mümkün olmadı: {message}",
+ sqlFormatterPreviewStale: "Son uğurlu nəticə göstərilir. Önbaxışı yeniləmək üçün SQL-i düzəldin.",
+ sqlFormatterPreviewUpdating: "Önbaxış yenilənir…",
+ sqlFormatterRule_inherit: "Miras al",
+ sqlFormatterRule_singleLine: "Tək sətir",
+ sqlFormatterRule_fit: "Sığarsa tək sətir",
+ sqlFormatterRule_vertical: "Hər element ayrı sətirdə",
+ sqlFormatterRule_wrap: "Enə görə sətirə keçir",
+ sqlFormatterRule_firstItem: "İlk elementə düzlə",
+ sqlFormatterRule_indent: "Girintiyə düzlə",
+ sqlFormatterRule_before: "Operatordan əvvəl yeni sətir",
+ sqlFormatterRule_after: "Operatordan sonra yeni sətir",
+ sqlFormatterRule_none: "Məcburi sətirsonu yoxdur",
+ sqlFormatterRule_remove: "Sil",
+ sqlFormatterRule_single: "Bir boş sətirə endir",
+ sqlFormatterRule_preserve: "Saxla",
+ sqlFormatterFallbackNotice: "Xüsusi qaydalar bu girişə tətbiq edilmədi; əsas düzülüş istifadə olundu.",
sqlFormatterAdvancedOptions: "Əlavə seçimlər",
sqlFormatterParams: "Parametrlər",
sqlFormatterParamTypes: "Parametr növləri",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index c6f228fb8e..2d809c9f8e 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -8997,6 +8997,46 @@ export default {
sqlFormatterPreserveEmptyLines: "Preserve empty lines",
sqlFormatterDenseOperators: "Dense operators",
sqlFormatterNewlineBeforeSemicolon: "Semicolon on new line",
+ sqlFormatterCustomRules: "Custom SQL rules",
+ sqlFormatterCustomRulesHint: "Uses custom rule layout while enabled; disabling restores the selected base layout. Procedure blocks keep base formatting; select standalone SQL inside them to apply these rules.",
+ sqlFormatterListLayout: "General list layout",
+ sqlFormatterSelectListLayout: "SELECT list",
+ sqlFormatterInsertListLayout: "INSERT list",
+ sqlFormatterUpdateListLayout: "UPDATE list",
+ sqlFormatterListItemAlignment: "List continuation alignment",
+ sqlFormatterEmptyLineMode: "Blank lines",
+ sqlFormatterDmlRules: "DML rules",
+ sqlFormatterConditionRules: "Condition rules",
+ sqlFormatterSelectCommaPosition: "SELECT comma",
+ sqlFormatterInsertCommaPosition: "INSERT comma",
+ sqlFormatterUpdateCommaPosition: "UPDATE comma",
+ sqlFormatterAlignSelectAliases: "Align SELECT aliases",
+ sqlFormatterAlignUpdateAssignments: "Align UPDATE assignments",
+ sqlFormatterCollapseShortStatements: "Collapse short statements",
+ sqlFormatterWhereLogicalOperatorNewline: "WHERE logical operators",
+ sqlFormatterOnLogicalOperatorNewline: "JOIN ON logical operators",
+ sqlFormatterExpressionLogicalOperatorNewline: "Other expression logical operators",
+ sqlFormatterNewlineBeforeJoinOn: "Newline before JOIN ON",
+ sqlFormatterPreview: "Formatting preview",
+ sqlFormatterPreviewDialect: "Dialect",
+ sqlFormatterPreviewSource: "Preview SQL",
+ sqlFormatterPreviewFailed: "Could not format preview: {message}",
+ sqlFormatterPreviewStale: "Showing the last successful result. Fix the SQL to refresh the preview.",
+ sqlFormatterPreviewUpdating: "Updating preview…",
+ sqlFormatterRule_inherit: "Inherit",
+ sqlFormatterRule_singleLine: "Single line",
+ sqlFormatterRule_fit: "Single line when it fits",
+ sqlFormatterRule_vertical: "One item per line",
+ sqlFormatterRule_wrap: "Wrap to width",
+ sqlFormatterRule_firstItem: "Align to first item",
+ sqlFormatterRule_indent: "Align to indentation",
+ sqlFormatterRule_before: "Newline before operator",
+ sqlFormatterRule_after: "Newline after operator",
+ sqlFormatterRule_none: "No forced newline",
+ sqlFormatterRule_remove: "Remove",
+ sqlFormatterRule_single: "Collapse to one blank line",
+ sqlFormatterRule_preserve: "Preserve",
+ sqlFormatterFallbackNotice: "Custom rules were not applied to this input; the base layout was used.",
sqlFormatterAdvancedOptions: "Advanced options",
sqlFormatterParams: "Params",
sqlFormatterParamTypes: "Param types",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 0b4c0fd965..b239f30e78 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -8016,6 +8016,46 @@ export default withEnglishFallback({
sqlFormatterPreserveEmptyLines: "Conservar líneas vacías",
sqlFormatterDenseOperators: "Operadores compactos",
sqlFormatterNewlineBeforeSemicolon: "Punto y coma en nueva línea",
+ sqlFormatterCustomRules: "Reglas SQL personalizadas",
+ sqlFormatterCustomRulesHint: "Al activar esta opción se usa el diseño personalizado; al desactivarla se restaura el diseño base seleccionado. Los bloques de procedimientos conservan el formato base.",
+ sqlFormatterListLayout: "Diseño general de listas",
+ sqlFormatterSelectListLayout: "Lista de SELECT",
+ sqlFormatterInsertListLayout: "Lista de INSERT",
+ sqlFormatterUpdateListLayout: "Lista de UPDATE",
+ sqlFormatterListItemAlignment: "Alineación de continuación de listas",
+ sqlFormatterEmptyLineMode: "Líneas en blanco",
+ sqlFormatterDmlRules: "Reglas DML",
+ sqlFormatterConditionRules: "Reglas de condiciones",
+ sqlFormatterSelectCommaPosition: "Coma de SELECT",
+ sqlFormatterInsertCommaPosition: "Coma de INSERT",
+ sqlFormatterUpdateCommaPosition: "Coma de UPDATE",
+ sqlFormatterAlignSelectAliases: "Alinear alias de SELECT",
+ sqlFormatterAlignUpdateAssignments: "Alinear asignaciones de UPDATE",
+ sqlFormatterCollapseShortStatements: "Compactar sentencias cortas",
+ sqlFormatterWhereLogicalOperatorNewline: "Operadores lógicos de WHERE",
+ sqlFormatterOnLogicalOperatorNewline: "Operadores lógicos de JOIN ON",
+ sqlFormatterExpressionLogicalOperatorNewline: "Operadores lógicos de otras expresiones",
+ sqlFormatterNewlineBeforeJoinOn: "Salto de línea antes de JOIN ON",
+ sqlFormatterPreview: "Vista previa del formato",
+ sqlFormatterPreviewDialect: "Dialecto",
+ sqlFormatterPreviewSource: "SQL de vista previa",
+ sqlFormatterPreviewFailed: "No se pudo dar formato a la vista previa: {message}",
+ sqlFormatterPreviewStale: "Se muestra el último resultado correcto. Corrige el SQL para actualizar la vista previa.",
+ sqlFormatterPreviewUpdating: "Actualizando vista previa…",
+ sqlFormatterRule_inherit: "Heredar",
+ sqlFormatterRule_singleLine: "Una sola línea",
+ sqlFormatterRule_fit: "Una línea si cabe",
+ sqlFormatterRule_vertical: "Un elemento por línea",
+ sqlFormatterRule_wrap: "Ajustar al ancho",
+ sqlFormatterRule_firstItem: "Alinear con el primer elemento",
+ sqlFormatterRule_indent: "Alinear con la sangría",
+ sqlFormatterRule_before: "Salto antes del operador",
+ sqlFormatterRule_after: "Salto después del operador",
+ sqlFormatterRule_none: "Sin salto forzado",
+ sqlFormatterRule_remove: "Eliminar",
+ sqlFormatterRule_single: "Reducir a una línea en blanco",
+ sqlFormatterRule_preserve: "Conservar",
+ sqlFormatterFallbackNotice: "No se aplicaron las reglas personalizadas; se usó el diseño base.",
sqlFormatterAdvancedOptions: "Opciones avanzadas",
sqlFormatterParams: "Parámetros",
sqlFormatterParamTypes: "Tipos de parámetro",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index 7b7e62a05d..67b75d6fe1 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -8113,6 +8113,46 @@ export default withEnglishFallback({
sqlFormatterPreserveEmptyLines: "Pertahankan baris kosong",
sqlFormatterDenseOperators: "Operator rapat",
sqlFormatterNewlineBeforeSemicolon: "Titik koma pada baris baru",
+ sqlFormatterCustomRules: "Aturan SQL kustom",
+ sqlFormatterCustomRulesHint: "Saat aktif, gunakan tata letak kustom; saat nonaktif, pulihkan tata letak dasar yang dipilih. Blok prosedur tetap menggunakan pemformatan dasar.",
+ sqlFormatterListLayout: "Tata letak daftar umum",
+ sqlFormatterSelectListLayout: "Daftar SELECT",
+ sqlFormatterInsertListLayout: "Daftar INSERT",
+ sqlFormatterUpdateListLayout: "Daftar UPDATE",
+ sqlFormatterListItemAlignment: "Perataan lanjutan daftar",
+ sqlFormatterEmptyLineMode: "Baris kosong",
+ sqlFormatterDmlRules: "Aturan DML",
+ sqlFormatterConditionRules: "Aturan kondisi",
+ sqlFormatterSelectCommaPosition: "Koma SELECT",
+ sqlFormatterInsertCommaPosition: "Koma INSERT",
+ sqlFormatterUpdateCommaPosition: "Koma UPDATE",
+ sqlFormatterAlignSelectAliases: "Ratakan alias SELECT",
+ sqlFormatterAlignUpdateAssignments: "Ratakan penetapan UPDATE",
+ sqlFormatterCollapseShortStatements: "Gabungkan pernyataan pendek",
+ sqlFormatterWhereLogicalOperatorNewline: "Operator logika WHERE",
+ sqlFormatterOnLogicalOperatorNewline: "Operator logika JOIN ON",
+ sqlFormatterExpressionLogicalOperatorNewline: "Operator logika ekspresi lain",
+ sqlFormatterNewlineBeforeJoinOn: "Baris baru sebelum JOIN ON",
+ sqlFormatterPreview: "Pratinjau pemformatan",
+ sqlFormatterPreviewDialect: "Dialek",
+ sqlFormatterPreviewSource: "SQL pratinjau",
+ sqlFormatterPreviewFailed: "Pratinjau tidak dapat diformat: {message}",
+ sqlFormatterPreviewStale: "Menampilkan hasil terakhir yang berhasil. Perbaiki SQL untuk memperbarui pratinjau.",
+ sqlFormatterPreviewUpdating: "Memperbarui pratinjau…",
+ sqlFormatterRule_inherit: "Warisi",
+ sqlFormatterRule_singleLine: "Satu baris",
+ sqlFormatterRule_fit: "Satu baris jika muat",
+ sqlFormatterRule_vertical: "Satu item per baris",
+ sqlFormatterRule_wrap: "Bungkus sesuai lebar",
+ sqlFormatterRule_firstItem: "Ratakan ke item pertama",
+ sqlFormatterRule_indent: "Ratakan ke indentasi",
+ sqlFormatterRule_before: "Baris baru sebelum operator",
+ sqlFormatterRule_after: "Baris baru setelah operator",
+ sqlFormatterRule_none: "Tanpa baris baru paksa",
+ sqlFormatterRule_remove: "Hapus",
+ sqlFormatterRule_single: "Ringkas menjadi satu baris kosong",
+ sqlFormatterRule_preserve: "Pertahankan",
+ sqlFormatterFallbackNotice: "Aturan kustom tidak diterapkan; tata letak dasar digunakan.",
sqlFormatterAdvancedOptions: "Opsi lanjutan",
sqlFormatterParams: "Parameter",
sqlFormatterParamTypes: "Jenis parameter",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 3c38168c06..dff9900a11 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -7795,6 +7795,46 @@ export default withEnglishFallback({
sqlFormatterPreserveEmptyLines: "Mantieni le righe vuote",
sqlFormatterDenseOperators: "Operatori compatti",
sqlFormatterNewlineBeforeSemicolon: "Punto e virgola su nuova riga",
+ sqlFormatterCustomRules: "Regole SQL personalizzate",
+ sqlFormatterCustomRulesHint: "Quando è attiva usa il layout personalizzato; disattivandola ripristina il layout base selezionato. I blocchi procedurali mantengono la formattazione di base.",
+ sqlFormatterListLayout: "Layout generale degli elenchi",
+ sqlFormatterSelectListLayout: "Elenco SELECT",
+ sqlFormatterInsertListLayout: "Elenco INSERT",
+ sqlFormatterUpdateListLayout: "Elenco UPDATE",
+ sqlFormatterListItemAlignment: "Allineamento delle righe successive dell’elenco",
+ sqlFormatterEmptyLineMode: "Righe vuote",
+ sqlFormatterDmlRules: "Regole DML",
+ sqlFormatterConditionRules: "Regole delle condizioni",
+ sqlFormatterSelectCommaPosition: "Virgola SELECT",
+ sqlFormatterInsertCommaPosition: "Virgola INSERT",
+ sqlFormatterUpdateCommaPosition: "Virgola UPDATE",
+ sqlFormatterAlignSelectAliases: "Allinea gli alias SELECT",
+ sqlFormatterAlignUpdateAssignments: "Allinea le assegnazioni UPDATE",
+ sqlFormatterCollapseShortStatements: "Compatta le istruzioni brevi",
+ sqlFormatterWhereLogicalOperatorNewline: "Operatori logici WHERE",
+ sqlFormatterOnLogicalOperatorNewline: "Operatori logici JOIN ON",
+ sqlFormatterExpressionLogicalOperatorNewline: "Operatori logici delle altre espressioni",
+ sqlFormatterNewlineBeforeJoinOn: "A capo prima di JOIN ON",
+ sqlFormatterPreview: "Anteprima formattazione",
+ sqlFormatterPreviewDialect: "Dialetto",
+ sqlFormatterPreviewSource: "SQL di anteprima",
+ sqlFormatterPreviewFailed: "Impossibile formattare l’anteprima: {message}",
+ sqlFormatterPreviewStale: "È mostrato l’ultimo risultato valido. Correggi SQL per aggiornare l’anteprima.",
+ sqlFormatterPreviewUpdating: "Aggiornamento anteprima…",
+ sqlFormatterRule_inherit: "Eredita",
+ sqlFormatterRule_singleLine: "Una riga",
+ sqlFormatterRule_fit: "Una riga se entra",
+ sqlFormatterRule_vertical: "Un elemento per riga",
+ sqlFormatterRule_wrap: "Vai a capo in base alla larghezza",
+ sqlFormatterRule_firstItem: "Allinea al primo elemento",
+ sqlFormatterRule_indent: "Allinea al rientro",
+ sqlFormatterRule_before: "A capo prima dell’operatore",
+ sqlFormatterRule_after: "A capo dopo l’operatore",
+ sqlFormatterRule_none: "Nessun a capo forzato",
+ sqlFormatterRule_remove: "Rimuovi",
+ sqlFormatterRule_single: "Riduci a una riga vuota",
+ sqlFormatterRule_preserve: "Mantieni",
+ sqlFormatterFallbackNotice: "Regole personalizzate non applicate; è stato usato il layout base.",
sqlFormatterAdvancedOptions: "Opzioni avanzate",
sqlFormatterParams: "Parametri",
sqlFormatterParamTypes: "Tipi parametro",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 5d15d55b0b..2ef3b4afc1 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -7823,6 +7823,46 @@ export default withEnglishFallback({
sqlFormatterPreserveEmptyLines: "空行を保持",
sqlFormatterDenseOperators: "演算子を詰める",
sqlFormatterNewlineBeforeSemicolon: "セミコロンを新しい行に",
+ sqlFormatterCustomRules: "カスタム SQL ルール",
+ sqlFormatterCustomRulesHint: "有効時はカスタムルールのレイアウトを使用し、無効にすると選択した基本レイアウトに戻ります。プロシージャブロックは基本形式のままです。",
+ sqlFormatterListLayout: "全般のリストレイアウト",
+ sqlFormatterSelectListLayout: "SELECT リスト",
+ sqlFormatterInsertListLayout: "INSERT リスト",
+ sqlFormatterUpdateListLayout: "UPDATE リスト",
+ sqlFormatterListItemAlignment: "リストの折り返し位置",
+ sqlFormatterEmptyLineMode: "空行",
+ sqlFormatterDmlRules: "DML ルール",
+ sqlFormatterConditionRules: "条件ルール",
+ sqlFormatterSelectCommaPosition: "SELECT のカンマ",
+ sqlFormatterInsertCommaPosition: "INSERT のカンマ",
+ sqlFormatterUpdateCommaPosition: "UPDATE のカンマ",
+ sqlFormatterAlignSelectAliases: "SELECT エイリアスを整列",
+ sqlFormatterAlignUpdateAssignments: "UPDATE の代入を整列",
+ sqlFormatterCollapseShortStatements: "短い文をまとめる",
+ sqlFormatterWhereLogicalOperatorNewline: "WHERE の論理演算子",
+ sqlFormatterOnLogicalOperatorNewline: "JOIN ON の論理演算子",
+ sqlFormatterExpressionLogicalOperatorNewline: "その他の式の論理演算子",
+ sqlFormatterNewlineBeforeJoinOn: "JOIN ON の前で改行",
+ sqlFormatterPreview: "フォーマットプレビュー",
+ sqlFormatterPreviewDialect: "方言",
+ sqlFormatterPreviewSource: "プレビュー SQL",
+ sqlFormatterPreviewFailed: "プレビューを整形できません: {message}",
+ sqlFormatterPreviewStale: "最後に成功した結果を表示しています。SQL を修正するとプレビューが更新されます。",
+ sqlFormatterPreviewUpdating: "プレビューを更新中…",
+ sqlFormatterRule_inherit: "継承",
+ sqlFormatterRule_singleLine: "1 行",
+ sqlFormatterRule_fit: "収まる場合は 1 行",
+ sqlFormatterRule_vertical: "項目ごとに 1 行",
+ sqlFormatterRule_wrap: "幅に合わせて折り返す",
+ sqlFormatterRule_firstItem: "先頭項目に揃える",
+ sqlFormatterRule_indent: "インデントに揃える",
+ sqlFormatterRule_before: "演算子の前で改行",
+ sqlFormatterRule_after: "演算子の後で改行",
+ sqlFormatterRule_none: "強制改行なし",
+ sqlFormatterRule_remove: "削除",
+ sqlFormatterRule_single: "空行を 1 行にまとめる",
+ sqlFormatterRule_preserve: "保持",
+ sqlFormatterFallbackNotice: "カスタムルールを適用できないため、基本レイアウトを使用しました。",
sqlFormatterAdvancedOptions: "詳細オプション",
sqlFormatterParams: "パラメーター",
sqlFormatterParamTypes: "パラメーター型",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 5f603b974d..fdfc9b698b 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -7759,6 +7759,46 @@ export default withEnglishFallback({
sqlFormatterPreserveEmptyLines: "빈 줄 유지",
sqlFormatterDenseOperators: "조밀한 연산자",
sqlFormatterNewlineBeforeSemicolon: "세미콜론 새 줄에",
+ sqlFormatterCustomRules: "사용자 지정 SQL 규칙",
+ sqlFormatterCustomRulesHint: "켜면 사용자 지정 규칙 레이아웃을 사용하고, 끄면 선택한 기본 레이아웃으로 돌아갑니다. 프로시저 블록은 기본 형식을 유지합니다.",
+ sqlFormatterListLayout: "일반 목록 레이아웃",
+ sqlFormatterSelectListLayout: "SELECT 목록",
+ sqlFormatterInsertListLayout: "INSERT 목록",
+ sqlFormatterUpdateListLayout: "UPDATE 목록",
+ sqlFormatterListItemAlignment: "목록 이어쓰기 정렬",
+ sqlFormatterEmptyLineMode: "빈 줄",
+ sqlFormatterDmlRules: "DML 규칙",
+ sqlFormatterConditionRules: "조건 규칙",
+ sqlFormatterSelectCommaPosition: "SELECT 쉼표",
+ sqlFormatterInsertCommaPosition: "INSERT 쉼표",
+ sqlFormatterUpdateCommaPosition: "UPDATE 쉼표",
+ sqlFormatterAlignSelectAliases: "SELECT 별칭 정렬",
+ sqlFormatterAlignUpdateAssignments: "UPDATE 할당 정렬",
+ sqlFormatterCollapseShortStatements: "짧은 문장 합치기",
+ sqlFormatterWhereLogicalOperatorNewline: "WHERE 논리 연산자",
+ sqlFormatterOnLogicalOperatorNewline: "JOIN ON 논리 연산자",
+ sqlFormatterExpressionLogicalOperatorNewline: "기타 식의 논리 연산자",
+ sqlFormatterNewlineBeforeJoinOn: "JOIN ON 앞에서 줄바꿈",
+ sqlFormatterPreview: "서식 미리 보기",
+ sqlFormatterPreviewDialect: "방언",
+ sqlFormatterPreviewSource: "미리 보기 SQL",
+ sqlFormatterPreviewFailed: "미리 보기를 서식 지정할 수 없습니다: {message}",
+ sqlFormatterPreviewStale: "마지막으로 성공한 결과를 표시합니다. SQL을 수정하면 미리 보기가 갱신됩니다.",
+ sqlFormatterPreviewUpdating: "미리 보기 업데이트 중…",
+ sqlFormatterRule_inherit: "상속",
+ sqlFormatterRule_singleLine: "한 줄",
+ sqlFormatterRule_fit: "들어가면 한 줄",
+ sqlFormatterRule_vertical: "항목마다 한 줄",
+ sqlFormatterRule_wrap: "너비에 맞춰 줄바꿈",
+ sqlFormatterRule_firstItem: "첫 항목에 맞춤",
+ sqlFormatterRule_indent: "들여쓰기에 맞춤",
+ sqlFormatterRule_before: "연산자 앞에서 줄바꿈",
+ sqlFormatterRule_after: "연산자 뒤에서 줄바꿈",
+ sqlFormatterRule_none: "강제 줄바꿈 안 함",
+ sqlFormatterRule_remove: "제거",
+ sqlFormatterRule_single: "빈 줄 한 줄로 축소",
+ sqlFormatterRule_preserve: "유지",
+ sqlFormatterFallbackNotice: "사용자 지정 규칙을 적용하지 못해 기본 레이아웃을 사용했습니다.",
sqlFormatterAdvancedOptions: "고급 옵션",
sqlFormatterParams: "매개변수",
sqlFormatterParamTypes: "매개변수 유형",
diff --git a/apps/desktop/src/i18n/locales/pl.ts b/apps/desktop/src/i18n/locales/pl.ts
index 193d66584b..751de68550 100644
--- a/apps/desktop/src/i18n/locales/pl.ts
+++ b/apps/desktop/src/i18n/locales/pl.ts
@@ -8181,6 +8181,46 @@ export default withEnglishFallback({
sqlFormatterPreserveEmptyLines: "Zachowaj puste linie",
sqlFormatterDenseOperators: "Zwarte operatory",
sqlFormatterNewlineBeforeSemicolon: "Średnik w nowej linii",
+ sqlFormatterCustomRules: "Niestandardowe reguły SQL",
+ sqlFormatterCustomRulesHint: "Po włączeniu używany jest niestandardowy układ; po wyłączeniu przywracany jest wybrany układ podstawowy. Bloki procedur zachowują formatowanie podstawowe.",
+ sqlFormatterListLayout: "Ogólny układ listy",
+ sqlFormatterSelectListLayout: "Lista SELECT",
+ sqlFormatterInsertListLayout: "Lista INSERT",
+ sqlFormatterUpdateListLayout: "Lista UPDATE",
+ sqlFormatterListItemAlignment: "Wyrównanie kontynuacji listy",
+ sqlFormatterEmptyLineMode: "Puste wiersze",
+ sqlFormatterDmlRules: "Reguły DML",
+ sqlFormatterConditionRules: "Reguły warunków",
+ sqlFormatterSelectCommaPosition: "Przecinek SELECT",
+ sqlFormatterInsertCommaPosition: "Przecinek INSERT",
+ sqlFormatterUpdateCommaPosition: "Przecinek UPDATE",
+ sqlFormatterAlignSelectAliases: "Wyrównaj aliasy SELECT",
+ sqlFormatterAlignUpdateAssignments: "Wyrównaj przypisania UPDATE",
+ sqlFormatterCollapseShortStatements: "Scal krótkie instrukcje",
+ sqlFormatterWhereLogicalOperatorNewline: "Operatory logiczne WHERE",
+ sqlFormatterOnLogicalOperatorNewline: "Operatory logiczne JOIN ON",
+ sqlFormatterExpressionLogicalOperatorNewline: "Operatory logiczne innych wyrażeń",
+ sqlFormatterNewlineBeforeJoinOn: "Nowy wiersz przed JOIN ON",
+ sqlFormatterPreview: "Podgląd formatowania",
+ sqlFormatterPreviewDialect: "Dialekt",
+ sqlFormatterPreviewSource: "SQL do podglądu",
+ sqlFormatterPreviewFailed: "Nie można sformatować podglądu: {message}",
+ sqlFormatterPreviewStale: "Wyświetlany jest ostatni poprawny wynik. Popraw SQL, aby odświeżyć podgląd.",
+ sqlFormatterPreviewUpdating: "Odświeżanie podglądu…",
+ sqlFormatterRule_inherit: "Dziedzicz",
+ sqlFormatterRule_singleLine: "Jeden wiersz",
+ sqlFormatterRule_fit: "Jeden wiersz, jeśli się mieści",
+ sqlFormatterRule_vertical: "Jeden element w wierszu",
+ sqlFormatterRule_wrap: "Zawijaj do szerokości",
+ sqlFormatterRule_firstItem: "Wyrównaj do pierwszego elementu",
+ sqlFormatterRule_indent: "Wyrównaj do wcięcia",
+ sqlFormatterRule_before: "Nowy wiersz przed operatorem",
+ sqlFormatterRule_after: "Nowy wiersz po operatorze",
+ sqlFormatterRule_none: "Bez wymuszonego nowego wiersza",
+ sqlFormatterRule_remove: "Usuń",
+ sqlFormatterRule_single: "Zredukuj do jednego pustego wiersza",
+ sqlFormatterRule_preserve: "Zachowaj",
+ sqlFormatterFallbackNotice: "Nie zastosowano reguł niestandardowych; użyto układu podstawowego.",
sqlFormatterAdvancedOptions: "Opcje zaawansowane",
sqlFormatterParams: "Parametry",
sqlFormatterParamTypes: "Typy parametrów",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 16464da777..fa55cce2c0 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -7794,6 +7794,46 @@ export default withEnglishFallback({
sqlFormatterPreserveEmptyLines: "Preservar linhas em branco",
sqlFormatterDenseOperators: "Operadores compactos",
sqlFormatterNewlineBeforeSemicolon: "Ponto e vírgula em nova linha",
+ sqlFormatterCustomRules: "Regras SQL personalizadas",
+ sqlFormatterCustomRulesHint: "Quando ativada, usa o layout personalizado; ao desativar, restaura o layout base selecionado. Blocos de procedimento mantêm a formatação base.",
+ sqlFormatterListLayout: "Layout geral de listas",
+ sqlFormatterSelectListLayout: "Lista SELECT",
+ sqlFormatterInsertListLayout: "Lista INSERT",
+ sqlFormatterUpdateListLayout: "Lista UPDATE",
+ sqlFormatterListItemAlignment: "Alinhamento das continuações da lista",
+ sqlFormatterEmptyLineMode: "Linhas em branco",
+ sqlFormatterDmlRules: "Regras DML",
+ sqlFormatterConditionRules: "Regras de condição",
+ sqlFormatterSelectCommaPosition: "Vírgula SELECT",
+ sqlFormatterInsertCommaPosition: "Vírgula INSERT",
+ sqlFormatterUpdateCommaPosition: "Vírgula UPDATE",
+ sqlFormatterAlignSelectAliases: "Alinhar aliases SELECT",
+ sqlFormatterAlignUpdateAssignments: "Alinhar atribuições UPDATE",
+ sqlFormatterCollapseShortStatements: "Compactar instruções curtas",
+ sqlFormatterWhereLogicalOperatorNewline: "Operadores lógicos WHERE",
+ sqlFormatterOnLogicalOperatorNewline: "Operadores lógicos JOIN ON",
+ sqlFormatterExpressionLogicalOperatorNewline: "Operadores lógicos de outras expressões",
+ sqlFormatterNewlineBeforeJoinOn: "Quebra de linha antes de JOIN ON",
+ sqlFormatterPreview: "Prévia da formatação",
+ sqlFormatterPreviewDialect: "Dialeto",
+ sqlFormatterPreviewSource: "SQL de prévia",
+ sqlFormatterPreviewFailed: "Não foi possível formatar a prévia: {message}",
+ sqlFormatterPreviewStale: "Exibindo o último resultado bem-sucedido. Corrija o SQL para atualizar a prévia.",
+ sqlFormatterPreviewUpdating: "Atualizando prévia…",
+ sqlFormatterRule_inherit: "Herdar",
+ sqlFormatterRule_singleLine: "Uma linha",
+ sqlFormatterRule_fit: "Uma linha se couber",
+ sqlFormatterRule_vertical: "Um item por linha",
+ sqlFormatterRule_wrap: "Quebrar conforme a largura",
+ sqlFormatterRule_firstItem: "Alinhar ao primeiro item",
+ sqlFormatterRule_indent: "Alinhar à indentação",
+ sqlFormatterRule_before: "Quebra antes do operador",
+ sqlFormatterRule_after: "Quebra depois do operador",
+ sqlFormatterRule_none: "Sem quebra forçada",
+ sqlFormatterRule_remove: "Remover",
+ sqlFormatterRule_single: "Reduzir a uma linha em branco",
+ sqlFormatterRule_preserve: "Manter",
+ sqlFormatterFallbackNotice: "As regras personalizadas não foram aplicadas; o layout base foi usado.",
sqlFormatterAdvancedOptions: "Opções avançadas",
sqlFormatterParams: "Parâmetros",
sqlFormatterParamTypes: "Tipos de parâmetro",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index b5bbcf7a96..5d265dfba8 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -9205,6 +9205,46 @@ export default withEnglishFallback({
sqlFormatterPreserveEmptyLines: "Сохранять пустые строки",
sqlFormatterDenseOperators: "Плотные операторы",
sqlFormatterNewlineBeforeSemicolon: "Точка с запятой на новой строке",
+ sqlFormatterCustomRules: "Пользовательские правила SQL",
+ sqlFormatterCustomRulesHint: "При включении используется пользовательская раскладка; при отключении восстанавливается выбранная базовая раскладка. Блоки процедур сохраняют базовое форматирование.",
+ sqlFormatterListLayout: "Общая раскладка списков",
+ sqlFormatterSelectListLayout: "Список SELECT",
+ sqlFormatterInsertListLayout: "Список INSERT",
+ sqlFormatterUpdateListLayout: "Список UPDATE",
+ sqlFormatterListItemAlignment: "Выравнивание продолжения списка",
+ sqlFormatterEmptyLineMode: "Пустые строки",
+ sqlFormatterDmlRules: "Правила DML",
+ sqlFormatterConditionRules: "Правила условий",
+ sqlFormatterSelectCommaPosition: "Запятая SELECT",
+ sqlFormatterInsertCommaPosition: "Запятая INSERT",
+ sqlFormatterUpdateCommaPosition: "Запятая UPDATE",
+ sqlFormatterAlignSelectAliases: "Выравнивать псевдонимы SELECT",
+ sqlFormatterAlignUpdateAssignments: "Выравнивать присваивания UPDATE",
+ sqlFormatterCollapseShortStatements: "Объединять короткие операторы",
+ sqlFormatterWhereLogicalOperatorNewline: "Логические операторы WHERE",
+ sqlFormatterOnLogicalOperatorNewline: "Логические операторы JOIN ON",
+ sqlFormatterExpressionLogicalOperatorNewline: "Логические операторы других выражений",
+ sqlFormatterNewlineBeforeJoinOn: "Перенос перед JOIN ON",
+ sqlFormatterPreview: "Предпросмотр форматирования",
+ sqlFormatterPreviewDialect: "Диалект",
+ sqlFormatterPreviewSource: "SQL для предпросмотра",
+ sqlFormatterPreviewFailed: "Не удалось отформатировать предпросмотр: {message}",
+ sqlFormatterPreviewStale: "Показан последний успешный результат. Исправьте SQL, чтобы обновить предпросмотр.",
+ sqlFormatterPreviewUpdating: "Обновление предпросмотра…",
+ sqlFormatterRule_inherit: "Наследовать",
+ sqlFormatterRule_singleLine: "Одна строка",
+ sqlFormatterRule_fit: "В одну строку, если помещается",
+ sqlFormatterRule_vertical: "Каждый элемент с новой строки",
+ sqlFormatterRule_wrap: "Перенос по ширине",
+ sqlFormatterRule_firstItem: "По первому элементу",
+ sqlFormatterRule_indent: "По отступу",
+ sqlFormatterRule_before: "Перенос перед оператором",
+ sqlFormatterRule_after: "Перенос после оператора",
+ sqlFormatterRule_none: "Без принудительного переноса",
+ sqlFormatterRule_remove: "Удалить",
+ sqlFormatterRule_single: "Свести к одной пустой строке",
+ sqlFormatterRule_preserve: "Сохранить",
+ sqlFormatterFallbackNotice: "Пользовательские правила не применены; использована базовая раскладка.",
sqlFormatterAdvancedOptions: "Дополнительные параметры",
sqlFormatterParams: "Параметры",
sqlFormatterParamTypes: "Типы параметров",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index 0aba589389..8b3c56bdd4 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -9640,6 +9640,46 @@ export default withEnglishFallback({
sqlFormatterPreserveEmptyLines: "คงบรรทัดว่าง",
sqlFormatterDenseOperators: "ตัวดำเนินการแบบหนาแน่น",
sqlFormatterNewlineBeforeSemicolon: "เซมิโคลอนขึ้นบรรทัดใหม่",
+ sqlFormatterCustomRules: "กฎ SQL แบบกำหนดเอง",
+ sqlFormatterCustomRulesHint: "เมื่อเปิดใช้จะใช้รูปแบบตามกฎกำหนดเอง เมื่อปิดจะคืนค่ารูปแบบพื้นฐานที่เลือก บล็อกโพรซีเยอร์ยังคงใช้รูปแบบพื้นฐาน",
+ sqlFormatterListLayout: "รูปแบบรายการทั่วไป",
+ sqlFormatterSelectListLayout: "รายการ SELECT",
+ sqlFormatterInsertListLayout: "รายการ INSERT",
+ sqlFormatterUpdateListLayout: "รายการ UPDATE",
+ sqlFormatterListItemAlignment: "การจัดแนวบรรทัดต่อเนื่องของรายการ",
+ sqlFormatterEmptyLineMode: "บรรทัดว่าง",
+ sqlFormatterDmlRules: "กฎ DML",
+ sqlFormatterConditionRules: "กฎเงื่อนไข",
+ sqlFormatterSelectCommaPosition: "เครื่องหมายจุลภาค SELECT",
+ sqlFormatterInsertCommaPosition: "เครื่องหมายจุลภาค INSERT",
+ sqlFormatterUpdateCommaPosition: "เครื่องหมายจุลภาค UPDATE",
+ sqlFormatterAlignSelectAliases: "จัดแนว alias ของ SELECT",
+ sqlFormatterAlignUpdateAssignments: "จัดแนวการกำหนดค่าของ UPDATE",
+ sqlFormatterCollapseShortStatements: "รวมคำสั่งสั้น",
+ sqlFormatterWhereLogicalOperatorNewline: "ตัวดำเนินการตรรกะ WHERE",
+ sqlFormatterOnLogicalOperatorNewline: "ตัวดำเนินการตรรกะ JOIN ON",
+ sqlFormatterExpressionLogicalOperatorNewline: "ตัวดำเนินการตรรกะของนิพจน์อื่น",
+ sqlFormatterNewlineBeforeJoinOn: "ขึ้นบรรทัดใหม่ก่อน JOIN ON",
+ sqlFormatterPreview: "ตัวอย่างการจัดรูปแบบ",
+ sqlFormatterPreviewDialect: "Dialect",
+ sqlFormatterPreviewSource: "SQL สำหรับตัวอย่าง",
+ sqlFormatterPreviewFailed: "จัดรูปแบบตัวอย่างไม่ได้: {message}",
+ sqlFormatterPreviewStale: "กำลังแสดงผลลัพธ์ล่าสุดที่สำเร็จ แก้ SQL เพื่ออัปเดตตัวอย่าง",
+ sqlFormatterPreviewUpdating: "กำลังอัปเดตตัวอย่าง…",
+ sqlFormatterRule_inherit: "สืบทอด",
+ sqlFormatterRule_singleLine: "บรรทัดเดียว",
+ sqlFormatterRule_fit: "บรรทัดเดียวเมื่อพอดี",
+ sqlFormatterRule_vertical: "หนึ่งรายการต่อบรรทัด",
+ sqlFormatterRule_wrap: "ตัดบรรทัดตามความกว้าง",
+ sqlFormatterRule_firstItem: "จัดแนวกับรายการแรก",
+ sqlFormatterRule_indent: "จัดแนวตามการเยื้อง",
+ sqlFormatterRule_before: "ขึ้นบรรทัดใหม่ก่อนตัวดำเนินการ",
+ sqlFormatterRule_after: "ขึ้นบรรทัดใหม่หลังตัวดำเนินการ",
+ sqlFormatterRule_none: "ไม่บังคับขึ้นบรรทัดใหม่",
+ sqlFormatterRule_remove: "นำออก",
+ sqlFormatterRule_single: "ยุบให้เหลือบรรทัดว่างหนึ่งบรรทัด",
+ sqlFormatterRule_preserve: "คงไว้",
+ sqlFormatterFallbackNotice: "ใช้รูปแบบพื้นฐาน เนื่องจากไม่สามารถใช้กฎกำหนดเองกับข้อมูลนี้ได้",
sqlFormatterAdvancedOptions: "ตัวเลือกขั้นสูง",
sqlFormatterParams: "พารามิเตอร์",
sqlFormatterParamTypes: "ชนิดพารามิเตอร์",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index 52cfb8752a..e6ac8f337c 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -7253,6 +7253,46 @@ export default withEnglishFallback({
sqlFormatterPreserveEmptyLines: "Boş satırları koru",
sqlFormatterDenseOperators: "Sık işleçler",
sqlFormatterNewlineBeforeSemicolon: "Noktalı virgül yeni satırda",
+ sqlFormatterCustomRules: "Özel SQL kuralları",
+ sqlFormatterCustomRulesHint: "Açıkken özel kural düzeni kullanılır; kapatıldığında seçilen temel düzene dönülür. Prosedür blokları temel biçimlendirmeyi korur.",
+ sqlFormatterListLayout: "Genel liste düzeni",
+ sqlFormatterSelectListLayout: "SELECT listesi",
+ sqlFormatterInsertListLayout: "INSERT listesi",
+ sqlFormatterUpdateListLayout: "UPDATE listesi",
+ sqlFormatterListItemAlignment: "Liste devamı hizalaması",
+ sqlFormatterEmptyLineMode: "Boş satırlar",
+ sqlFormatterDmlRules: "DML kuralları",
+ sqlFormatterConditionRules: "Koşul kuralları",
+ sqlFormatterSelectCommaPosition: "SELECT virgülü",
+ sqlFormatterInsertCommaPosition: "INSERT virgülü",
+ sqlFormatterUpdateCommaPosition: "UPDATE virgülü",
+ sqlFormatterAlignSelectAliases: "SELECT takma adlarını hizala",
+ sqlFormatterAlignUpdateAssignments: "UPDATE atamalarını hizala",
+ sqlFormatterCollapseShortStatements: "Kısa ifadeleri birleştir",
+ sqlFormatterWhereLogicalOperatorNewline: "WHERE mantıksal işleçleri",
+ sqlFormatterOnLogicalOperatorNewline: "JOIN ON mantıksal işleçleri",
+ sqlFormatterExpressionLogicalOperatorNewline: "Diğer ifadelerin mantıksal işleçleri",
+ sqlFormatterNewlineBeforeJoinOn: "JOIN ON öncesinde yeni satır",
+ sqlFormatterPreview: "Biçimlendirme önizlemesi",
+ sqlFormatterPreviewDialect: "Diyalekt",
+ sqlFormatterPreviewSource: "Önizleme SQL’i",
+ sqlFormatterPreviewFailed: "Önizleme biçimlendirilemedi: {message}",
+ sqlFormatterPreviewStale: "Son başarılı sonuç gösteriliyor. Önizlemeyi yenilemek için SQL’i düzeltin.",
+ sqlFormatterPreviewUpdating: "Önizleme güncelleniyor…",
+ sqlFormatterRule_inherit: "Devral",
+ sqlFormatterRule_singleLine: "Tek satır",
+ sqlFormatterRule_fit: "Sığarsa tek satır",
+ sqlFormatterRule_vertical: "Her öğe ayrı satırda",
+ sqlFormatterRule_wrap: "Genişliğe göre kaydır",
+ sqlFormatterRule_firstItem: "İlk öğeye hizala",
+ sqlFormatterRule_indent: "Girintiye hizala",
+ sqlFormatterRule_before: "İşleçten önce yeni satır",
+ sqlFormatterRule_after: "İşleçten sonra yeni satır",
+ sqlFormatterRule_none: "Zorunlu yeni satır yok",
+ sqlFormatterRule_remove: "Kaldır",
+ sqlFormatterRule_single: "Tek boş satıra indir",
+ sqlFormatterRule_preserve: "Koru",
+ sqlFormatterFallbackNotice: "Özel kurallar bu girdiye uygulanmadı; temel düzen kullanıldı.",
sqlFormatterAdvancedOptions: "Gelişmiş seçenekler",
sqlFormatterParams: "Parametreler",
sqlFormatterParamTypes: "Parametre türleri",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index e78028d474..9243dedaeb 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -8965,6 +8965,46 @@ export default withEnglishFallback({
sqlFormatterPreserveEmptyLines: "保留原有空行",
sqlFormatterDenseOperators: "紧凑运算符",
sqlFormatterNewlineBeforeSemicolon: "分号单独换行",
+ sqlFormatterCustomRules: "自定义 SQL 规则",
+ sqlFormatterCustomRulesHint: "启用后使用自定义规则布局;关闭后恢复所选基础布局。过程块继续使用基础格式化,选中其中的独立 SQL 可应用这些规则。",
+ sqlFormatterListLayout: "通用列表布局",
+ sqlFormatterSelectListLayout: "SELECT 列表",
+ sqlFormatterInsertListLayout: "INSERT 列表",
+ sqlFormatterUpdateListLayout: "UPDATE 列表",
+ sqlFormatterListItemAlignment: "列表续行对齐",
+ sqlFormatterEmptyLineMode: "空行",
+ sqlFormatterDmlRules: "DML 规则",
+ sqlFormatterConditionRules: "条件规则",
+ sqlFormatterSelectCommaPosition: "SELECT 逗号",
+ sqlFormatterInsertCommaPosition: "INSERT 逗号",
+ sqlFormatterUpdateCommaPosition: "UPDATE 逗号",
+ sqlFormatterAlignSelectAliases: "对齐 SELECT 别名",
+ sqlFormatterAlignUpdateAssignments: "对齐 UPDATE 赋值",
+ sqlFormatterCollapseShortStatements: "合并短语句",
+ sqlFormatterWhereLogicalOperatorNewline: "WHERE 逻辑运算符",
+ sqlFormatterOnLogicalOperatorNewline: "JOIN ON 逻辑运算符",
+ sqlFormatterExpressionLogicalOperatorNewline: "其他表达式逻辑运算符",
+ sqlFormatterNewlineBeforeJoinOn: "JOIN 的 ON 前换行",
+ sqlFormatterPreview: "格式化预览",
+ sqlFormatterPreviewDialect: "方言",
+ sqlFormatterPreviewSource: "预览 SQL",
+ sqlFormatterPreviewFailed: "无法格式化预览:{message}",
+ sqlFormatterPreviewStale: "显示的是上次成功结果;修正 SQL 后会重新预览。",
+ sqlFormatterPreviewUpdating: "正在更新预览…",
+ sqlFormatterRule_inherit: "继承",
+ sqlFormatterRule_singleLine: "单行",
+ sqlFormatterRule_fit: "能放下则单行",
+ sqlFormatterRule_vertical: "每项一行",
+ sqlFormatterRule_wrap: "按宽度换行",
+ sqlFormatterRule_firstItem: "对齐首项",
+ sqlFormatterRule_indent: "按缩进对齐",
+ sqlFormatterRule_before: "运算符前换行",
+ sqlFormatterRule_after: "运算符后换行",
+ sqlFormatterRule_none: "不主动换行",
+ sqlFormatterRule_remove: "移除",
+ sqlFormatterRule_single: "合并为一行",
+ sqlFormatterRule_preserve: "保留",
+ sqlFormatterFallbackNotice: "当前输入未应用自定义规则,已使用基础布局。",
sqlFormatterAdvancedOptions: "高级选项",
sqlFormatterParams: "参数替换",
sqlFormatterParamTypes: "参数类型",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 4ce64ab1f1..c215fe451f 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -7142,6 +7142,46 @@ export default withEnglishFallback({
sqlFormatterPreserveEmptyLines: "保留原有空行",
sqlFormatterDenseOperators: "緊湊運算子",
sqlFormatterNewlineBeforeSemicolon: "分號獨立換行",
+ sqlFormatterCustomRules: "自訂 SQL 規則",
+ sqlFormatterCustomRulesHint: "啟用時使用自訂規則排版;關閉後還原所選的基本排版。程序區塊仍使用基本格式。",
+ sqlFormatterListLayout: "一般清單排版",
+ sqlFormatterSelectListLayout: "SELECT 清單",
+ sqlFormatterInsertListLayout: "INSERT 清單",
+ sqlFormatterUpdateListLayout: "UPDATE 清單",
+ sqlFormatterListItemAlignment: "清單續行對齊",
+ sqlFormatterEmptyLineMode: "空白行",
+ sqlFormatterDmlRules: "DML 規則",
+ sqlFormatterConditionRules: "條件規則",
+ sqlFormatterSelectCommaPosition: "SELECT 逗號",
+ sqlFormatterInsertCommaPosition: "INSERT 逗號",
+ sqlFormatterUpdateCommaPosition: "UPDATE 逗號",
+ sqlFormatterAlignSelectAliases: "對齊 SELECT 別名",
+ sqlFormatterAlignUpdateAssignments: "對齊 UPDATE 指派",
+ sqlFormatterCollapseShortStatements: "合併較短的語句",
+ sqlFormatterWhereLogicalOperatorNewline: "WHERE 邏輯運算子",
+ sqlFormatterOnLogicalOperatorNewline: "JOIN ON 邏輯運算子",
+ sqlFormatterExpressionLogicalOperatorNewline: "其他運算式的邏輯運算子",
+ sqlFormatterNewlineBeforeJoinOn: "在 JOIN ON 前換行",
+ sqlFormatterPreview: "格式預覽",
+ sqlFormatterPreviewDialect: "方言",
+ sqlFormatterPreviewSource: "預覽 SQL",
+ sqlFormatterPreviewFailed: "無法格式化預覽:{message}",
+ sqlFormatterPreviewStale: "目前顯示上次成功的結果。修正 SQL 後即可更新預覽。",
+ sqlFormatterPreviewUpdating: "正在更新預覽…",
+ sqlFormatterRule_inherit: "繼承",
+ sqlFormatterRule_singleLine: "單行",
+ sqlFormatterRule_fit: "可容納時單行",
+ sqlFormatterRule_vertical: "每個項目一行",
+ sqlFormatterRule_wrap: "依寬度換行",
+ sqlFormatterRule_firstItem: "對齊第一個項目",
+ sqlFormatterRule_indent: "依縮排對齊",
+ sqlFormatterRule_before: "在運算子前換行",
+ sqlFormatterRule_after: "在運算子後換行",
+ sqlFormatterRule_none: "不強制換行",
+ sqlFormatterRule_remove: "移除",
+ sqlFormatterRule_single: "合併為一個空白行",
+ sqlFormatterRule_preserve: "保留",
+ sqlFormatterFallbackNotice: "此輸入未套用自訂規則,已改用基本排版。",
sqlFormatterAdvancedOptions: "進階選項",
sqlFormatterParams: "參數替換",
sqlFormatterParamTypes: "參數類型",
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlFormatter.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlFormatter.spec.ts
index 2cf6f49f10..433c5ee634 100644
--- a/apps/desktop/src/lib/__tests__/sql/sqlFormatter.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/sqlFormatter.spec.ts
@@ -12,6 +12,7 @@ import {
import type { SqlFormatDialect } from "@/lib/sql/sqlFormatter";
import type { SqlFormatterSettings } from "@/lib/sql/sqlFormatterConfig";
import { extractSqlParameters } from "@/lib/sql/sqlParameters";
+import { tokenizeSqlSemantic } from "@/lib/sql/semantic/tokens";
// Most cases in this regression suite pin the former compact layout while
// checking dialect-specific token handling. New default-layout behavior is
@@ -687,6 +688,168 @@ AND owner_id = 42`,
expect(formatted).toContain("col1 -- first column");
expect(formatted).toMatch(/,\s*col2\s*-- second column/);
});
+
+ describe("dialect content boundaries", () => {
+ it.each([
+ ["postgres", "-- note", "AND", "\n", "dbx", "standard"],
+ ["postgres", "-- note", "OR", "\r\n", "classic", "standard"],
+ ["mysql", "# note", "XOR", "\n", "dbx", "standard"],
+ ["mysql", "# note", "AND", "\r\n", "classic", "standard"],
+ ["sqlserver", "-- note", "OR", "\r\n", "dbx", "tabularRight"],
+ ["mysql", "-- note", "AND", "\n", "dbx", "tabularLeft"],
+ ] as const)("keeps %s %s before %s as a code boundary (%j, %s, %s)", async (dialect, comment, operator, lineBreak, layoutStyle, indentStyle) => {
+ const source = `select a from t where x=1 ${comment}${lineBreak}${operator.toLowerCase()} y=2;`;
+ const settings = { layoutStyle, indentStyle, logicalOperatorNewline: "none" } as const;
+ const formatted = await formatSqlText(source, dialect, settings);
+ const tokens = (sql: string) => tokenizeSqlSemantic(sql, dialect).map((token) => token.normalized);
+ expect(formatted).toContain(`${comment}\n`);
+ expect(formatted).toMatch(new RegExp(`\\n\\s*${operator}\\s+y = 2;`));
+ expect(tokens(formatted)).toEqual(tokens(source));
+ expect(await formatSqlText(formatted, dialect, settings)).toBe(formatted);
+ });
+
+ it.each(["dbx", "classic"] as const)("still joins ordinary conditions and treats comment symbols in strings as data (%s)", async (layoutStyle) => {
+ const source = "select '-- not a comment' as note, '# not a comment' as other from t where x=1 and y=2 or z=3;";
+ const settings = { layoutStyle, logicalOperatorNewline: "none" } as const;
+ const formatted = await formatSqlText(source, "mysql", settings);
+ expect(formatted).toContain("'-- not a comment'");
+ expect(formatted).toContain("'# not a comment'");
+ expect(formatted).toContain("x = 1 AND y = 2 OR z = 3;");
+ expect(await formatSqlText(formatted, "mysql", settings)).toBe(formatted);
+ });
+
+ describe.each(["dbx", "classic"] as const)("Oracle alternative quoted literals (%s)", (layoutStyle) => {
+ it.each([
+ ["q", "[", "]", "\n"],
+ ["Q", "{", "}", "\r\n"],
+ ["nq", "(", ")", "\n"],
+ ["NQ", "<", ">", "\r\n"],
+ ["nQ", "!", "!", "\n"],
+ ["Nq", "~", "~", "\r\n"],
+ ] as const)("preserves %s with %s%s delimiters and %j newlines", async (prefix, open, close, lineBreak) => {
+ const literal = `${prefix}'${open}first 'quoted'${lineBreak}${lineBreak}-- AND is data${lineBreak}/* OR is data */ last${close}'`;
+ const adjacent = "q'~second 'quoted'\n\nlast~'";
+ const source = `select ${literal} as note, 'tail' as label, ${adjacent} as other from dual;\n\nselect :id from dual;`;
+ const settings = { layoutStyle, preserveEmptyLines: true, logicalOperatorNewline: "none" } as const;
+ const formatted = await formatSqlText(source, "oracle", settings);
+ const tokens = (sql: string) => tokenizeSqlSemantic(sql, "oracle").map((token) => token.normalized);
+ expect(formatted).toContain(literal);
+ expect(formatted).toContain(adjacent);
+ expect(formatted).toContain("'tail'");
+ expect(tokens(formatted)).toEqual(tokens(source));
+ expect(await formatSqlText(formatted, "oracle", settings)).toBe(formatted);
+ });
+ });
+
+ it("preserves a multiline q literal without empty-line preservation and leaves ordinary strings separate", async () => {
+ const literal = "q'[first 'quoted'\n\nlast]'";
+ const source = `select ${literal}, 'ordinary', q'!single 'quoted'!' from dual;`;
+ const formatted = await formatSqlText(source, "oracle", { preserveEmptyLines: false });
+ expect(formatted).toContain(literal);
+ expect(
+ tokenizeSqlSemantic(formatted, "oracle")
+ .filter((token) => token.kind === "string")
+ .map((token) => token.text),
+ ).toEqual([literal, "'ordinary'", "q'!single 'quoted'!'"]);
+ });
+
+ it.each(["dbx", "classic"] as const)("preserves spaces and tabs on a q literal's blank line in the base layout (%s)", async (layoutStyle) => {
+ const literal = "q'[first 'quoted'\r\n \t\r\nlast]'";
+ const source = `select ${literal} as note from dual;\n\nselect 2;`;
+ const settings = { layoutStyle, preserveEmptyLines: true } as const;
+ const formatted = await formatSqlText(source, "oracle", settings);
+ expect(formatted).toContain(literal);
+ expect(tokenizeSqlSemantic(formatted, "oracle").map((token) => token.normalized)).toEqual(tokenizeSqlSemantic(source, "oracle").map((token) => token.normalized));
+ expect(await formatSqlText(formatted, "oracle", settings)).toBe(formatted);
+ });
+
+ it.each(["dbx", "classic"] as const)("does not apply FROM same-line layout inside protected contents (%s)", async (layoutStyle) => {
+ const literal = "q'[first 'quoted'\nFROM\n literal_source\nlast]'";
+ const source = `select ${literal} as note from actual_source;`;
+ const settings = { layoutStyle, fromClauseLayout: "sameLine" } as const;
+ const formatted = await formatSqlText(source, "oracle", settings);
+ expect(formatted).toContain(literal);
+ expect(formatted).toContain("FROM actual_source");
+ expect(await formatSqlText(formatted, "oracle", settings)).toBe(formatted);
+ });
+
+ it.each([
+ ["postgres", "/* leading */"],
+ ["postgres", "-- leading"],
+ ["mysql", "# leading"],
+ ] as const)("keeps a leading %s comment below FROM (%s)", async (dialect, comment) => {
+ const source = `select a from\n ${comment}\n source_table;`;
+ const settings = { layoutStyle: "classic", fromClauseLayout: "sameLine" } as const;
+ const formatted = await formatSqlText(source, dialect, settings);
+ expect(formatted).toMatch(/FROM\n/);
+ expect(formatted).toContain(comment);
+ expect(tokenizeSqlSemantic(formatted, dialect).map((token) => token.normalized)).toEqual(tokenizeSqlSemantic(source, dialect).map((token) => token.normalized));
+ expect(await formatSqlText(formatted, dialect, settings)).toBe(formatted);
+ });
+
+ it("keeps quoted table names eligible for FROM same-line layout", async () => {
+ expect(await formatSqlText('select a from "Case Table";', "postgres", { layoutStyle: "classic", fromClauseLayout: "sameLine" })).toContain('FROM "Case Table"');
+ });
+
+ it.each([false, true])("does not normalize literal or block-comment line endings while restoring code paragraphs (rules=%s)", async (customRulesEnabled) => {
+ const literal = "$tag$first\r\n\r\nlast$tag$";
+ const comment = "/* first\r\n\r\nlast */";
+ const source = `select ${literal} as note from t;\n\n${comment}\n\nselect 2;`;
+ const settings = { customRulesEnabled, emptyLineMode: "preserve", preserveEmptyLines: true } as const;
+ const formatted = await formatSqlText(source, "postgres", settings);
+ expect(formatted).toContain(literal);
+ expect(formatted).toContain(comment);
+ expect(await formatSqlText(formatted, "postgres", settings)).toBe(formatted);
+ });
+
+ it.each(["", "\n"])("does not add a trailing empty line while restoring paragraphs at EOF %j", async (ending) => {
+ expect(await formatSqlText(`-- heading\n\nselect 1;${ending}`, "postgres", { preserveEmptyLines: true })).toBe("-- heading\n\nSELECT 1;");
+ });
+
+ it.each([
+ ["postgres", "/* first\r\n\r\nlast */", false],
+ ["postgres", "/* outer\r\n /* inner */\r\nlast */", true],
+ ["mysql", "/*+ MAX_EXECUTION_TIME(1000)\r\n NO_RANGE_OPTIMIZATION(t) */", false],
+ ["mysql", "/*!40101 SET @note = 'first\r\nlast' */", true],
+ ] as const)("preserves %s CR block comments and marker-like data (rules=%s)", async (dialect, comment, customRulesEnabled) => {
+ const markerLikeLiteral = "'/*__DBX_PRESERVE_BLOCK_COMMENT_0_0__*/'";
+ const otherComment = "/* another\r\ncomment */";
+ const source = `select a ${comment},b from t where x=1 and y=2;\n\n${otherComment}\nselect ${markerLikeLiteral} as note;`;
+ const settings = { customRulesEnabled, layoutStyle: "classic", logicalOperatorNewline: "none", commaPosition: "before", preserveEmptyLines: true } as const;
+ const formatted = await formatSqlText(source, dialect, settings);
+ expect(formatted).toContain(comment);
+ expect(formatted).toContain(otherComment);
+ expect(formatted).toContain(markerLikeLiteral);
+ expect(formatted.replace(markerLikeLiteral, "")).not.toContain("__DBX_PRESERVE_BLOCK_COMMENT_");
+ expect(tokenizeSqlSemantic(formatted, dialect).map((token) => token.normalized)).toEqual(tokenizeSqlSemantic(source, dialect).map((token) => token.normalized));
+ expect(await formatSqlText(formatted, dialect, settings)).toBe(formatted);
+ });
+
+ it("does not complete an unterminated CR block comment", async () => {
+ const source = "select a /* unfinished\r\n still unfinished";
+ const formatted = await formatSqlForEditing(source, "postgres", { preserveEmptyLines: true });
+ expect(formatted).not.toContain("*/");
+ expect(formatted).not.toContain("__DBX_PRESERVE_BLOCK_COMMENT_");
+ });
+
+ it.each([
+ ["postgres", "select * from t where c@?'$.x';", "c @? '$.x'"],
+ ["sqlserver", "select @myvar from t;", "@myvar"],
+ ["mysql", "select 'D d\\'D D' as note from t;", "'D d\\'D D'"],
+ ] as const)("preserves the %s operator, variable or escaped string boundary", async (dialect, source, expected) => {
+ const settings = { customRulesEnabled: true };
+ const formatted = await formatSqlText(source, dialect, settings);
+ expect(formatted).toContain(expected);
+ expect(await formatSqlText(formatted, dialect, settings)).toBe(formatted);
+ });
+
+ it.each(["\n", "\r\n"])("does not extend an empty line comment across %j", async (lineBreak) => {
+ const source = `--${lineBreak}select a,b from t;`;
+ const formatted = await formatSqlText(source, "postgres", { customRulesEnabled: true });
+ expect(formatted).toMatch(/^--\nSELECT/);
+ expect(tokenizeSqlSemantic(formatted, "postgres").map((token) => token.normalized)).toEqual(tokenizeSqlSemantic(source, "postgres").map((token) => token.normalized));
+ });
+ });
});
/**
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlFormatterConfig.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlFormatterConfig.spec.ts
index 1103b5d8cb..e57412e128 100644
--- a/apps/desktop/src/lib/__tests__/sql/sqlFormatterConfig.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/sqlFormatterConfig.spec.ts
@@ -127,3 +127,45 @@ describe("sqlFormatterConfig layout style", () => {
expect(parseSqlFormatterConfig(JSON.stringify({ version: 3, formatter: "sql-formatter", options: {} }))).toEqual({ ok: false, message: "Unsupported config version." });
});
});
+
+describe("SQL formatter custom rule configuration", () => {
+ it.each([20, 50, 76, 80, 120, 500])("accepts a width of %i columns", (expressionWidth) => {
+ const result = parseSqlFormatterConfig(JSON.stringify({ version: 2, formatter: "sql-formatter", options: { expressionWidth } }));
+ expect(result.ok).toBe(true);
+ if (result.ok) expect(result.settings.expressionWidth).toBe(expressionWidth);
+ });
+
+ it.each([19, 501, 76.5, "76", null])("rejects an invalid width %s", (expressionWidth) => {
+ expect(parseSqlFormatterConfig(JSON.stringify({ version: 2, formatter: "sql-formatter", options: { expressionWidth } }))).toEqual({ ok: false, message: "Invalid formatter option value: expressionWidth." });
+ });
+
+ it.each([
+ { listLayout: "unknown" },
+ { selectListLayout: "unknown" },
+ { insertListLayout: false },
+ { updateListLayout: 3 },
+ { customRulesEnabled: "true" },
+ { alignSelectAliases: 1 },
+ { alignUpdateAssignments: null },
+ { selectCommaPosition: "middle" },
+ { insertCommaPosition: true },
+ { updateCommaPosition: "middle" },
+ { whereLogicalOperatorNewline: "unknown" },
+ { onLogicalOperatorNewline: 1 },
+ { expressionLogicalOperatorNewline: false },
+ { listItemAlignment: "left" },
+ { newlineBeforeJoinOn: 1 },
+ { collapseShortStatements: null },
+ { emptyLineMode: "unknown" },
+ ])("rejects invalid explicit custom options %j", (options) => {
+ const result = parseSqlFormatterConfig(JSON.stringify({ version: 2, formatter: "sql-formatter", options }));
+ expect(result.ok).toBe(false);
+ });
+
+ it("keeps custom rule settings out of third-party formatter options", () => {
+ const options = sqlFormatterOptions({ customRulesEnabled: true, selectListLayout: "singleLine", expressionWidth: 76 });
+ expect(options.expressionWidth).toBe(76);
+ expect(options).not.toHaveProperty("customRulesEnabled");
+ expect(options).not.toHaveProperty("selectListLayout");
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlFormatterRules.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlFormatterRules.spec.ts
new file mode 100644
index 0000000000..c57f1a8691
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/sql/sqlFormatterRules.spec.ts
@@ -0,0 +1,386 @@
+import { describe, expect, it } from "vitest";
+import { formatSqlForDisplay, formatSqlText } from "@/lib/sql/sqlFormatter";
+import { normalizeSqlFormatterSettings, parseSqlFormatterConfig, serializeSqlFormatterConfig, type SqlFormatterSettings } from "@/lib/sql/sqlFormatterConfig";
+import { tokenizeSqlSemantic } from "@/lib/sql/semantic/tokens";
+
+const rules = (overrides: Partial<SqlFormatterSettings> = {}): Partial<SqlFormatterSettings> => ({ customRulesEnabled: true, ...overrides });
+
+describe("configurable SQL formatting rules (issue #8570)", () => {
+ it("keeps custom rules disabled when loading existing settings", () => {
+ expect(normalizeSqlFormatterSettings({ keywordCase: "lower", expressionWidth: 80 })).toMatchObject({
+ keywordCase: "lower",
+ expressionWidth: 80,
+ customRulesEnabled: false,
+ });
+ });
+
+ it("round-trips independent rules and the reference width through the production config parser", () => {
+ const settings = {
+ customRulesEnabled: true,
+ listLayout: "wrap",
+ selectListLayout: "vertical",
+ insertListLayout: "singleLine",
+ updateListLayout: "fit",
+ selectCommaPosition: "before",
+ insertCommaPosition: "after",
+ updateCommaPosition: "inherit",
+ alignSelectAliases: false,
+ alignUpdateAssignments: true,
+ whereLogicalOperatorNewline: "before",
+ onLogicalOperatorNewline: "after",
+ expressionLogicalOperatorNewline: "none",
+ newlineBeforeJoinOn: true,
+ collapseShortStatements: false,
+ emptyLineMode: "single",
+ listItemAlignment: "indent",
+ expressionWidth: 76,
+ };
+ const parsed = parseSqlFormatterConfig(JSON.stringify({ version: 2, formatter: "sql-formatter", options: settings }));
+ expect(parsed.ok).toBe(true);
+ if (!parsed.ok) return;
+ expect(parsed.settings).toMatchObject(settings);
+ expect(parseSqlFormatterConfig(serializeSqlFormatterConfig(parsed.settings))).toEqual(parsed);
+ });
+
+ it("can keep a SELECT list on one line independently of INSERT and UPDATE", async () => {
+ const result = await formatSqlText("select deptno as department_number, dname as department_name, loc as department_location from dept;", "oracle", rules({ selectListLayout: "singleLine" }));
+ expect(result).toContain("SELECT deptno AS department_number, dname AS department_name, loc AS department_location");
+ });
+
+ it("can expand INSERT target columns and each VALUES tuple independently", async () => {
+ const result = await formatSqlText("insert into dept (deptno,dname,loc) values (10,'Accounting','New York'),(20,'Sales','Boston');", "oracle", rules({ insertListLayout: "vertical" }));
+ expect(result).toMatch(/dept\s*\(\s*deptno,\n\s*dname,\n\s*loc\s*\)/i);
+ expect(result).toMatch(/\(\s*10,\n\s*'Accounting',\n\s*'New York'\s*\)/);
+ expect(result).toMatch(/\(\s*20,\n\s*'Sales',\n\s*'Boston'\s*\)/);
+ });
+
+ it("can expand and align UPDATE assignments without collapsing the whole statement", async () => {
+ const result = await formatSqlText("update dept set dname='Accounting',loc='New York' where deptno=10;", "oracle", rules({ updateListLayout: "vertical", alignUpdateAssignments: true }));
+ expect(result).toMatch(/SET dname = 'Accounting',\n\s*loc\s+= 'New York'/);
+ });
+
+ it("combines right-aligned keywords with independent list rules", async () => {
+ const result = await formatSqlText("select a,b from dept; insert into dept (a,b) values (1,2);", "oracle", rules({ indentStyle: "tabularRight", selectListLayout: "singleLine", insertListLayout: "vertical" }));
+ expect(result).toMatch(/SELECT +a, b/);
+ expect(result).toMatch(/\(\s*a,\n\s*b\s*\)/);
+ });
+
+ it("gives JOIN ON and WHERE their own logical operator placement", async () => {
+ const result = await formatSqlText(
+ "select a.id from a join b on a.id=b.id and a.kind=b.kind where a.x=1 and b.y=2;",
+ "oracle",
+ rules({
+ selectListLayout: "singleLine",
+ newlineBeforeJoinOn: true,
+ onLogicalOperatorNewline: "after",
+ whereLogicalOperatorNewline: "before",
+ }),
+ );
+ expect(result).toMatch(/\n\s*ON a\.id = b\.id AND\n\s*a\.kind = b\.kind/);
+ expect(result).toMatch(/WHERE a\.x = 1\n\s*AND b\.y = 2/);
+ });
+
+ it("restores the original classic layout when custom rules are disabled", async () => {
+ const sql = "select a,b from dept where a=1 and b=2;";
+ const baseline = await formatSqlText(sql, "oracle", { layoutStyle: "classic" });
+ const disabled = await formatSqlText(sql, "oracle", { layoutStyle: "classic", customRulesEnabled: false, selectListLayout: "singleLine", whereLogicalOperatorNewline: "none" });
+ expect(disabled).toBe(baseline);
+ });
+
+ it.each(["singleLine", "fit", "vertical", "wrap"] as const)("implements the %s list mode rather than just changing the option", async (selectListLayout) => {
+ const options = rules({ selectListLayout, expressionWidth: 36, collapseShortStatements: false });
+ const result = await formatSqlText("select alpha_col,bravo_col,charlie_col from t;", "oracle", options);
+ if (selectListLayout === "singleLine") expect(result).toContain("SELECT alpha_col, bravo_col, charlie_col");
+ else if (selectListLayout === "wrap") expect(result).toMatch(/SELECT alpha_col, bravo_col,\n\s*charlie_col/);
+ else expect(result).toMatch(/SELECT alpha_col,\n\s*bravo_col,\n\s*charlie_col/);
+ expect(await formatSqlText(result, "oracle", options)).toBe(result);
+ });
+
+ it("honours general list rules recursively in functions, IN and a nested subquery", async () => {
+ const options = rules({ listLayout: "vertical", selectListLayout: "singleLine", collapseShortStatements: true });
+ const result = await formatSqlText("select coalesce(a,b) as x from t where id in (1,2,3) and k in (select coalesce(c,d) from u);", "oracle", options);
+ expect(result).toMatch(/coalesce\(a,\n\s*b\)/i);
+ expect(result).toMatch(/IN \(1,\n\s*2,\n\s*3\)/);
+ expect(result).toMatch(/coalesce\(c,\n\s*d\)/i);
+ expect(await formatSqlText(result, "oracle", options)).toBe(result);
+ });
+
+ it("does not treat a function inside an INSERT value as another INSERT tuple", async () => {
+ const result = await formatSqlText("insert into t (a,b) values (f(1,2),3);", "oracle", rules({ insertListLayout: "vertical", listLayout: "singleLine" }));
+ expect(result).toContain("f(1, 2)");
+ expect(result).toMatch(/f\(1, 2\),\n\s*3/);
+ });
+
+ it("applies expression rules inside CASE without splitting BETWEEN's AND", async () => {
+ const options = rules({ selectListLayout: "singleLine", expressionLogicalOperatorNewline: "after", whereLogicalOperatorNewline: "before" });
+ const result = await formatSqlText("select case when a=1 and b=2 then coalesce(c,d) else e end as x from t where id between 1 and 2 and k=3;", "oracle", options);
+ expect(result).toMatch(/WHEN a = 1 AND\n\s*b = 2 THEN/);
+ expect(result).toMatch(/BETWEEN 1 AND 2\n\s*AND k = 3/);
+ expect(await formatSqlText(result, "oracle", options)).toBe(result);
+ });
+
+ it("applies nested list rules inside BETWEEN bounds and composite property access", async () => {
+ const options = rules({ listLayout: "vertical", selectListLayout: "singleLine" });
+ const result = await formatSqlText("select (get_row(a,b)).value from t where n between coalesce(low_a,low_b) and coalesce(high_a,high_b);", "postgres", options);
+ expect(result).toMatch(/get_row\(a,\n\s*b\)/);
+ expect(result).toMatch(/coalesce\(low_a,\n\s*low_b\)/);
+ expect(result).toMatch(/coalesce\(high_a,\n\s*high_b\)/);
+ expect(await formatSqlText(result, "postgres", options)).toBe(result);
+ });
+
+ it("honours nested list rules in LIMIT and set-operation operands", async () => {
+ const options = rules({ listLayout: "vertical", selectListLayout: "singleLine", collapseShortStatements: false, indentStyle: "tabularRight" });
+ const result = await formatSqlText("select a from t limit coalesce(10,20); select a from t union all values (coalesce(1,2));", "postgres", options);
+ expect(result).toMatch(/LIMIT coalesce\(10,\n\s*20\)/i);
+ expect(result).toMatch(/coalesce\(1,\n\s*2\)/i);
+ expect(await formatSqlText(result, "postgres", options)).toBe(result);
+ });
+
+ it.each(["fit", "wrap"] as const)("keeps nested %s widths independent of the SELECT single-line rule", async (listLayout) => {
+ const options = rules({ listLayout, selectListLayout: "singleLine", expressionWidth: 44, collapseShortStatements: false });
+ const result = await formatSqlText("select coalesce(alpha_col,bravo_col,charlie_col,delta_col) from t;", "postgres", options);
+ if (listLayout === "fit") expect(result).toMatch(/coalesce\(alpha_col,\n\s*bravo_col,\n\s*charlie_col,\n\s*delta_col\)/);
+ else expect(result).toMatch(/coalesce\(alpha_col, bravo_col,\n\s*charlie_col, delta_col\)/);
+ expect(result.split("\n").every((line) => line.length <= 44)).toBe(true);
+ expect(await formatSqlText(result, "postgres", options)).toBe(result);
+ });
+
+ it("keeps single-line function arguments and scalar CASE items allowed to exceed the width", async () => {
+ const options = rules({ listLayout: "singleLine", selectListLayout: "singleLine", expressionWidth: 20, collapseShortStatements: false });
+ const result = await formatSqlText("select coalesce(alpha_col,bravo_col),case when a=1 then 'a long literal' else 'another long literal' end as label from t;", "postgres", options);
+ expect(result).toContain("SELECT coalesce(alpha_col, bravo_col), CASE WHEN a = 1 THEN 'a long literal' ELSE 'another long literal' END AS label");
+ expect(await formatSqlText(result, "postgres", options)).toBe(result);
+ });
+
+ it.each(["before", "after"] as const)("keeps SELECT annotations safe with %s commas", async (selectCommaPosition) => {
+ const sql = "select a as x, -- first field\n long_name as y, /* next field */\n c as z from t;";
+ const options = rules({ selectListLayout: "vertical", selectCommaPosition });
+ const result = await formatSqlText(sql, "oracle", options);
+ expect(result).toContain("-- first field");
+ expect(result).toContain("/* next field */");
+ const tokens = (value: string) =>
+ tokenizeSqlSemantic(value, "oracle")
+ .filter((token) => token.kind !== "comment")
+ .map((token) => token.normalized);
+ expect(tokens(result)).toEqual(tokens(sql));
+ expect(await formatSqlText(result, "oracle", options)).toBe(result);
+ });
+
+ it("allows the three DML comma and alignment rules to differ", async () => {
+ const options = rules({ selectListLayout: "vertical", selectCommaPosition: "before", updateListLayout: "vertical", updateCommaPosition: "after", alignSelectAliases: false, alignUpdateAssignments: true });
+ const result = await formatSqlText("select a as x,long_name as y from t; update t set a=1,long_name=2;", "oracle", options);
+ expect(result).toMatch(/SELECT a AS x\n\s*, long_name AS y/);
+ expect(result).toMatch(/SET a\s+= 1,\n\s*long_name = 2/);
+ expect(await formatSqlText(result, "oracle", options)).toBe(result);
+ });
+
+ it("keeps inline commas adjacent to their DML items when leading commas are selected", async () => {
+ const options = rules({ selectListLayout: "singleLine", insertListLayout: "singleLine", updateListLayout: "singleLine", selectCommaPosition: "before", insertCommaPosition: "before", updateCommaPosition: "before", collapseShortStatements: false });
+ const result = await formatSqlText("select a,b from t; insert into t (a,b) values(1,2); update t set a=1,b=2;", "oracle", options);
+ expect(result).toContain("SELECT a, b");
+ expect(result).toContain("t (a, b)");
+ expect(result).toContain("VALUES (1, 2)");
+ expect(result).toContain("SET a = 1, b = 2");
+ expect(await formatSqlText(result, "oracle", options)).toBe(result);
+ });
+
+ it("measures leading commas at the wrap boundary without adding a space before them", async () => {
+ const options = rules({ selectListLayout: "wrap", selectCommaPosition: "before", expressionWidth: 20, collapseShortStatements: false });
+ const result = await formatSqlText("select aaaaa,bbbbbb,ccc from t;", "oracle", options);
+ expect(result).toMatch(/SELECT aaaaa, bbbbbb\n\s*, ccc/);
+ expect(result.split("\n").every((line) => line.length <= 20)).toBe(true);
+ expect(await formatSqlText(result, "oracle", options)).toBe(result);
+ });
+
+ it("keeps VALUES set operands on the existing DML list rules", async () => {
+ const sql = "select 0 union all values (coalesce(1,2),3),(4,5);";
+ const options = rules({ listLayout: "vertical", insertListLayout: "inherit", selectListLayout: "singleLine", commaPosition: "before", collapseShortStatements: false });
+ const diagnostics: string[] = [];
+ const result = await formatSqlText(sql, "postgres", options, (value) => diagnostics.push(value));
+ expect(result).toMatch(/coalesce\(1\n\s*, 2\)\n\s*, 3\)/);
+ expect(result).toMatch(/\(4\n\s*, 5\)/);
+ expect(tokenizeSqlSemantic(result, "postgres").map((token) => token.normalized)).toEqual(tokenizeSqlSemantic(sql, "postgres").map((token) => token.normalized));
+ expect(diagnostics).toEqual([]);
+ expect(await formatSqlText(result, "postgres", options)).toBe(result);
+ });
+
+ it.each([
+ ["oracle", `select coalesce("a,b", q'[x, AND 'y like z']') as note, :p as p from t where id between 1 and 2 and label='OR'; -- tail`],
+ ["mysql", "select coalesce(`a,b`, 'x, AND y') as note, :p as p from t where id between 1 and 2 and label='OR'; -- tail"],
+ ["postgres", `select coalesce("a,b", $tag$x,\n\nAND 'y'$tag$) as note, :p as p from t where id between 1 and 2 and label='OR'; /* tail */`],
+ ["sqlserver", "select coalesce([a,b], 'x, AND y') as note, @p as p from t where id between 1 and 2 and label='OR'; -- tail"],
+ ] as const)("preserves protected %s tokens and is idempotent", async (dialect, sql) => {
+ const options = rules({ listLayout: "vertical", selectCommaPosition: "before", emptyLineMode: "single", expressionWidth: 76 });
+ const protectedTokens = (value: string) =>
+ tokenizeSqlSemantic(value, dialect)
+ .filter((token) => ["comment", "string", "quoted_identifier", "parameter"].includes(token.kind))
+ .map((token) => token.text);
+ const result = await formatSqlText(sql, dialect, options);
+ expect(protectedTokens(result)).toEqual(protectedTokens(sql));
+ expect(await formatSqlText(result, dialect, options)).toBe(result);
+ });
+
+ it("collapses code-only empty lines without rewriting literal or block-comment paragraphs", async () => {
+ const sql = "select 'first\n\n\nlast' as text, a\n\n\n\nfrom t /* first\n\n\nlast */ where id=1;";
+ const result = await formatSqlText(sql, "oracle", rules({ emptyLineMode: "single" }));
+ expect(result).toContain("'first\n\n\nlast'");
+ expect(result).toContain("/* first\n\n\nlast */");
+ expect(result.replace("'first\n\n\nlast'", "literal").replace("/* first\n\n\nlast */", "comment")).not.toMatch(/\n(?:[ \t]*\n){2}/);
+ expect(result).not.toContain("__DBX_PRESERVE_EMPTY_LINE_");
+ });
+
+ it.each(["remove", "single", "preserve"] as const)("keeps alternative quoted literals intact with %s rules", async (emptyLineMode) => {
+ const literal = "nQ'{first 'quoted'\r\n\r\n-- AND is data\r\nlast}'";
+ const source = `select ${literal} as note, q'!second 'quoted'\nlast!' as other from dual;\n\nselect :id from dual;`;
+ const options = rules({ emptyLineMode, selectListLayout: "vertical", preserveEmptyLines: false });
+ const result = await formatSqlText(source, "oracle", options);
+ expect(result).toContain(literal);
+ expect(tokenizeSqlSemantic(result, "oracle").map((token) => token.normalized)).toEqual(tokenizeSqlSemantic(source, "oracle").map((token) => token.normalized));
+ expect(await formatSqlText(result, "oracle", options)).toBe(result);
+ });
+
+ it("keeps a line comment boundary even when WHERE rules request no logical breaks", async () => {
+ const source = "select a,b from t where x=1 -- note\r\nand y=2;";
+ const options = rules({ whereLogicalOperatorNewline: "none" });
+ const result = await formatSqlText(source, "postgres", options);
+ expect(result).toMatch(/-- note\n\s*AND y = 2/);
+ expect(tokenizeSqlSemantic(result, "postgres").map((token) => token.normalized)).toEqual(tokenizeSqlSemantic(source, "postgres").map((token) => token.normalized));
+ expect(await formatSqlText(result, "postgres", options)).toBe(result);
+ });
+
+ it.each(["preserve", "single", "inherit"] as const)("does not mistake quoted or commented marker-like lines for %s empty lines", async (emptyLineMode) => {
+ const sql = "select 'first\n-- __DBX_PRESERVE_EMPTY_LINE_0_0__\nlast' as note from t;\n\nselect 2; /* first\n-- __DBX_PRESERVE_EMPTY_LINE_0_0__\nlast */";
+ const options = rules({ emptyLineMode, preserveEmptyLines: true });
+ const protectedTokens = (value: string) =>
+ tokenizeSqlSemantic(value, "oracle")
+ .filter((token) => ["string", "comment"].includes(token.kind))
+ .map((token) => token.text);
+ const result = await formatSqlText(sql, "oracle", options);
+ expect(protectedTokens(result)).toEqual(protectedTokens(sql));
+ expect(await formatSqlText(result, "oracle", options)).toBe(result);
+ });
+
+ it("keeps complete PL/SQL blocks on the established base formatter and reports the fallback", async () => {
+ const sql = "begin select a,b into x,y from t; x:=1; end;";
+ const base = await formatSqlText(sql, "oracle", { layoutStyle: "classic" });
+ const diagnostics: string[] = [];
+ const result = await formatSqlText(sql, "oracle", rules({ layoutStyle: "classic" }), (diagnostic) => diagnostics.push(diagnostic));
+ expect(result).toBe(base);
+ expect(diagnostics).toEqual(["custom-rules-fallback"]);
+ });
+
+ it.each(["remove", "single"] as const)("restores saved base spacing when %s rules decline a procedure script", async (emptyLineMode) => {
+ const sql = "-- heading\n\nbegin select 1 into x from dual; x:=1; end; select 2 from dual;";
+ const saved = { layoutStyle: "classic", preserveEmptyLines: true, linesBetweenQueries: 2 } as const;
+ const base = await formatSqlText(sql, "oracle", saved);
+ const diagnostics: string[] = [];
+ const result = await formatSqlText(sql, "oracle", rules({ ...saved, emptyLineMode }), (value) => diagnostics.push(value));
+ expect(result).toBe(base);
+ expect(diagnostics).toEqual(["custom-rules-fallback"]);
+ });
+
+ it("falls back for a complete FUNCTION while its independent SQL selection uses the rules", async () => {
+ const query = "select deptno,dname into v_id,v_name from dept where deptno=p_id and loc='Boston';";
+ const sql = `create or replace function department_label(p_id number) return varchar2 is\n v_id number;\n v_name varchar2(100);\nbegin\n ${query}\n v_name := trim(v_name);\n return v_name;\nexception when no_data_found then return 'unknown';\nend;`;
+ const options = rules({ layoutStyle: "classic", selectListLayout: "vertical" });
+ const diagnostics: string[] = [];
+ const base = await formatSqlText(sql, "oracle", { layoutStyle: "classic" });
+ expect(await formatSqlText(sql, "oracle", options, (value) => diagnostics.push(value))).toBe(base);
+ expect(diagnostics).toEqual(["custom-rules-fallback"]);
+ diagnostics.length = 0;
+ expect(await formatSqlText(query, "oracle", options, (value) => diagnostics.push(value))).toMatch(/SELECT deptno,\n\s*dname/);
+ expect(diagnostics).toEqual([]);
+ });
+
+ it("retains the source if neither rule nor base formatting can parse the input", async () => {
+ const sql = "declare v_name varchar2(100) := 'unfinished";
+ const diagnostics: string[] = [];
+ await expect(formatSqlText(sql, "oracle", rules(), (value) => diagnostics.push(value))).rejects.toThrow();
+ expect(diagnostics).toEqual([]);
+ expect(await formatSqlForDisplay(sql, "oracle", rules())).toBe(sql);
+ });
+
+ it.each(["firstItem", "indent"] as const)("positions list continuations with %s alignment", async (listItemAlignment) => {
+ const result = await formatSqlText("select a,b from t;", "oracle", rules({ listItemAlignment, selectListLayout: "vertical", tabWidth: 4 }));
+ expect(result).toContain(`SELECT a,\n${" ".repeat(listItemAlignment === "firstItem" ? 7 : 4)}b`);
+ });
+
+ it("lets ON none override the global operator break without changing WHERE", async () => {
+ const options = rules({ newlineBeforeJoinOn: true, onLogicalOperatorNewline: "none", logicalOperatorNewline: "before", selectListLayout: "singleLine" });
+ const result = await formatSqlText("select a.id from a join b on a.id=b.id and a.x=b.x where a.y=1 and b.z=2;", "oracle", options);
+ expect(result).toMatch(/ON a\.id = b\.id AND a\.x = b\.x/);
+ expect(result).toMatch(/WHERE a\.y = 1\n\s*AND b\.z = 2/);
+ expect(await formatSqlText(result, "oracle", options)).toBe(result);
+ });
+
+ it("keeps DBX placeholders and an indivisible long literal intact at a narrow width", async () => {
+ const literal = "'a comma, AND a very long literal that must not be split'";
+ const sql = "select ${like} as x, #{Id} as y, " + literal + " as z from t;";
+ const options = rules({ expressionWidth: 20, selectListLayout: "wrap", selectCommaPosition: "before", functionCase: "lower" });
+ const result = await formatSqlText(sql, "mysql", options);
+ expect(result).toContain("${like}");
+ expect(result).toContain("#{Id}");
+ expect(result).toContain(literal);
+ expect(await formatSqlText(result, "mysql", options)).toBe(result);
+ });
+
+ it.each(["standard", "tabularLeft", "tabularRight"] as const)("uses %s keyword columns together with list rules", async (indentStyle) => {
+ const options = rules({ indentStyle, selectListLayout: "vertical", collapseShortStatements: false });
+ const result = await formatSqlText("select a,b from t where id=1;", "oracle", options);
+ const lines = result.split("\n");
+ const select = lines.find((line) => /\bSELECT\b/.test(line))!;
+ const from = lines.find((line) => /\bFROM\b/.test(line))!;
+ const where = lines.find((line) => /\bWHERE\b/.test(line))!;
+ if (indentStyle === "tabularLeft") expect([select.indexOf("a"), from.indexOf("t"), where.indexOf("id")]).toEqual([7, 7, 7]);
+ else if (indentStyle === "tabularRight") expect([select.indexOf("SELECT") + 6, from.indexOf("FROM") + 4, where.indexOf("WHERE") + 5]).toEqual([6, 6, 6]);
+ else expect([select.indexOf("SELECT"), from.indexOf("FROM"), where.indexOf("WHERE")]).toEqual([0, 0, 0]);
+ expect(await formatSqlText(result, "oracle", options)).toBe(result);
+ });
+
+ it("keeps the first keyword's right padding when a later keyword is longer", async () => {
+ const options = rules({ indentStyle: "tabularRight", selectListLayout: "vertical", collapseShortStatements: false });
+ const result = await formatSqlText("select a,b from t order by a,b;", "oracle", options);
+ expect(result).toMatch(/^ SELECT a,/);
+ expect(result).toMatch(/\n FROM t/);
+ expect(result).toMatch(/\nORDER BY a, b/);
+ expect(await formatSqlText(result, "oracle", options)).toBe(result);
+ });
+
+ it("lets all DML lists inherit the general rule without losing their individual values", async () => {
+ const options = rules({ listLayout: "singleLine", selectListLayout: "inherit", insertListLayout: "inherit", updateListLayout: "inherit", collapseShortStatements: false });
+ const result = await formatSqlText("select a,b from t; insert into t (a,b) values(1,2); update t set a=1,b=2;", "oracle", options);
+ expect(result).toContain("SELECT a, b");
+ expect(result).toContain("t (a, b)");
+ expect(result).toContain("VALUES (1, 2)");
+ expect(result).toContain("SET a = 1, b = 2");
+ });
+
+ it.each(["remove", "single", "preserve", "inherit"] as const)("applies the %s empty-line mode to code paragraphs", async (emptyLineMode) => {
+ const result = await formatSqlText("-- heading\n\n\nSELECT a,b FROM t;", "oracle", rules({ emptyLineMode, preserveEmptyLines: true }));
+ const breaks = emptyLineMode === "remove" ? "\n" : emptyLineMode === "single" ? "\n\n" : "\n\n\n";
+ expect(result).toContain(`-- heading${breaks}SELECT`);
+ expect(result).not.toContain("__DBX_PRESERVE_EMPTY_LINE_");
+ });
+
+ it.each([
+ ["remove", 0],
+ ["single", 1],
+ ["preserve", 2],
+ ["inherit", 2],
+ ] as const)("limits generated query spacing with emptyLineMode=%s", async (emptyLineMode, blankLines) => {
+ const options = rules({ emptyLineMode, linesBetweenQueries: 2 });
+ const result = await formatSqlText("select 1; select 2;", "oracle", options);
+ expect(result).toBe(`SELECT 1;${"\n".repeat(blankLines + 1)}SELECT 2;`);
+ expect(await formatSqlText(result, "oracle", options)).toBe(result);
+ });
+
+ it("preserves the saved query spacing when custom rules are disabled", async () => {
+ expect(await formatSqlText("select 1; select 2;", "oracle", { customRulesEnabled: false, emptyLineMode: "remove", linesBetweenQueries: 2 })).toBe("SELECT 1;\n\n\nSELECT 2;");
+ });
+
+ it.each(["preserve", "upper", "lower"] as const)("keeps functionCase=%s when arguments must expand", async (functionCase) => {
+ const result = await formatSqlText("select CoAlEsCe(a,b) from t;", "postgres", rules({ listLayout: "vertical", selectListLayout: "singleLine", functionCase }));
+ const name = functionCase === "preserve" ? "CoAlEsCe" : functionCase === "upper" ? "COALESCE" : "coalesce";
+ expect(result).toMatch(new RegExp(`${name}\\(a,\\n\\s*b\\)`));
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlFormatterRulesFallback.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlFormatterRulesFallback.spec.ts
new file mode 100644
index 0000000000..fe1c489cd4
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/sql/sqlFormatterRulesFallback.spec.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it, vi } from "vitest";
+
+// Simulate the external package moving its private parser, not our own layout behavior.
+vi.mock("sql-formatter/dist/esm/parser/createParser.js", () => {
+ throw new Error("External parser module unavailable");
+});
+
+import { formatSqlText } from "@/lib/sql/sqlFormatter";
+import { tokenizeSqlSemantic } from "@/lib/sql/semantic/tokens";
+
+describe("custom rule engine recovery", () => {
+ it("keeps the public formatter usable and reports the downgrade once", async () => {
+ const source = "select a,b from t where id=1;";
+ const base = await formatSqlText(source, "oracle", { layoutStyle: "classic" });
+ const diagnostics: string[] = [];
+ const result = await formatSqlText(source, "oracle", { customRulesEnabled: true, selectListLayout: "singleLine", layoutStyle: "classic" }, (diagnostic) => diagnostics.push(diagnostic));
+ expect(result).toBe(base);
+ expect(diagnostics).toEqual(["custom-rules-fallback"]);
+ });
+
+ it.each(["remove", "single"] as const)("restores original input and base spacing after the engine declines %s rules", async (emptyLineMode) => {
+ const source = "-- heading\n\nselect a,b from t; select 2;";
+ const saved = { layoutStyle: "classic", preserveEmptyLines: true, linesBetweenQueries: 2 } as const;
+ const base = await formatSqlText(source, "oracle", saved);
+ const diagnostics: string[] = [];
+ const result = await formatSqlText(source, "oracle", { ...saved, customRulesEnabled: true, emptyLineMode }, (value) => diagnostics.push(value));
+ expect(result).toBe(base);
+ expect(diagnostics).toEqual(["custom-rules-fallback"]);
+ });
+
+ it("preserves multiline q literals and line comment boundaries when the private engine is unavailable", async () => {
+ const literal = "q'[first 'quoted'\r\n \t\r\nlast]'";
+ const comment = "/* first\r\n\r\nlast */";
+ const source = `select ${literal} as note ${comment} from dual where x=1 -- note\nand y=2;`;
+ const saved = { layoutStyle: "classic", preserveEmptyLines: true, logicalOperatorNewline: "none" } as const;
+ const diagnostics: string[] = [];
+ const result = await formatSqlText(source, "oracle", { ...saved, customRulesEnabled: true }, (value) => diagnostics.push(value));
+ expect(result).toContain(literal);
+ expect(result).toContain(comment);
+ expect(result).toMatch(/-- note\n\s*AND y = 2/);
+ expect(tokenizeSqlSemantic(result, "oracle").map((token) => token.normalized)).toEqual(tokenizeSqlSemantic(source, "oracle").map((token) => token.normalized));
+ expect(result).toBe(await formatSqlText(source, "oracle", saved));
+ expect(await formatSqlText(result, "oracle", { ...saved, customRulesEnabled: true })).toBe(result);
+ expect(diagnostics).toEqual(["custom-rules-fallback"]);
+ });
+});
diff --git a/apps/desktop/src/lib/settings/__tests__/settingsSearch.spec.ts b/apps/desktop/src/lib/settings/__tests__/settingsSearch.spec.ts
index b92e40e163..60e4c2f8ad 100644
--- a/apps/desktop/src/lib/settings/__tests__/settingsSearch.spec.ts
+++ b/apps/desktop/src/lib/settings/__tests__/settingsSearch.spec.ts
@@ -75,6 +75,42 @@ describe("settings search", () => {
expect(searchSettings(entries, "line number", "en").map((entry) => entry.id)).toEqual(["editor-line-numbers"]);
});
+ it("indexes the new formatter rules and preview in the formatter settings group", () => {
+ const formatterEntries = resolveSettingsSearchEntries(
+ SETTINGS_SEARCH_DEFINITIONS.filter((entry) => entry.id.startsWith("formatter-")),
+ { isWeb: false, visibleCategories: new Set<SettingsCategory>(["formatter"]) },
+ (key) =>
+ ({
+ "settings.sqlFormatterCustomRules": "Custom SQL rules",
+ "settings.sqlFormatterListLayout": "General list layout",
+ "settings.sqlFormatterSelectListLayout": "SELECT list",
+ "settings.sqlFormatterInsertListLayout": "INSERT list",
+ "settings.sqlFormatterUpdateListLayout": "UPDATE list",
+ "settings.sqlFormatterListItemAlignment": "List item alignment",
+ "settings.sqlFormatterEmptyLineMode": "Empty line mode",
+ "settings.sqlFormatterAlignSelectAliases": "Align SELECT aliases",
+ "settings.sqlFormatterAlignUpdateAssignments": "Align UPDATE assignments",
+ "settings.sqlFormatterSelectCommaPosition": "SELECT comma position",
+ "settings.sqlFormatterInsertCommaPosition": "INSERT comma position",
+ "settings.sqlFormatterUpdateCommaPosition": "UPDATE comma position",
+ "settings.sqlFormatterWhereLogicalOperatorNewline": "WHERE logical operator newline",
+ "settings.sqlFormatterOnLogicalOperatorNewline": "ON logical operator newline",
+ "settings.sqlFormatterExpressionLogicalOperatorNewline": "Expression logical operator newline",
+ "settings.sqlFormatterNewlineBeforeJoinOn": "Newline before JOIN ON",
+ "settings.sqlFormatterCollapseShortStatements": "Collapse short statements",
+ "settings.sqlFormatterPreview": "Formatting preview",
+ })[key] ?? key,
+ categoryLabels,
+ );
+ expect(searchSettings(formatterEntries, "SELECT list", "en").map((entry) => entry.id)).toContain("formatter-select-layout");
+ expect(searchSettings(formatterEntries, "preview", "en").map((entry) => entry.id)).toContain("formatter-preview");
+ expect(searchSettings(formatterEntries, "empty line", "en").map((entry) => entry.id)).toContain("formatter-empty-line-mode");
+ expect(searchSettings(formatterEntries, "align UPDATE", "en").map((entry) => entry.id)).toContain("formatter-align-update-assignments");
+ expect(searchSettings(formatterEntries, "WHERE logical", "en").map((entry) => entry.id)).toContain("formatter-where-logical-newline");
+ expect(formatterEntries.find((entry) => entry.id === "formatter-custom-rules")?.targetId).toBe("formatter");
+ expect(formatterEntries.every((entry) => entry.route?.formatterMode === "form" || entry.route?.formatterMode === "json")).toBe(true);
+ });
+
it("indexes the query editor caret-browsing preference (#11827)", () => {
const definition = SETTINGS_SEARCH_DEFINITIONS.find((entry) => entry.id === "editor-caret-browsing");
expect(definition).toEqual({
@@ -402,6 +438,18 @@ describe("settings search", () => {
{ titleKey: "settings.sqlFormatterDenseOperators", category: "formatter", targetId: "formatter" },
{ titleKey: "settings.sqlFormatterNewlineBeforeSemicolon", category: "formatter", targetId: "formatter" },
{ titleKey: "settings.sqlFormatterParamTypes", category: "formatter", targetId: "formatter" },
+ { titleKey: "settings.sqlFormatterListItemAlignment", category: "formatter", targetId: "formatter" },
+ { titleKey: "settings.sqlFormatterEmptyLineMode", category: "formatter", targetId: "formatter" },
+ { titleKey: "settings.sqlFormatterAlignSelectAliases", category: "formatter", targetId: "formatter" },
+ { titleKey: "settings.sqlFormatterAlignUpdateAssignments", category: "formatter", targetId: "formatter" },
+ { titleKey: "settings.sqlFormatterSelectCommaPosition", category: "formatter", targetId: "formatter" },
+ { titleKey: "settings.sqlFormatterInsertCommaPosition", category: "formatter", targetId: "formatter" },
+ { titleKey: "settings.sqlFormatterUpdateCommaPosition", category: "formatter", targetId: "formatter" },
+ { titleKey: "settings.sqlFormatterWhereLogicalOperatorNewline", category: "formatter", targetId: "formatter" },
+ { titleKey: "settings.sqlFormatterOnLogicalOperatorNewline", category: "formatter", targetId: "formatter" },
+ { titleKey: "settings.sqlFormatterExpressionLogicalOperatorNewline", category: "formatter", targetId: "formatter" },
+ { titleKey: "settings.sqlFormatterNewlineBeforeJoinOn", category: "formatter", targetId: "formatter" },
+ { titleKey: "settings.sqlFormatterCollapseShortStatements", category: "formatter", targetId: "formatter" },
{ titleKey: "settings.routineSourceOpenMode", category: "navigation", targetId: "navigation" },
{ titleKey: "settings.disconnectTabHandlingMode", category: "navigation", targetId: "navigation" },
{ titleKey: "settings.compactColumnHeaderActions", category: "data", targetId: "data" },
diff --git a/apps/desktop/src/lib/settings/__tests__/settingsSearchCoverage.spec.ts b/apps/desktop/src/lib/settings/__tests__/settingsSearchCoverage.spec.ts
index 4b43c30d9f..002eff8360 100644
--- a/apps/desktop/src/lib/settings/__tests__/settingsSearchCoverage.spec.ts
+++ b/apps/desktop/src/lib/settings/__tests__/settingsSearchCoverage.spec.ts
@@ -55,6 +55,9 @@ const auditedNonLiteralLabels: Record<string, string> = {
"t(def.labelKey)": "APP_CUSTOM_UI_COLOR_DEFS tested below",
"getToolbarVisibilityItemLabel(item)": "Toolbar controls and index share TOOLBAR_VISIBILITY_ITEMS",
"t(tool.labelKey)": "MCP_TOOL_OPTIONS tested below",
+ "t(`settings.${titleKey}`) t(option.labelKey)": "Formatter rule titles and option labels derived from the SFC below",
+ "t(`settings.${titleKey}`)": "Formatter rule titles derived from the SFC below",
+ "t(`settings.${titleKey}`) t(`settings.sqlFormatterRule_${value}`)": "Formatter rule titles and enum labels derived from the SFC below",
database: "User-owned database names must never enter the static search index",
Authentication: "Static AI protocol alias tested below",
Endpoint: "Static AI protocol alias tested below",
@@ -120,6 +123,14 @@ function inspectSettingsTemplates(entry: string): Map<string, Set<string>> {
if (/ThemeCustomizerDialog|DataGridTypeColorSchemeDialog/.test(file)) {
for (const match of script.matchAll(/labelKey:\s*["']([^"']+)["']|label:\s*t\(\s*["']([^"']+)["']/g)) keys.add(match[1] ?? match[2]);
}
+ // Formatter rule rows render their labels from local definitions rather than literal template keys.
+ if (file.endsWith("SqlFormatterSettingsPanel.vue")) {
+ for (const match of script.matchAll(/titleKey:\s*["']([^"']+)["']/g)) keys.add(`settings.${match[1]}`);
+ for (const match of script.matchAll(/labelKey:\s*["']([^"']+)["']/g)) keys.add(match[1]);
+ const ruleEnums = script.match(/const ruleEnums = \{([\s\S]*?)\} as const;/)?.[1];
+ if (!ruleEnums) throw new Error("Formatter rule enum source is missing");
+ for (const match of ruleEnums.matchAll(/["']([^"']+)["']/g)) keys.add(`settings.sqlFormatterRule_${match[1]}`);
+ }
findings.set(relative(src, file), keys);
for (const component of components) {
if (excludedComponents[component]) continue;
diff --git a/apps/desktop/src/lib/settings/__tests__/settingsTransfer.spec.ts b/apps/desktop/src/lib/settings/__tests__/settingsTransfer.spec.ts
index 5e3df9a3d1..87724930b6 100644
--- a/apps/desktop/src/lib/settings/__tests__/settingsTransfer.spec.ts
+++ b/apps/desktop/src/lib/settings/__tests__/settingsTransfer.spec.ts
@@ -552,6 +552,41 @@ describe("settingsTransfer", () => {
expect(result.value.editorSettings.sqlFormatter?.commaPosition).toBe("after");
});
+ it("imports a pre-custom-rules application backup without dropping existing settings", () => {
+ const current = DEFAULT_EDITOR_SETTINGS.sqlFormatter;
+ const oldKeys = [
+ "layoutStyle",
+ "keywordCase",
+ "dataTypeCase",
+ "functionCase",
+ "identifierCase",
+ "indentStyle",
+ "useTabs",
+ "tabWidth",
+ "logicalOperatorNewline",
+ "commaPosition",
+ "fromClauseLayout",
+ "expressionWidth",
+ "linesBetweenQueries",
+ "preserveEmptyLines",
+ "denseOperators",
+ "newlineBeforeSemicolon",
+ "paramTypes",
+ ];
+ const legacy = Object.fromEntries(Object.entries(current).filter(([key]) => oldKeys.includes(key)));
+ const result = parseSettingsTransferFile(fileWith({ sqlFormatter: legacy }));
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.value.editorSettings.sqlFormatter).toMatchObject({ ...legacy, customRulesEnabled: false, selectListLayout: "vertical" });
+ });
+
+ it("preserves custom rules and a 76-column width in application backups", () => {
+ const sqlFormatter = { ...DEFAULT_EDITOR_SETTINGS.sqlFormatter, customRulesEnabled: true, selectListLayout: "wrap", updateListLayout: "vertical", expressionWidth: 76 };
+ const result = parseSettingsTransferFile(fileWith({ sqlFormatter }));
+ expect(result.ok).toBe(true);
+ if (result.ok) expect(result.value.editorSettings.sqlFormatter).toEqual(sqlFormatter);
+ });
+
it("rejects malformed sql variable syntax overrides", () => {
const result = parseSettingsTransferFile(fileWith({ sqlVariableSyntaxOverrides: { mysql: { positional: "yes" } } }));
expect(result.ok).toBe(false);
diff --git a/apps/desktop/src/lib/settings/settingsSearch.ts b/apps/desktop/src/lib/settings/settingsSearch.ts
index b397b7bc66..ac98b0308e 100644
--- a/apps/desktop/src/lib/settings/settingsSearch.ts
+++ b/apps/desktop/src/lib/settings/settingsSearch.ts
@@ -272,6 +272,31 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
{ id: "formatter-dense-operators", category: "formatter", titleKey: "settings.sqlFormatterDenseOperators", targetId: "formatter", route: { formatterMode: "form" } },
{ id: "formatter-newline-before-semicolon", category: "formatter", titleKey: "settings.sqlFormatterNewlineBeforeSemicolon", targetId: "formatter", route: { formatterMode: "form" } },
{ id: "formatter-param-types", category: "formatter", titleKey: "settings.sqlFormatterParamTypes", targetId: "formatter", route: { formatterMode: "form" } },
+ {
+ id: "formatter-custom-rules",
+ category: "formatter",
+ titleKey: "settings.sqlFormatterCustomRules",
+ targetId: "formatter",
+ route: { formatterMode: "form" },
+ keywordKeys: ["inherit", "singleLine", "fit", "vertical", "wrap", "firstItem", "indent", "before", "after", "none", "remove", "single", "preserve"].map((value) => `settings.sqlFormatterRule_${value}`),
+ },
+ { id: "formatter-list-layout", category: "formatter", titleKey: "settings.sqlFormatterListLayout", targetId: "formatter", route: { formatterMode: "form" } },
+ { id: "formatter-select-layout", category: "formatter", titleKey: "settings.sqlFormatterSelectListLayout", targetId: "formatter", route: { formatterMode: "form" } },
+ { id: "formatter-insert-layout", category: "formatter", titleKey: "settings.sqlFormatterInsertListLayout", targetId: "formatter", route: { formatterMode: "form" } },
+ { id: "formatter-update-layout", category: "formatter", titleKey: "settings.sqlFormatterUpdateListLayout", targetId: "formatter", route: { formatterMode: "form" } },
+ { id: "formatter-list-alignment", category: "formatter", titleKey: "settings.sqlFormatterListItemAlignment", targetId: "formatter", route: { formatterMode: "form" } },
+ { id: "formatter-empty-line-mode", category: "formatter", titleKey: "settings.sqlFormatterEmptyLineMode", targetId: "formatter", route: { formatterMode: "form" } },
+ { id: "formatter-align-select-aliases", category: "formatter", titleKey: "settings.sqlFormatterAlignSelectAliases", targetId: "formatter", route: { formatterMode: "form" } },
+ { id: "formatter-align-update-assignments", category: "formatter", titleKey: "settings.sqlFormatterAlignUpdateAssignments", targetId: "formatter", route: { formatterMode: "form" } },
+ { id: "formatter-select-comma-position", category: "formatter", titleKey: "settings.sqlFormatterSelectCommaPosition", targetId: "formatter", route: { formatterMode: "form" } },
+ { id: "formatter-insert-comma-position", category: "formatter", titleKey: "settings.sqlFormatterInsertCommaPosition", targetId: "formatter", route: { formatterMode: "form" } },
+ { id: "formatter-update-comma-position", category: "formatter", titleKey: "settings.sqlFormatterUpdateCommaPosition", targetId: "formatter", route: { formatterMode: "form" } },
+ { id: "formatter-where-logical-newline", category: "formatter", titleKey: "settings.sqlFormatterWhereLogicalOperatorNewline", targetId: "formatter", route: { formatterMode: "form" } },
+ { id: "formatter-on-logical-newline", category: "formatter", titleKey: "settings.sqlFormatterOnLogicalOperatorNewline", targetId: "formatter", route: { formatterMode: "form" } },
+ { id: "formatter-expression-logical-newline", category: "formatter", titleKey: "settings.sqlFormatterExpressionLogicalOperatorNewline", targetId: "formatter", route: { formatterMode: "form" } },
+ { id: "formatter-newline-before-join-on", category: "formatter", titleKey: "settings.sqlFormatterNewlineBeforeJoinOn", targetId: "formatter", route: { formatterMode: "form" } },
+ { id: "formatter-collapse-short-statements", category: "formatter", titleKey: "settings.sqlFormatterCollapseShortStatements", targetId: "formatter", route: { formatterMode: "form" } },
+ { id: "formatter-preview", category: "formatter", titleKey: "settings.sqlFormatterPreview", targetId: "formatter", route: { formatterMode: "form" }, keywordKeys: ["settings.sqlFormatterPreviewDialect", "settings.sqlFormatterPreviewSource"] },
{ id: "appearance-language", category: "appearance", titleKey: "settings.languageTitle", targetId: "appearance" },
{ id: "appearance-theme", category: "appearance", titleKey: "settings.theme", targetId: "appearance" },
{ id: "appearance-color-theme", category: "appearance", titleKey: "settings.colorTheme", targetId: "appearance", keywordKeys: APP_CUSTOM_UI_COLOR_DEFS.map((item) => item.labelKey) },
@@ -538,6 +563,7 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
"connection.httpTunnelProtocolDbx",
"connection.httpTunnelProtocolNavicat",
"connection.httpTunnelUrl",
+ "connection.httpTunnelProtocol",
"connection.httpTunnelToken",
"connection.httpTunnelConnectTimeout",
],
diff --git a/apps/desktop/src/lib/settings/settingsTransfer.ts b/apps/desktop/src/lib/settings/settingsTransfer.ts
index cdfcb79b5d..381eae863f 100644
--- a/apps/desktop/src/lib/settings/settingsTransfer.ts
+++ b/apps/desktop/src/lib/settings/settingsTransfer.ts
@@ -3,7 +3,7 @@ import { DEFAULT_CUSTOM_THEME_COLORS, DEFAULT_CUSTOM_THEME_DDL_COLORS, DEFAULT_E
import { EDITOR_MAX_FONT_SIZE, EDITOR_MIN_FONT_SIZE } from "@/lib/editor/editorZoom";
import { DATA_GRID_TYPE_COLOR_KEYS, DATA_GRID_TYPE_COLOR_SCHEME_AUTO_ID } from "@/lib/dataGrid/dataGridTypeColorScheme";
import { SHORTCUT_DEFINITIONS } from "@/lib/editor/shortcutRegistry";
-import { DEFAULT_SQL_FORMATTER_SETTINGS, isCompleteSqlFormatterSettings, type SqlFormatterOptionSettings } from "@/lib/sql/sqlFormatterConfig";
+import { DEFAULT_SQL_FORMATTER_RULE_SETTINGS, DEFAULT_SQL_FORMATTER_SETTINGS, isCompleteSqlFormatterSettings, type SqlFormatterOptionSettings, type SqlFormatterRuleSettings } from "@/lib/sql/sqlFormatterConfig";
import { SQL_VARIABLE_SYNTAX_KEYS } from "@/lib/sql/sqlVariableSyntax";
/**
@@ -477,7 +477,7 @@ const SQL_VARIABLE_SYNTAX_KEY_SET = new Set<string>(SQL_VARIABLE_SYNTAX_KEYS);
* because the version boundary is known; nothing is inferred about which
* style the user meant. Every future formatter option must be added here.
*/
-const SQL_FORMATTER_KEYS_ADDED_AFTER_TRANSFER_FORMAT = new Set<keyof SqlFormatterOptionSettings>(["commaPosition", "layoutStyle"]);
+const SQL_FORMATTER_KEYS_ADDED_AFTER_TRANSFER_FORMAT = new Set<keyof SqlFormatterOptionSettings>(["commaPosition", "layoutStyle", ...(Object.keys(DEFAULT_SQL_FORMATTER_RULE_SETTINGS) as (keyof SqlFormatterRuleSettings)[])]);
/**
* Complete-schema check that tolerates the absence of the post-transfer
diff --git a/apps/desktop/src/lib/sql/layout/primitives.ts b/apps/desktop/src/lib/sql/layout/primitives.ts
index 60fbb30f41..9dd1a44fe3 100644
--- a/apps/desktop/src/lib/sql/layout/primitives.ts
+++ b/apps/desktop/src/lib/sql/layout/primitives.ts
@@ -1,5 +1,7 @@
import type { AstNode, CaseExpressionNode, ClauseNode, KeywordNode, LimitClauseNode, ParenthesisNode, SetOperationNode } from "sql-formatter/dist/esm/parser/ast.js";
import type { SqlLayoutRenderers } from "./internals";
+import type { SqlFormatterSettings } from "../sqlFormatterConfig";
+import { clauseRuleContext, hasRuleLineBreak, ruleLogicalNewline } from "./rules";
/**
* The building blocks both layout strategies share: a column-tracking output
@@ -11,6 +13,8 @@ import type { SqlLayoutRenderers } from "./internals";
*/
export interface SqlLayoutOptions {
+ /** Explicit, opt-in rule mode; absent for every existing layout call. */
+ rules?: SqlFormatterSettings;
/** Hard wrap column; a group wider than this is broken across lines. */
lineWidth: number;
/** Maximum number of clause items kept on the keyword's line. */
@@ -69,6 +73,10 @@ export interface SqlLayoutContext {
* measurements override it — see {@link collapsedContext}.
*/
joinLogicalOperators?: boolean;
+ listKind?: "general" | "select" | "insert" | "update";
+ logicalContext?: "where" | "on" | "expression";
+ /** Same-level keyword width, never shared with a nested query block. */
+ keywordWidth?: number;
}
/**
@@ -93,7 +101,7 @@ export class Writer {
*/
private lineCommentOpen = false;
- constructor(private readonly options: Pick<SqlLayoutOptions, "useTabs" | "indentWidth">) {}
+ constructor(private readonly options: Pick<SqlLayoutOptions, "useTabs" | "indentWidth" | "rules">) {}
/** Column the cursor currently sits at, on the last line. */
get column(): number {
@@ -105,7 +113,8 @@ export class Writer {
if (text.length === 0) return;
this.closeLineComment();
this.lines[this.lines.length - 1] += text;
- this.columns[this.columns.length - 1] += text.length;
+ if (this.options.rules && /[\r\n]/.test(text)) this.columns[this.columns.length - 1] = text.length - Math.max(text.lastIndexOf("\n"), text.lastIndexOf("\r")) - 1;
+ else this.columns[this.columns.length - 1] += text.length;
}
/** Appends a single separating space, unless one is already there. */
@@ -115,6 +124,7 @@ export class Writer {
return;
}
const line = this.lines[this.lines.length - 1];
+ if (this.options.rules && /[([]$/.test(line)) return;
if (line.length > 0 && !line.endsWith(" ")) {
this.lines[this.lines.length - 1] = `${line} `;
this.columns[this.columns.length - 1] += 1;
@@ -142,10 +152,9 @@ export class Writer {
}
toString(): string {
- return this.lines
- .map((line) => line.trimEnd())
- .join("\n")
- .trim();
+ const text = this.lines.map((line) => line.trimEnd()).join("\n");
+ // Leading spaces can be the first keyword's tabular alignment, not input padding.
+ return this.options.rules ? text.replace(/^\n+|\n+$/g, "") : text.trim();
}
/**
@@ -228,6 +237,7 @@ export function isBodyNode(node: AstNode): boolean {
* even when the user asked for `logicalOperatorNewline: "before"`.
*/
export function collapsedContext(ctx: SqlLayoutContext): SqlLayoutContext {
+ if (ctx.options.rules) return ctx;
return ctx.joinLogicalOperators ? ctx : { ...ctx, joinLogicalOperators: true };
}
@@ -404,6 +414,7 @@ const DEFINITION_LIST_KEYWORD = new RegExp(`^(?:INSERT\\b[\\s\\S]*\\bINTO|${CREA
* `ON DUPLICATE KEY UPDATE b = f(c)`, which the parser also puts here — a call.
*/
export function clauseChildContext(ctx: SqlLayoutContext, clause: ClauseNode): SqlLayoutContext {
+ ctx = clauseRuleContext(ctx, clause);
if (clause.children.length < 2 || !DEFINITION_LIST_KEYWORD.test(clause.nameKw.text.trim())) return ctx;
const at = clause.children.findIndex(isParenthesis);
@@ -452,6 +463,7 @@ function hasMultipleStatementHeads(nodes: AstNode[]): boolean {
*/
export function renderInline(ctx: SqlLayoutContext, nodes: AstNode[], width: number): string | null {
if (nodes.length === 0 || width <= 0 || hasMultipleStatementHeads(nodes)) return null;
+ if (ctx.options.rules && hasRuleLineBreak(ctx, nodes)) return null;
const parenAt = nodes.findIndex(isParenthesis);
if (parenAt >= 0) {
@@ -482,7 +494,7 @@ export function renderInline(ctx: SqlLayoutContext, nodes: AstNode[], width: num
);
if (direct) return direct;
- const joinsOperators = ctx.joinLogicalOperators ?? ctx.options.logicalOperatorNewline === "none";
+ const joinsOperators = ctx.options.rules ? ruleLogicalNewline(ctx) === "none" : (ctx.joinLogicalOperators ?? ctx.options.logicalOperatorNewline === "none");
const joined = joinsOperators && nodes.some(isLogicalOperator) ? renderLogicalJoin(ctx, nodes, width) : null;
if (joined) return joined;
@@ -523,8 +535,10 @@ function renderParenGroup(ctx: SqlLayoutContext, nodes: AstNode[], at: number, w
const head = at === 0 ? "" : renderInline(groupCtx, nodes.slice(0, at), width);
if (head === null) return null;
- const separator = at === 0 || isCallParen(nodes, at, ctx) ? "" : " ";
- const inner = renderInline(groupCtx, node.children, width - head.length - separator.length - node.openParen.length - node.closeParen.length);
+ const call = isCallParen(nodes, at, ctx);
+ const separator = at === 0 || call ? "" : " ";
+ const innerCtx = ctx.options.rules && call ? { ...groupCtx, listKind: "general" as const } : groupCtx;
+ const inner = renderInline(innerCtx, node.children, width - head.length - separator.length - node.openParen.length - node.closeParen.length);
if (!inner) return null;
const group = `${head}${separator}${node.openParen}${inner}${node.closeParen}`;
diff --git a/apps/desktop/src/lib/sql/layout/printer.ts b/apps/desktop/src/lib/sql/layout/printer.ts
index c91cc79beb..e1ad2f2d09 100644
--- a/apps/desktop/src/lib/sql/layout/printer.ts
+++ b/apps/desktop/src/lib/sql/layout/printer.ts
@@ -1,5 +1,6 @@
import type { AstNode, ClauseNode, LimitClauseNode, ParenthesisNode, SetOperationNode, StatementNode } from "sql-formatter/dist/esm/parser/ast.js";
import { createTableLayout, isCreateTable } from "./ddl";
+import { hasRuleLineBreak, ruleCommaPosition, ruleListLayout, ruleLogicalNewline, supportsSqlRules } from "./rules";
import {
clauseChildContext,
collapsedContext,
@@ -54,6 +55,10 @@ export type { SqlLayoutContext, SqlLayoutOptions } from "./primitives";
* stay on one line when they are short enough.
*/
function printClause(writer: Writer, clause: ClauseNode, baseColumn: number, ctx: SqlLayoutContext): void {
+ if (ctx.options.rules) {
+ printRuleClause(writer, clause, baseColumn, ctx);
+ return;
+ }
const keyword = keywordText(clause.nameKw, ctx);
const items = splitByComma(clause.children);
const itemColumn = baseColumn + keyword.length + 1;
@@ -132,6 +137,220 @@ function printClause(writer: Writer, clause: ClauseNode, baseColumn: number, ctx
});
}
+function writeRuleKeyword(writer: Writer, keyword: string, ctx: SqlLayoutContext): void {
+ const style = ctx.options.rules!.indentStyle;
+ const padding = Math.max(0, (ctx.keywordWidth ?? keyword.length) - keyword.length);
+ if (style === "tabularRight") writer.write(" ".repeat(padding));
+ writer.write(keyword);
+ if (style === "tabularLeft") writer.write(" ".repeat(padding));
+}
+
+function printRuleClause(writer: Writer, clause: ClauseNode, baseColumn: number, ctx: SqlLayoutContext): void {
+ writeRuleKeyword(writer, keywordText(clause.nameKw, ctx), ctx);
+ if (clause.children.length === 0) return;
+ if (clause.nameKw.text.toUpperCase() === "FROM" && !ctx.options.fromClauseSourceOnSameLine) writer.newline(baseColumn + ctx.options.indentWidth);
+ else writer.write(" ");
+ const childCtx = clauseChildContext(ctx, clause);
+ printRuleList(writer, splitByComma(clause.children), baseColumn, childCtx);
+}
+
+function alignedAssignmentItems(items: AstNode[][], ctx: SqlLayoutContext, width: number): Array<AlignedProjectionItem | null> | null {
+ const parsed = items.map((item) => {
+ const at = item.findIndex((node) => node.type === "operator" && node.text === "=");
+ if (at <= 0 || at === item.length - 1) return null;
+ const expression = renderInline(ctx, item.slice(0, at), width);
+ const alias = renderInline(ctx, item.slice(at + 1), width);
+ return expression && alias ? { expression, alias, asKeyword: "=", aliasColumn: 0 } : null;
+ });
+ if (parsed.some((item) => !item)) return null;
+ const aliasColumn = Math.max(...parsed.map((item) => item!.expression.length)) + 1;
+ if (parsed.some((item) => aliasColumn + 2 + item!.alias.length > width)) return null;
+ return parsed.map((item) => ({ ...item!, aliasColumn }));
+}
+
+/** One list writer serves clauses, INSERT tuples, IN lists and function arguments. */
+function printRuleList(writer: Writer, items: AstNode[][], baseColumn: number, ctx: SqlLayoutContext): void {
+ const mode = ruleListLayout(ctx);
+ const comma = ruleCommaPosition(ctx);
+ const firstColumn = writer.column;
+ const continuation = ctx.options.rules!.listItemAlignment === "indent" ? baseColumn + ctx.options.indentWidth : firstColumn;
+ const nodes = items.flatMap((item, index) => (index === 0 ? item : [{ type: "comma" } as AstNode, ...item]));
+ // Single-line lists keep their own separators inline, but each item still
+ // visits its nested lists with their actual remaining width.
+ const flat = mode === "singleLine" || (mode === "vertical" && items.length > 1) ? null : renderInline(ctx, nodes, ctx.options.lineWidth - writer.column);
+ if (flat) {
+ writer.write(flat);
+ return;
+ }
+ const available = ctx.options.lineWidth - Math.max(firstColumn, continuation);
+ const aligned =
+ mode !== "singleLine" && items.length > 1 ? (ctx.listKind === "select" && ctx.options.rules!.alignSelectAliases ? alignedProjectionItems(items, ctx, available) : ctx.listKind === "update" && ctx.options.rules!.alignUpdateAssignments ? alignedAssignmentItems(items, ctx, available) : null) : null;
+
+ items.forEach((item, index) => {
+ let itemNodes = item;
+ if (index > 0) {
+ const commentCount = comma === "after" ? leadingTrailingComments(item) : 0;
+ if (commentCount > 0) {
+ writer.space();
+ printRuleElement(writer, item.slice(0, commentCount), baseColumn, ctx);
+ itemNodes = item.slice(commentCount);
+ }
+ const text = renderInline(ctx, itemNodes, Number.MAX_SAFE_INTEGER);
+ const separatorWidth = comma === "before" ? 2 : 1;
+ const trailingCommaWidth = comma === "after" && index < items.length - 1 ? 1 : 0;
+ const sameLine = mode === "singleLine" || (mode === "wrap" && !!text && writer.column + separatorWidth + text.length + trailingCommaWidth <= ctx.options.lineWidth);
+ if (sameLine && commentCount === 0) {
+ if (comma === "before") writer.write(", ");
+ else writer.space();
+ } else {
+ writer.newline(comma === "before" ? Math.max(baseColumn, continuation - 2) : continuation);
+ if (comma === "before") writer.write(", ");
+ }
+ }
+ const alignment = aligned?.[index];
+ if (alignment && itemNodes === item) {
+ writer.write(alignment.expression);
+ writer.write(" ".repeat(alignment.aliasColumn - alignment.expression.length));
+ writer.write(`${alignment.asKeyword} ${alignment.alias}`);
+ } else {
+ printRuleElement(writer, itemNodes, baseColumn, ctx);
+ }
+ if (comma === "after" && index < items.length - 1) writer.write(",");
+ });
+}
+
+function printRuleComments(writer: Writer, nodes: AstNode[] | undefined, column: number, ctx: SqlLayoutContext): void {
+ if (nodes?.length) printRuleElement(writer, nodes, column, ctx);
+}
+
+function printRuleJoins(writer: Writer, nodes: AstNode[], baseColumn: number, ctx: SqlLayoutContext): boolean {
+ const first = nodes.findIndex(isJoinKeyword);
+ if (first < 0) return false;
+ if (first > 0) printRuleElement(writer, nodes.slice(0, first), baseColumn, ctx);
+ let index = first;
+ while (index < nodes.length) {
+ const end = joinElementEnd(nodes, index + 1);
+ const segment = nodes.slice(index + 1, end);
+ const on = segment.findIndex((node) => node.type === "keyword" && node.text.toUpperCase() === "ON");
+ const joinColumn = baseColumn + ctx.options.joinIndentWidth;
+ writer.newline(joinColumn);
+ writer.write(keywordText(nodes[index], ctx));
+ writer.space();
+ printRuleElement(writer, on < 0 ? segment : segment.slice(0, on), joinColumn, { ...ctx, listKind: "general", logicalContext: "expression" });
+ if (on >= 0) {
+ if (ctx.options.rules!.newlineBeforeJoinOn) writer.newline(joinColumn + ctx.options.indentWidth);
+ else writer.space();
+ writer.write(keywordText(segment[on], ctx));
+ writer.space();
+ printRuleElement(writer, segment.slice(on + 1), joinColumn, { ...ctx, listKind: "general", logicalContext: "on" });
+ }
+ index = end;
+ }
+ return true;
+}
+
+function printRuleElement(writer: Writer, nodes: AstNode[], baseColumn: number, ctx: SqlLayoutContext): void {
+ if (nodes.length === 0) return;
+ const whole = renderInline(ctx, nodes, ctx.options.lineWidth - writer.column);
+ if (whole) {
+ writer.write(whole);
+ return;
+ }
+ if (printRuleJoins(writer, nodes, baseColumn, ctx)) return;
+ const operands = ruleLogicalNewline(ctx) === "none" ? null : splitLogicalOperands(nodes);
+ if (operands) {
+ printCondition(writer, operands, baseColumn, ctx);
+ return;
+ }
+ for (let index = 0; index < nodes.length;) {
+ const node = nodes[index];
+ if (node.type === "line_comment" || node.type === "block_comment" || node.type === "disable_comment") {
+ if (/[\r\n]/.test(node.precedingWhitespace)) writer.newline(baseColumn);
+ else writer.space();
+ writer.write(node.text);
+ if (node.type !== "block_comment") writer.markLineComment();
+ index += 1;
+ } else if (node.type === "parenthesis") {
+ if (!isCallParen(nodes, index, ctx)) writer.space();
+ writeParenthesis(writer, nodes, index, isCallParen(nodes, index, ctx) ? { ...ctx, listKind: "general" } : ctx);
+ index += 1;
+ } else if (node.type === "function_call" || node.type === "parameterized_data_type" || node.type === "array_subscript") {
+ writer.space();
+ printRuleComments(writer, node.leadingComments, writer.column, ctx);
+ const name = node.type === "function_call" ? node.nameKw : node.type === "parameterized_data_type" ? node.dataType : node.array;
+ if (node.type === "function_call") {
+ const casing = ctx.options.rules!.functionCase;
+ writer.write(casing === "preserve" ? node.nameKw.raw : casing === "upper" ? node.nameKw.text.toUpperCase() : node.nameKw.text.toLowerCase());
+ } else writer.write(ctx.renderers.block([name]).trim());
+ writeParenthesis(writer, [node.parenthesis], 0, { ...ctx, listKind: "general" });
+ printRuleComments(writer, node.trailingComments, writer.column, ctx);
+ index += 1;
+ } else if (node.type === "property_access") {
+ printRuleComments(writer, node.leadingComments, writer.column, ctx);
+ printRuleElement(writer, [node.object], baseColumn, ctx);
+ writer.write(node.operator);
+ if (node.property.type === "array_subscript") {
+ writer.write(ctx.renderers.block([node.property.array]).trim());
+ writeParenthesis(writer, [node.property.parenthesis], 0, { ...ctx, listKind: "general" });
+ } else writer.write(ctx.renderers.block([node.property]).trim());
+ printRuleComments(writer, node.trailingComments, writer.column, ctx);
+ index += 1;
+ } else if (node.type === "between_predicate") {
+ writer.space();
+ printRuleComments(writer, node.leadingComments, writer.column, ctx);
+ writer.write(keywordText(node.betweenKw, ctx));
+ writer.space();
+ printRuleElement(writer, node.expr1, baseColumn, ctx);
+ writer.space();
+ writer.write(keywordText(node.andKw, ctx));
+ writer.space();
+ printRuleElement(writer, node.expr2, baseColumn, ctx);
+ printRuleComments(writer, node.trailingComments, writer.column, ctx);
+ index += 1;
+ } else if (node.type === "case_expression") {
+ writer.space();
+ printRuleComments(writer, node.leadingComments, writer.column, ctx);
+ const caseCtx: SqlLayoutContext = { ...ctx, listKind: "general", logicalContext: "expression" };
+ const inlineCase = ruleListLayout(ctx) === "singleLine" && !hasRuleLineBreak(ctx, [node]);
+ writer.write(keywordText(node.caseKw, ctx));
+ if (node.expr.length) {
+ writer.space();
+ printRuleElement(writer, node.expr, baseColumn, caseCtx);
+ }
+ for (const branch of node.clauses) {
+ if (inlineCase) writer.space();
+ else writer.newline(baseColumn + ctx.options.indentWidth);
+ printRuleComments(writer, branch.leadingComments, writer.column, ctx);
+ if (branch.type === "case_when") {
+ writer.write(keywordText(branch.whenKw, ctx));
+ writer.space();
+ printRuleElement(writer, branch.condition, baseColumn + ctx.options.indentWidth, caseCtx);
+ writer.space();
+ writer.write(keywordText(branch.thenKw, ctx));
+ } else writer.write(keywordText(branch.elseKw, ctx));
+ writer.space();
+ printRuleElement(writer, branch.result, baseColumn + ctx.options.indentWidth, caseCtx);
+ printRuleComments(writer, branch.trailingComments, writer.column, ctx);
+ }
+ if (inlineCase) writer.space();
+ else writer.newline(baseColumn);
+ writer.write(keywordText(node.endKw, ctx));
+ printRuleComments(writer, node.trailingComments, writer.column, ctx);
+ index += 1;
+ } else {
+ let end = index + 1;
+ while (end < nodes.length && !["parenthesis", "function_call", "parameterized_data_type", "array_subscript", "property_access", "between_predicate", "case_expression", "line_comment", "block_comment", "disable_comment"].includes(nodes[end].type)) end += 1;
+ const run = nodes.slice(index, end);
+ const first = run[0];
+ if (!(first.type === "operator" && ctx.renderers.denseOperator(first.text))) writer.space();
+ const inline = renderInline(ctx, run, Number.MAX_SAFE_INTEGER);
+ if (inline) writer.write(inline);
+ else emitText(writer, ctx.renderers.block(run).trim(), writer.column, endsWithLineComment(run));
+ index = end;
+ }
+ }
+}
+
/** Count leading comments that were written on the previous source line. */
function leadingTrailingComments(item: AstNode[]): number {
let count = 0;
@@ -174,6 +393,13 @@ function alignedProjectionItems(items: AstNode[][], ctx: SqlLayoutContext, lineW
function printLimitClause(writer: Writer, clause: LimitClauseNode, ctx: SqlLayoutContext): void {
const keyword = keywordText(clause.limitKw, ctx);
const children = limitChildren(clause);
+ if (ctx.options.rules) {
+ const baseColumn = writer.column;
+ writeRuleKeyword(writer, keyword, ctx);
+ writer.space();
+ printRuleList(writer, splitByComma(children), baseColumn, { ...ctx, listKind: "general", logicalContext: "expression" });
+ return;
+ }
const flat = renderInline(ctx, children, ctx.options.lineWidth - writer.column - keyword.length - 1);
if (flat) {
writer.write(`${keyword} ${flat}`);
@@ -222,6 +448,20 @@ function measureParen(writer: Writer, nodes: AstNode[], index: number, ctx: SqlL
*/
function writeParenthesis(writer: Writer, nodes: AstNode[], index: number, ctx: SqlLayoutContext): void {
const node = nodes[index] as ParenthesisNode;
+ if (ctx.options.rules) {
+ printRuleComments(writer, node.leadingComments, writer.column, ctx);
+ const inner = measureParen(writer, nodes, index, ctx);
+ if (inner) writer.write(`${node.openParen}${inner}${node.closeParen}`);
+ else {
+ writer.write(node.openParen);
+ const column = writer.column;
+ if (node.children.some(isBodyNode)) printBlock(writer, node.children, column, ctx);
+ else printRuleList(writer, splitByComma(node.children), column - node.openParen.length, ctx);
+ writer.write(node.closeParen);
+ }
+ printRuleComments(writer, node.trailingComments, writer.column, ctx);
+ return;
+ }
const inner = measureParen(writer, nodes, index, ctx);
if (inner) {
writer.write(`${node.openParen}${inner}${node.closeParen}`);
@@ -235,15 +475,14 @@ function writeParenthesis(writer: Writer, nodes: AstNode[], index: number, ctx:
/**
* Emits one set operation (`UNION ALL`, `INTERSECT`, ...).
*
- * The parser only promotes a *bare* `SELECT` after the operator to a sibling
- * clause of its own; every other branch — a parenthesized subquery, a `VALUES`
- * list — stays in this node's `children`. Printing the keyword alone would
- * therefore delete every branch after the first one (#10472), so the operand is
- * written on the next line at the operator's column, which is where the
- * sibling-clause form (`SELECT ... UNION ALL SELECT ...`) puts it as well.
+ * Bare `SELECT` and `VALUES` operands become sibling clauses. Operands retained
+ * in this node's `children`, such as a parenthesized subquery or a `TABLE`
+ * reference, must also be printed to avoid dropping a branch (#10472). They go
+ * on the next line at the operator's column, just like the sibling-clause form.
*/
function printSetOperation(writer: Writer, node: SetOperationNode, baseColumn: number, ctx: SqlLayoutContext): void {
- writer.write(keywordText(node.nameKw, ctx));
+ if (ctx.options.rules) writeRuleKeyword(writer, keywordText(node.nameKw, ctx), ctx);
+ else writer.write(keywordText(node.nameKw, ctx));
if (node.children.length === 0) return;
writer.newline(baseColumn);
printSetOperationOperand(writer, node.children, ctx);
@@ -255,9 +494,7 @@ function printSetOperationOperand(writer: Writer, nodes: AstNode[], ctx: SqlLayo
writeParenthesis(writer, nodes, 0, ctx);
return;
}
- // Anything the grammar did not turn into a clause of its own (a `VALUES`
- // list, a dialect-specific operand): let sql-formatter lay it out, re-based
- // on this column.
+ // Keep other dialect-specific operands, such as TABLE references, at this column.
emitText(writer, ctx.renderers.block(nodes).trim(), writer.column, endsWithLineComment(nodes));
}
@@ -279,7 +516,7 @@ function printCondition(writer: Writer, operands: AstNode[][], baseColumn: numbe
}
const operator = keywordText(head, ctx);
- if (ctx.options.logicalOperatorNewline === "before") {
+ if (ruleLogicalNewline(ctx) === "before") {
writer.newline(column);
writer.write(operator);
writer.space();
@@ -297,6 +534,10 @@ function printCondition(writer: Writer, operands: AstNode[][], baseColumn: numbe
* current line.
*/
function printElement(writer: Writer, nodes: AstNode[], baseColumn: number, ctx: SqlLayoutContext): void {
+ if (ctx.options.rules) {
+ printRuleElement(writer, nodes, baseColumn, ctx);
+ return;
+ }
const whole = renderInline(ctx, nodes, ctx.options.lineWidth - writer.column);
if (whole) {
writer.write(whole);
@@ -360,6 +601,7 @@ function printElement(writer: Writer, nodes: AstNode[], baseColumn: number, ctx:
* the very expansion the caller asked for.
*/
function printBlock(writer: Writer, nodes: AstNode[], baseColumn: number, ctx: SqlLayoutContext): void {
+ if (ctx.options.rules) ctx = ruleBlockContext(nodes, ctx);
if (!nodes.some(isBodyNode)) {
// A plain expression group (not a subquery) that did not fit: let
// sql-formatter break it, then re-base the block on this column.
@@ -375,6 +617,11 @@ function printBlock(writer: Writer, nodes: AstNode[], baseColumn: number, ctx: S
}
}
+function ruleBlockContext(nodes: AstNode[], ctx: SqlLayoutContext): SqlLayoutContext {
+ const lengths = nodes.flatMap((node) => (node.type === "clause" || node.type === "set_operation" ? [keywordText(node.nameKw, ctx).length] : node.type === "limit_clause" ? [keywordText(node.limitKw, ctx).length] : []));
+ return { ...ctx, keywordWidth: Math.max(0, ...lengths) };
+}
+
/** Emits one clause / set operation / limit clause of a statement body. */
function writeBodyNode(writer: Writer, node: AstNode, baseColumn: number, ctx: SqlLayoutContext): void {
if (node.type === "clause") printClause(writer, node, baseColumn, ctx);
@@ -389,14 +636,25 @@ function writeBodyNode(writer: Writer, node: AstNode, baseColumn: number, ctx: S
/** Emits a whole statement, one clause per line unless the statement collapses. */
function printStatement(statement: StatementNode, ctx: SqlLayoutContext): string | null {
+ if (ctx.options.rules) {
+ if (!supportsSqlRules(statement.children)) return null;
+ ctx = ruleBlockContext(statement.children, ctx);
+ if (statement.children.every((node) => ["line_comment", "block_comment", "disable_comment"].includes(node.type))) {
+ const writer = new Writer(ctx.options);
+ printRuleElement(writer, statement.children, 0, ctx);
+ if (statement.hasSemicolon) writer.write(";");
+ return writer.toString();
+ }
+ }
const hasMultiItemProjection = statement.children.some((node) => node.type === "clause" && isProjectionClauseName(node.nameKw.text) && splitByComma(node.children).length > 1);
- const collapsed = hasMultiItemProjection ? null : renderInline(collapsedContext(ctx), statement.children, ctx.options.lineWidth);
+ const mayCollapse = ctx.options.rules ? ctx.options.rules.collapseShortStatements : !hasMultiItemProjection;
+ const collapsed = mayCollapse ? renderInline(collapsedContext(ctx), statement.children, ctx.options.lineWidth) : null;
if (collapsed) {
if (!statement.hasSemicolon) return collapsed;
return ctx.options.newlineBeforeSemicolon ? `${collapsed}\n;` : `${collapsed};`;
}
- if (isCreateTable(statement)) return createTableLayout(statement, ctx);
+ if (!ctx.options.rules && isCreateTable(statement)) return createTableLayout(statement, ctx);
// A statement without clauses is a bare expression — a fragment the user
// selected in the editor — and has no clause layout to apply. Declining hands
diff --git a/apps/desktop/src/lib/sql/layout/rules.ts b/apps/desktop/src/lib/sql/layout/rules.ts
new file mode 100644
index 0000000000..5aa33d925e
--- /dev/null
+++ b/apps/desktop/src/lib/sql/layout/rules.ts
@@ -0,0 +1,90 @@
+import type { AstNode, ClauseNode } from "sql-formatter/dist/esm/parser/ast.js";
+import type { SqlLayoutContext } from "./primitives";
+import type { SqlFormatterCommaPosition, SqlFormatterListLayout, SqlFormatterLogicalOperatorNewline } from "../sqlFormatterConfig";
+
+export function clauseRuleContext(ctx: SqlLayoutContext, clause: ClauseNode): SqlLayoutContext {
+ if (!ctx.options.rules) return ctx;
+ const keyword = clause.nameKw.text.toUpperCase();
+ const listKind = /^SELECT(?:\s|$)/.test(keyword) ? "select" : /^(?:INSERT\b|VALUES$)/.test(keyword) ? "insert" : keyword === "SET" || keyword === "UPDATE SET" ? "update" : "general";
+ const definition = /^(?:INSERT\b.*\bINTO|CREATE\b.*\bTABLE)$/.test(keyword) ? clause.children.find((node) => node.type === "parenthesis") : undefined;
+ return { ...ctx, listKind, logicalContext: keyword === "WHERE" ? "where" : "expression", ...(definition ? { nonCallParens: new Set([...(ctx.nonCallParens ?? []), definition]) } : {}) };
+}
+
+export function ruleListLayout(ctx: SqlLayoutContext): SqlFormatterListLayout {
+ const rules = ctx.options.rules!;
+ const override = ctx.listKind === "select" ? rules.selectListLayout : ctx.listKind === "insert" ? rules.insertListLayout : ctx.listKind === "update" ? rules.updateListLayout : "inherit";
+ return override === "inherit" ? rules.listLayout : override;
+}
+
+export function ruleCommaPosition(ctx: SqlLayoutContext): SqlFormatterCommaPosition {
+ const rules = ctx.options.rules!;
+ const override = ctx.listKind === "select" ? rules.selectCommaPosition : ctx.listKind === "insert" ? rules.insertCommaPosition : ctx.listKind === "update" ? rules.updateCommaPosition : "inherit";
+ return override === "inherit" ? rules.commaPosition : override;
+}
+
+export function ruleLogicalNewline(ctx: SqlLayoutContext): SqlFormatterLogicalOperatorNewline {
+ const rules = ctx.options.rules;
+ if (!rules) return ctx.options.logicalOperatorNewline;
+ const override = ctx.logicalContext === "where" ? rules.whereLogicalOperatorNewline : ctx.logicalContext === "on" ? rules.onLogicalOperatorNewline : rules.expressionLogicalOperatorNewline;
+ return override === "inherit" ? rules.logicalOperatorNewline : override;
+}
+
+function logicalOperator(node: AstNode): boolean {
+ return node.type === "keyword" && ["AND", "OR", "XOR"].includes(node.tokenType);
+}
+
+/** Before measuring any container, honour rules its nested SQL would otherwise bypass. */
+export function hasRuleLineBreak(ctx: SqlLayoutContext, nodes: AstNode[]): boolean {
+ if (!ctx.options.rules) return false;
+ if (ruleListLayout(ctx) === "vertical" && nodes.some((node) => node.type === "comma")) return true;
+ if (ruleLogicalNewline(ctx) !== "none" && nodes.some(logicalOperator)) return true;
+ return nodes.some((node, index) => {
+ if (node.leadingComments?.length || node.trailingComments?.length) return true;
+ switch (node.type) {
+ case "line_comment":
+ case "block_comment":
+ case "disable_comment":
+ return true;
+ case "clause":
+ return hasRuleLineBreak(clauseRuleContext(ctx, node), node.children);
+ case "set_operation":
+ return hasRuleLineBreak(ctx, node.children);
+ case "parenthesis": {
+ const previous = nodes[index - 1];
+ const call = !ctx.nonCallParens?.has(node) && (previous?.type === "identifier" || previous?.type === "property_access");
+ return hasRuleLineBreak(call ? { ...ctx, listKind: "general" } : ctx, node.children);
+ }
+ case "function_call":
+ case "parameterized_data_type":
+ case "array_subscript":
+ return hasRuleLineBreak({ ...ctx, listKind: "general" }, node.parenthesis.children);
+ case "property_access":
+ return hasRuleLineBreak(ctx, [node.object, node.property]);
+ case "between_predicate":
+ return hasRuleLineBreak(ctx, [...node.expr1, ...node.expr2]);
+ case "case_expression":
+ return hasRuleLineBreak({ ...ctx, listKind: "general", logicalContext: "expression" }, [...node.expr, ...node.clauses]);
+ case "case_when":
+ return hasRuleLineBreak(ctx, [...node.condition, ...node.result]);
+ case "case_else":
+ return hasRuleLineBreak(ctx, node.result);
+ case "limit_clause":
+ return hasRuleLineBreak(ctx, [...(node.offset ?? []), ...node.count]);
+ case "keyword":
+ return ctx.options.rules!.newlineBeforeJoinOn && node.text.toUpperCase() === "ON";
+ default:
+ return false;
+ }
+ });
+}
+
+/** A parsed procedure is not a supported SQL rule model merely because it contains SELECT. */
+export function supportsSqlRules(nodes: AstNode[]): boolean {
+ return nodes.every((node) => {
+ if (node.type === "clause" && /^(?:BEGIN|DECLARE|EXCEPTION|CREATE\s+(?:OR\s+REPLACE\s+)?(?:FUNCTION|PROCEDURE|PACKAGE|TRIGGER))\b/i.test(node.nameKw.text)) return false;
+ if (node.type === "operator" && node.text === ":=") return false;
+ if (node.type === "keyword" && ["END", "LOOP", "ELSIF"].includes(node.tokenType)) return false;
+ if (node.type === "clause" || node.type === "set_operation" || node.type === "parenthesis") return supportsSqlRules(node.children);
+ return true;
+ });
+}
diff --git a/apps/desktop/src/lib/sql/sqlFormatter.ts b/apps/desktop/src/lib/sql/sqlFormatter.ts
index b8d05d6990..56e1507122 100644
--- a/apps/desktop/src/lib/sql/sqlFormatter.ts
+++ b/apps/desktop/src/lib/sql/sqlFormatter.ts
@@ -2,6 +2,7 @@ import { DEFAULT_SQL_FORMATTER_SETTINGS, normalizeSqlFormatterSettings, sqlForma
import { formatSqlLayout, type SqlLayoutOptions } from "@/lib/sql/layout";
import { looksLikeXml } from "@/lib/sql/autoFormat";
import { compressCypherText, formatCypherText } from "@/lib/sql/cypherFormatter";
+import { tokenizeSqlSemantic } from "@/lib/sql/semantic/tokens";
export type SqlFormatDialect = "mysql" | "postgres" | "sqlite" | "sqlserver" | "oracle" | "clickhouse" | "dameng" | "duckdb" | "cypher" | "generic";
@@ -63,6 +64,9 @@ function resolveClickHouseIdentifierSafeDialect(sqlFormatter: SqlFormatterModule
// functions (e.g. SUBSTR, INSTR, LENGTH) and omits Oracle's byte/multibyte/code-point
// variants. Register them as reserved function names so functionCase normalizes them.
const ORACLE_EXTENDED_FUNCTION_NAMES = ["SUBSTRB", "SUBSTR2", "SUBSTR4", "SUBSTRC", "INSTRB", "INSTR2", "INSTR4", "INSTRC", "LENGTHB", "LENGTH2", "LENGTH4", "LENGTHC"];
+// The bundled q-quote pattern uses `.`, so it stops matching at a line break.
+// Keep each complete alternative literal as one token in both layout engines.
+const ORACLE_Q_QUOTE_PATTERN = String.raw`[Nn]?[Qq]'(?:\[[\s\S]*?\]|\{[\s\S]*?\}|\([\s\S]*?\)|<[\s\S]*?>|(?<dbxOracleQuote>[^\s<\[({])[\s\S]*?\k<dbxOracleQuote>)'`;
let oracleExtendedDialect: SqlFormatterModule["plsql"] | null = null;
function resolveOracleExtendedDialect(sqlFormatter: SqlFormatterModule): SqlFormatterModule["plsql"] {
@@ -76,6 +80,7 @@ function resolveOracleExtendedDialect(sqlFormatter: SqlFormatterModule): SqlForm
tokenizerOptions: {
...sqlFormatter.plsql.tokenizerOptions,
reservedFunctionNames: [...sqlFormatter.plsql.tokenizerOptions.reservedFunctionNames, ...extraFunctions],
+ stringTypes: sqlFormatter.plsql.tokenizerOptions.stringTypes.map((type) => (typeof type !== "string" && "quote" in type && type.quote === "q''" ? { regex: ORACLE_Q_QUOTE_PATTERN } : type)),
},
};
return oracleExtendedDialect;
@@ -230,9 +235,9 @@ interface EmptyLineProtection {
* valid at every SQL code boundary and are restored only after all DBX layout
* post-processing is complete.
*/
-function protectEmptyLines(sql: string): EmptyLineProtection {
+function protectEmptyLines(sql: string, originalSql = sql): EmptyLineProtection {
let namespace = 0;
- while (sql.includes(`__DBX_PRESERVE_EMPTY_LINE_${namespace}_`)) namespace += 1;
+ while (originalSql.includes(`__DBX_PRESERVE_EMPTY_LINE_${namespace}_`)) namespace += 1;
const markers: string[] = [];
const lineBreakPattern = /\r\n|\r|\n/g;
@@ -272,7 +277,9 @@ function restoreProtectedEmptyLines(sql: string, markers: readonly string[]): st
if (markers.length === 0) return sql;
const markerSet = new Set(markers);
- const lines = sql.split(/\r\n|\r|\n/);
+ // Keep each terminator: normalizing the whole result would also rewrite
+ // line breaks inside string literals and block comments.
+ const lines = Array.from(sql.matchAll(/[^\r\n]*(?:\r\n|\r|\n|$)/g), ([line]) => line);
for (let index = 0; index < lines.length;) {
if (!markerSet.has(lines[index].trim())) {
index += 1;
@@ -298,12 +305,12 @@ function restoreProtectedEmptyLines(sql: string, markers: readonly string[]): st
}
for (let markerIndex = index; markerIndex < runEnd; markerIndex += 1) {
- lines[markerIndex] = "";
+ lines[markerIndex] = lines[markerIndex].replace(/[^\r\n]+/, "");
}
index = runEnd;
}
- return lines.join("\n");
+ return lines.join("");
}
const DUCKDB_ALIAS_IDENTIFIER_START_RE = /[\p{L}_]/u;
@@ -426,7 +433,27 @@ function restoreDuckDbPrefixAliasSeparators(sql: string, marker: string | null):
return marker ? sql.split(marker).join(":") : sql;
}
-export async function formatSqlText(sql: string, dialect: SqlFormatDialect = "generic", settings: Partial<SqlFormatterSettings> = DEFAULT_SQL_FORMATTER_SETTINGS): Promise<string> {
+function protectBlockCommentLineEndings(sql: string, dialect: SqlFormatDialect): { sql: string; markers: Map<string, string> } {
+ const markers = new Map<string, string>();
+ if (!sql.includes("\r")) return { sql, markers };
+
+ let namespace = 0;
+ while (sql.includes(`__DBX_PRESERVE_BLOCK_COMMENT_${namespace}_`)) namespace += 1;
+ const { masked, spans } = maskStringAndCommentSpans(sql, dialect);
+ const protectedSpans = spans.map((span) => {
+ if (!span.startsWith("/*") || !span.includes("\r")) return span;
+ // Keep hints and MySQL executable comments in their original comment category.
+ const kind = span[2] === "+" || span[2] === "!" ? span[2] : "";
+ const marker = `/*${kind}__DBX_PRESERVE_BLOCK_COMMENT_${namespace}_${markers.size}__*/`;
+ markers.set(marker, span);
+ return marker;
+ });
+ return { sql: restoreSpans(masked, protectedSpans), markers };
+}
+
+export type SqlFormatterDiagnostic = "custom-rules-fallback";
+
+export async function formatSqlText(sql: string, dialect: SqlFormatDialect = "generic", settings: Partial<SqlFormatterSettings> = DEFAULT_SQL_FORMATTER_SETTINGS, onDiagnostic?: (diagnostic: SqlFormatterDiagnostic) => void): Promise<string> {
if (!sql.trim()) return sql;
if (sql.length > MAX_SQL_FORMAT_CHARS) {
throw new Error("SQL is too large to format safely.");
@@ -441,10 +468,16 @@ export async function formatSqlText(sql: string, dialect: SqlFormatDialect = "ge
const sqlFormatter = await import("sql-formatter");
const { format, formatDialect } = sqlFormatter;
- const options = sqlFormatterOptions(normalizedSettings);
const language = formatterLanguage(dialect);
- const emptyLineProtection = normalizedSettings.preserveEmptyLines ? protectEmptyLines(sql) : null;
- const sqlWithProtectedEmptyLines = emptyLineProtection?.sql ?? sql;
+ const emptyLineMode = normalizedSettings.customRulesEnabled && normalizedSettings.emptyLineMode !== "inherit" ? normalizedSettings.emptyLineMode : normalizedSettings.preserveEmptyLines ? "preserve" : "remove";
+ const linesBetweenQueries =
+ normalizedSettings.customRulesEnabled && normalizedSettings.emptyLineMode === "remove" ? 0 : normalizedSettings.customRulesEnabled && normalizedSettings.emptyLineMode === "single" && normalizedSettings.linesBetweenQueries === 2 ? 1 : normalizedSettings.linesBetweenQueries;
+ const options = sqlFormatterOptions({ ...normalizedSettings, linesBetweenQueries });
+ // The external formatter reindents multiline block comments and drops CRs.
+ // Preserve affected comments until all formatting and layout passes finish.
+ const commentProtection = protectBlockCommentLineEndings(sql, dialect);
+ const emptyLineProtection = emptyLineMode === "remove" ? null : protectCodeEmptyLines(commentProtection.sql, dialect, emptyLineMode === "single");
+ const sqlWithProtectedEmptyLines = emptyLineProtection?.sql ?? commentProtection.sql;
const protectedInput = dialect === "duckdb" ? protectDuckDbPrefixAliasSeparators(sqlWithProtectedEmptyLines) : { sql: sqlWithProtectedEmptyLines, marker: null };
const formatterOptions =
language === "postgresql"
@@ -492,10 +525,16 @@ export async function formatSqlText(sql: string, dialect: SqlFormatDialect = "ge
}
};
+ let appliedCustomRules = false;
const finalizeFormattedSql = (formatted: string): string => {
+ if (normalizedSettings.customRulesEnabled && !appliedCustomRules) {
+ onDiagnostic?.("custom-rules-fallback");
+ return formatted;
+ }
const restoredDuckDbAliases = restoreDuckDbPrefixAliasSeparators(formatted, protectedInput.marker);
- const laidOut = applySqlFormatterLayout(restoredDuckDbAliases, normalizedSettings, dialect);
- return emptyLineProtection ? restoreProtectedEmptyLines(laidOut, emptyLineProtection.markers) : laidOut;
+ const laidOut = appliedCustomRules ? normalizeLikeOperatorCase(restoredDuckDbAliases, normalizedSettings, dialect) : applySqlFormatterLayout(restoredDuckDbAliases, normalizedSettings, dialect);
+ const restored = emptyLineProtection ? restoreProtectedEmptyLines(laidOut, emptyLineProtection.markers) : laidOut;
+ return commentProtection.markers.size ? restored.replace(/\/\*[+!]?__DBX_PRESERVE_BLOCK_COMMENT_\d+_\d+__\*\//g, (marker) => commentProtection.markers.get(marker) ?? marker) : restored;
};
// DBX's own layout printer produces the default `dbx` style. It needs the AST
@@ -510,7 +549,7 @@ export async function formatSqlText(sql: string, dialect: SqlFormatDialect = "ge
lineWidth: normalizedSettings.expressionWidth,
indentWidth: normalizedSettings.tabWidth,
useTabs: normalizedSettings.useTabs,
- linesBetweenQueries: normalizedSettings.linesBetweenQueries,
+ linesBetweenQueries,
fromClauseSourceOnSameLine: normalizedSettings.fromClauseLayout === "sameLine",
keywordCase: normalizedSettings.keywordCase,
logicalOperatorNewline: normalizedSettings.logicalOperatorNewline,
@@ -520,6 +559,14 @@ export async function formatSqlText(sql: string, dialect: SqlFormatDialect = "ge
const usesDefaultStyle = normalizedSettings.layoutStyle === "dbx" && normalizedSettings.indentStyle === "standard";
const formatOnce = async (input: string): Promise<string> => {
+ if (normalizedSettings.customRulesEnabled) {
+ const customLayout = await formatSqlLayout({ sql: input, language, dialectOptions: resolvedDialect, cfg: formatterOptions, options: { ...layoutOptions, rules: normalizedSettings } });
+ appliedCustomRules = customLayout !== null;
+ if (customLayout !== null) return customLayout;
+ // Retry the original input through the saved base layout, without rule-only
+ // empty-line markers or spacing overrides. The disabled flag bounds the retry.
+ return formatSqlText(sql, dialect, { ...normalizedSettings, customRulesEnabled: false });
+ }
const laidOut = usesDefaultStyle ? await formatSqlLayout({ sql: input, language, dialectOptions: resolvedDialect, cfg: formatterOptions, options: layoutOptions }) : null;
return laidOut ?? formatWithFallback(input);
};
@@ -557,12 +604,20 @@ export async function formatSqlText(sql: string, dialect: SqlFormatDialect = "ge
* line, but masking them is cheap and defends against callers that ever pass
* raw (non-formatter) SQL through this path.
*/
-function maskStringAndCommentSpans(sql: string, dialect: SqlFormatDialect): { masked: string; spans: string[] } {
+function maskStringAndCommentSpans(sql: string, dialect: SqlFormatDialect, protectLineCommentTerminator = false): { masked: string; spans: string[] } {
const len = sql.length;
const spans: string[] = [];
const placeholder = (index: number) => `\x00${index}\x00`;
let out = "";
let i = 0;
+ const oracleQuotes =
+ dialect === "oracle"
+ ? new Map(
+ tokenizeSqlSemantic(sql, "oracle")
+ .filter((token) => token.kind === "string" && (token.quote === "q'" || token.quote === "nq'"))
+ .map((token) => [token.span.start, token.span.end]),
+ )
+ : null;
const isIdentifierPart = (c: string | undefined) => c !== undefined && /[A-Za-z0-9_$]/.test(c);
const supportsNestedBlockComments = dialect === "postgres" || dialect === "sqlserver" || dialect === "clickhouse";
@@ -587,6 +642,12 @@ function maskStringAndCommentSpans(sql: string, dialect: SqlFormatDialect): { ma
while (i < len) {
const ch = sql[i];
const next = sql[i + 1];
+ const oracleQuoteEnd = oracleQuotes?.get(i);
+ if (oracleQuoteEnd !== undefined) {
+ emit(i, oracleQuoteEnd);
+ i = oracleQuoteEnd;
+ continue;
+ }
// 块注释 /* ... */(含嵌套)
if (ch === "/" && next === "*") {
@@ -620,6 +681,7 @@ function maskStringAndCommentSpans(sql: string, dialect: SqlFormatDialect): { ma
const start = i;
i += startsDashComment ? 2 : 1;
while (i < len && sql[i] !== "\n" && sql[i] !== "\r") i++;
+ if (protectLineCommentTerminator && i < len) i += sql[i] === "\r" && sql[i + 1] === "\n" ? 2 : 1;
emit(start, i);
continue;
}
@@ -726,6 +788,14 @@ function maskStringAndCommentSpans(sql: string, dialect: SqlFormatDialect): { ma
return { masked: out, spans };
}
+/** Hide quoted/comment spans before identifying code-only paragraph boundaries. */
+function protectCodeEmptyLines(sql: string, dialect: SqlFormatDialect, single: boolean): EmptyLineProtection {
+ const { masked, spans } = maskStringAndCommentSpans(sql, dialect);
+ const code = single ? masked.replace(/(?:\r\n|\r|\n)[ \t]*(?:(?:\r\n|\r|\n)[ \t]*){2,}/g, "\n\n") : masked;
+ const protectedLines = protectEmptyLines(code, sql);
+ return { sql: restoreSpans(protectedLines.sql, spans), markers: protectedLines.markers };
+}
+
function restoreSpans(masked: string, spans: string[]): string {
return masked.replace(/\x00(\d+)\x00/g, (_, index) => spans[Number(index)] ?? "");
}
@@ -733,7 +803,8 @@ function restoreSpans(masked: string, spans: string[]): string {
function keepLogicalOperatorsOnSameLine(sql: string, dialect: SqlFormatDialect = "generic"): string {
// 先遮罩块注释/字符串/引号标识符,避免正则命中注释或字面量内部的 AND/OR/XOR
// (块注释内部跨行的 AND/OR 会被误折叠成空格,破坏用户多行注释格式)。
- const { masked, spans } = maskStringAndCommentSpans(sql, dialect);
+ // A line comment's terminator is a code boundary, not optional layout whitespace.
+ const { masked, spans } = maskStringAndCommentSpans(sql, dialect, true);
const collapsed = masked.replace(/\n[ \t]*(AND|OR|XOR)\b/gi, " $1").replace(/\b(AND|OR|XOR)[ \t]*\n[ \t]*/gi, "$1 ");
return restoreSpans(collapsed, spans);
}
@@ -751,8 +822,9 @@ function normalizeLikeOperatorCase(sql: string, settings: SqlFormatterSettings,
return restoreSpans(normalized, spans);
}
-function keepFromClauseAndFirstSourceOnSameLine(sql: string, indentStyle: SqlFormatterIndentStyle): string {
- const lines = sql.split("\n");
+function keepFromClauseAndFirstSourceOnSameLine(sql: string, indentStyle: SqlFormatterIndentStyle, dialect: SqlFormatDialect): string {
+ const { masked, spans } = maskStringAndCommentSpans(sql, dialect);
+ const lines = masked.split("\n");
for (let index = 0; index < lines.length - 1; index += 1) {
const clauseMatch = lines[index].match(/^(\s*)FROM\s*$/i);
if (!clauseMatch) continue;
@@ -763,7 +835,8 @@ function keepFromClauseAndFirstSourceOnSameLine(sql: string, indentStyle: SqlFor
const source = sourceMatch[2];
// Keep derived tables and leading comments multiline; merging these would
// make nested SQL and comment boundaries substantially harder to read.
- if (source.startsWith("(") || source.startsWith("/*") || source.startsWith("--")) continue;
+ const leadingSpan = source.startsWith("\x00") ? spans[Number(source.split("\x00", 3)[1])] : "";
+ if (source.startsWith("(") || leadingSpan.startsWith("/*") || leadingSpan.startsWith("--") || (dialect === "mysql" && leadingSpan.startsWith("#"))) continue;
const clauseIndent = clauseMatch[1];
const sourceIndent = sourceMatch[1];
@@ -778,7 +851,7 @@ function keepFromClauseAndFirstSourceOnSameLine(sql: string, indentStyle: SqlFor
lines.splice(index + 1, 1);
index -= 1;
}
- return lines.join("\n");
+ return restoreSpans(lines.join("\n"), spans);
}
function formatLeadingCommas(sql: string, dialect: SqlFormatDialect = "generic"): string {
@@ -846,7 +919,7 @@ function formatLeadingCommas(sql: string, dialect: SqlFormatDialect = "generic")
function applySqlFormatterLayout(sql: string, settings: SqlFormatterSettings, dialect: SqlFormatDialect): string {
let formatted = normalizeLikeOperatorCase(sql, settings, dialect);
if (settings.logicalOperatorNewline === "none") formatted = keepLogicalOperatorsOnSameLine(formatted, dialect);
- if (settings.fromClauseLayout === "sameLine") formatted = keepFromClauseAndFirstSourceOnSameLine(formatted, settings.indentStyle);
+ if (settings.fromClauseLayout === "sameLine") formatted = keepFromClauseAndFirstSourceOnSameLine(formatted, settings.indentStyle, dialect);
if (settings.commaPosition === "before") formatted = formatLeadingCommas(formatted, dialect);
return formatted;
}
diff --git a/apps/desktop/src/lib/sql/sqlFormatterConfig.ts b/apps/desktop/src/lib/sql/sqlFormatterConfig.ts
index 9ef0c7bee7..cd2ae99534 100644
--- a/apps/desktop/src/lib/sql/sqlFormatterConfig.ts
+++ b/apps/desktop/src/lib/sql/sqlFormatterConfig.ts
@@ -13,8 +13,13 @@ const LOGICAL_OPERATOR_NEWLINE_VALUES = ["before", "after", "none"] as const;
const COMMA_POSITION_VALUES = ["after", "before"] as const;
const FROM_CLAUSE_LAYOUT_VALUES = ["newLine", "sameLine"] 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;
+const LIST_LAYOUT_VALUES = ["singleLine", "fit", "vertical", "wrap"] as const;
+const LIST_LAYOUT_OVERRIDE_VALUES = ["inherit", ...LIST_LAYOUT_VALUES] as const;
+const COMMA_OVERRIDE_VALUES = ["inherit", ...COMMA_POSITION_VALUES] as const;
+const LOGICAL_OVERRIDE_VALUES = ["inherit", ...LOGICAL_OPERATOR_NEWLINE_VALUES] as const;
+const LIST_ALIGNMENT_VALUES = ["firstItem", "indent"] as const;
+const EMPTY_LINE_MODE_VALUES = ["inherit", "remove", "single", "preserve"] as const;
const SQL_FORMATTER_PARAM_TYPE_MARKERS = ["?", ":", "$"] as const;
const SQL_FORMATTER_NAMED_PARAM_TYPE_MARKERS = [":", "@", "$"] as const;
const SQL_FORMATTER_LEGACY_OPTION_KEYS = new Set(["params"]);
@@ -26,8 +31,54 @@ export type SqlFormatterLogicalOperatorNewline = (typeof LOGICAL_OPERATOR_NEWLIN
export type SqlFormatterCommaPosition = (typeof COMMA_POSITION_VALUES)[number];
export type SqlFormatterFromClauseLayout = (typeof FROM_CLAUSE_LAYOUT_VALUES)[number];
export type SqlFormatterTabWidth = (typeof TAB_WIDTH_VALUES)[number];
-export type SqlFormatterExpressionWidth = (typeof EXPRESSION_WIDTH_VALUES)[number];
+export type SqlFormatterExpressionWidth = number;
export type SqlFormatterLinesBetweenQueries = (typeof LINES_BETWEEN_QUERIES_VALUES)[number];
+export type SqlFormatterListLayout = (typeof LIST_LAYOUT_VALUES)[number];
+export type SqlFormatterListLayoutOverride = (typeof LIST_LAYOUT_OVERRIDE_VALUES)[number];
+export type SqlFormatterCommaOverride = (typeof COMMA_OVERRIDE_VALUES)[number];
+export type SqlFormatterLogicalOverride = (typeof LOGICAL_OVERRIDE_VALUES)[number];
+export type SqlFormatterListAlignment = (typeof LIST_ALIGNMENT_VALUES)[number];
+export type SqlFormatterEmptyLineMode = (typeof EMPTY_LINE_MODE_VALUES)[number];
+
+export interface SqlFormatterRuleSettings {
+ customRulesEnabled: boolean;
+ listLayout: SqlFormatterListLayout;
+ selectListLayout: SqlFormatterListLayoutOverride;
+ insertListLayout: SqlFormatterListLayoutOverride;
+ updateListLayout: SqlFormatterListLayoutOverride;
+ listItemAlignment: SqlFormatterListAlignment;
+ alignSelectAliases: boolean;
+ alignUpdateAssignments: boolean;
+ selectCommaPosition: SqlFormatterCommaOverride;
+ insertCommaPosition: SqlFormatterCommaOverride;
+ updateCommaPosition: SqlFormatterCommaOverride;
+ whereLogicalOperatorNewline: SqlFormatterLogicalOverride;
+ onLogicalOperatorNewline: SqlFormatterLogicalOverride;
+ expressionLogicalOperatorNewline: SqlFormatterLogicalOverride;
+ newlineBeforeJoinOn: boolean;
+ collapseShortStatements: boolean;
+ emptyLineMode: SqlFormatterEmptyLineMode;
+}
+
+export const DEFAULT_SQL_FORMATTER_RULE_SETTINGS: SqlFormatterRuleSettings = {
+ customRulesEnabled: false,
+ listLayout: "fit",
+ selectListLayout: "vertical",
+ insertListLayout: "fit",
+ updateListLayout: "fit",
+ listItemAlignment: "firstItem",
+ alignSelectAliases: true,
+ alignUpdateAssignments: false,
+ selectCommaPosition: "inherit",
+ insertCommaPosition: "inherit",
+ updateCommaPosition: "inherit",
+ whereLogicalOperatorNewline: "inherit",
+ onLogicalOperatorNewline: "inherit",
+ expressionLogicalOperatorNewline: "inherit",
+ newlineBeforeJoinOn: false,
+ collapseShortStatements: true,
+ emptyLineMode: "inherit",
+};
export interface SqlFormatterCustomParameter {
regex: string;
@@ -46,7 +97,7 @@ export interface SqlFormatterParamTypes {
custom?: SqlFormatterCustomParameter[];
}
-export interface SqlFormatterOptionSettings {
+export interface SqlFormatterOptionSettings extends SqlFormatterRuleSettings {
// DBX-private: selects which layout engine runs and never reaches
// sql-formatter itself (see sqlFormatterOptions).
layoutStyle: SqlFormatterLayoutStyle;
@@ -79,6 +130,7 @@ export interface SqlFormatterConfigFile {
export type SqlFormatterConfigParseResult = { ok: true; settings: SqlFormatterSettings } | { ok: false; message: string };
export const DEFAULT_SQL_FORMATTER_SETTINGS: SqlFormatterSettings = {
+ ...DEFAULT_SQL_FORMATTER_RULE_SETTINGS,
layoutStyle: "dbx",
keywordCase: "upper",
dataTypeCase: "preserve",
@@ -105,6 +157,7 @@ export const DEFAULT_SQL_FORMATTER_SETTINGS: SqlFormatterSettings = {
// stops importing wholesale, and given a row in the `expectedControls` list of
// lib/settings/__tests__/settingsSearch.spec.ts so its search entry stays pinned.
const SQL_FORMATTER_OPTION_KEYS = new Set<keyof SqlFormatterOptionSettings>([
+ ...(Object.keys(DEFAULT_SQL_FORMATTER_RULE_SETTINGS) as (keyof SqlFormatterRuleSettings)[]),
"layoutStyle",
"keywordCase",
"dataTypeCase",
@@ -125,6 +178,23 @@ const SQL_FORMATTER_OPTION_KEYS = new Set<keyof SqlFormatterOptionSettings>([
]);
const SQL_FORMATTER_OPTION_VALIDATORS: Record<keyof SqlFormatterOptionSettings, (value: unknown) => boolean> = {
+ customRulesEnabled: (value) => typeof value === "boolean",
+ listLayout: (value) => isStringChoice(value, LIST_LAYOUT_VALUES),
+ selectListLayout: (value) => isStringChoice(value, LIST_LAYOUT_OVERRIDE_VALUES),
+ insertListLayout: (value) => isStringChoice(value, LIST_LAYOUT_OVERRIDE_VALUES),
+ updateListLayout: (value) => isStringChoice(value, LIST_LAYOUT_OVERRIDE_VALUES),
+ listItemAlignment: (value) => isStringChoice(value, LIST_ALIGNMENT_VALUES),
+ alignSelectAliases: (value) => typeof value === "boolean",
+ alignUpdateAssignments: (value) => typeof value === "boolean",
+ selectCommaPosition: (value) => isStringChoice(value, COMMA_OVERRIDE_VALUES),
+ insertCommaPosition: (value) => isStringChoice(value, COMMA_OVERRIDE_VALUES),
+ updateCommaPosition: (value) => isStringChoice(value, COMMA_OVERRIDE_VALUES),
+ whereLogicalOperatorNewline: (value) => isStringChoice(value, LOGICAL_OVERRIDE_VALUES),
+ onLogicalOperatorNewline: (value) => isStringChoice(value, LOGICAL_OVERRIDE_VALUES),
+ expressionLogicalOperatorNewline: (value) => isStringChoice(value, LOGICAL_OVERRIDE_VALUES),
+ newlineBeforeJoinOn: (value) => typeof value === "boolean",
+ collapseShortStatements: (value) => typeof value === "boolean",
+ emptyLineMode: (value) => isStringChoice(value, EMPTY_LINE_MODE_VALUES),
layoutStyle: (value) => isStringChoice(value, LAYOUT_STYLE_VALUES),
keywordCase: (value) => isStringChoice(value, CASE_VALUES),
dataTypeCase: (value) => isStringChoice(value, CASE_VALUES),
@@ -136,7 +206,7 @@ const SQL_FORMATTER_OPTION_VALIDATORS: Record<keyof SqlFormatterOptionSettings,
logicalOperatorNewline: (value) => isStringChoice(value, LOGICAL_OPERATOR_NEWLINE_VALUES),
commaPosition: (value) => isStringChoice(value, COMMA_POSITION_VALUES),
fromClauseLayout: (value) => isStringChoice(value, FROM_CLAUSE_LAYOUT_VALUES),
- expressionWidth: (value) => isNumberChoice(value, EXPRESSION_WIDTH_VALUES),
+ expressionWidth: isExpressionWidth,
linesBetweenQueries: (value) => isNumberChoice(value, LINES_BETWEEN_QUERIES_VALUES),
preserveEmptyLines: (value) => typeof value === "boolean",
denseOperators: (value) => typeof value === "boolean",
@@ -156,6 +226,10 @@ function isNumberChoice(value: unknown, values: readonly number[]): boolean {
return typeof value === "number" && values.includes(value);
}
+function isExpressionWidth(value: unknown): value is number {
+ return typeof value === "number" && Number.isInteger(value) && value >= 20 && value <= 500;
+}
+
function isMarkerArray<T extends readonly string[]>(value: unknown, markers: T): value is T[number][] {
return Array.isArray(value) && value.every((item) => typeof item === "string" && markers.includes(item));
}
@@ -209,6 +283,23 @@ function normalizeParamTypes(value: unknown, fallback: SqlFormatterParamTypes |
export function sqlFormatterOptionSettings(settings: unknown): SqlFormatterOptionSettings {
const input = isObject(settings) ? settings : {};
return {
+ customRulesEnabled: normalizeBoolean(input.customRulesEnabled, DEFAULT_SQL_FORMATTER_SETTINGS.customRulesEnabled),
+ listLayout: normalizeChoice(input.listLayout, LIST_LAYOUT_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.listLayout),
+ selectListLayout: normalizeChoice(input.selectListLayout, LIST_LAYOUT_OVERRIDE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.selectListLayout),
+ insertListLayout: normalizeChoice(input.insertListLayout, LIST_LAYOUT_OVERRIDE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.insertListLayout),
+ updateListLayout: normalizeChoice(input.updateListLayout, LIST_LAYOUT_OVERRIDE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.updateListLayout),
+ listItemAlignment: normalizeChoice(input.listItemAlignment, LIST_ALIGNMENT_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.listItemAlignment),
+ alignSelectAliases: normalizeBoolean(input.alignSelectAliases, DEFAULT_SQL_FORMATTER_SETTINGS.alignSelectAliases),
+ alignUpdateAssignments: normalizeBoolean(input.alignUpdateAssignments, DEFAULT_SQL_FORMATTER_SETTINGS.alignUpdateAssignments),
+ selectCommaPosition: normalizeChoice(input.selectCommaPosition, COMMA_OVERRIDE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.selectCommaPosition),
+ insertCommaPosition: normalizeChoice(input.insertCommaPosition, COMMA_OVERRIDE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.insertCommaPosition),
+ updateCommaPosition: normalizeChoice(input.updateCommaPosition, COMMA_OVERRIDE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.updateCommaPosition),
+ whereLogicalOperatorNewline: normalizeChoice(input.whereLogicalOperatorNewline, LOGICAL_OVERRIDE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.whereLogicalOperatorNewline),
+ onLogicalOperatorNewline: normalizeChoice(input.onLogicalOperatorNewline, LOGICAL_OVERRIDE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.onLogicalOperatorNewline),
+ expressionLogicalOperatorNewline: normalizeChoice(input.expressionLogicalOperatorNewline, LOGICAL_OVERRIDE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.expressionLogicalOperatorNewline),
+ newlineBeforeJoinOn: normalizeBoolean(input.newlineBeforeJoinOn, DEFAULT_SQL_FORMATTER_SETTINGS.newlineBeforeJoinOn),
+ collapseShortStatements: normalizeBoolean(input.collapseShortStatements, DEFAULT_SQL_FORMATTER_SETTINGS.collapseShortStatements),
+ emptyLineMode: normalizeChoice(input.emptyLineMode, EMPTY_LINE_MODE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.emptyLineMode),
layoutStyle: normalizeChoice(input.layoutStyle, LAYOUT_STYLE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.layoutStyle),
keywordCase: normalizeChoice(input.keywordCase, CASE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.keywordCase),
dataTypeCase: normalizeChoice(input.dataTypeCase, CASE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.dataTypeCase),
@@ -220,7 +311,7 @@ export function sqlFormatterOptionSettings(settings: unknown): SqlFormatterOptio
logicalOperatorNewline: normalizeChoice(input.logicalOperatorNewline, LOGICAL_OPERATOR_NEWLINE_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.logicalOperatorNewline),
commaPosition: normalizeChoice(input.commaPosition, COMMA_POSITION_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.commaPosition),
fromClauseLayout: normalizeChoice(input.fromClauseLayout, FROM_CLAUSE_LAYOUT_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.fromClauseLayout),
- expressionWidth: normalizeNumberChoice(input.expressionWidth, EXPRESSION_WIDTH_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.expressionWidth),
+ expressionWidth: isExpressionWidth(input.expressionWidth) ? input.expressionWidth : DEFAULT_SQL_FORMATTER_SETTINGS.expressionWidth,
linesBetweenQueries: normalizeNumberChoice(input.linesBetweenQueries, LINES_BETWEEN_QUERIES_VALUES, DEFAULT_SQL_FORMATTER_SETTINGS.linesBetweenQueries),
preserveEmptyLines: normalizeBoolean(input.preserveEmptyLines, DEFAULT_SQL_FORMATTER_SETTINGS.preserveEmptyLines),
denseOperators: normalizeBoolean(input.denseOperators, DEFAULT_SQL_FORMATTER_SETTINGS.denseOperators),
diff --git a/docs/assets/sql-formatter-rules/preview.jpg b/docs/assets/sql-formatter-rules/preview.jpg
new file mode 100644
index 0000000000..6f8fd69dbe
Binary files /dev/null and b/docs/assets/sql-formatter-rules/preview.jpg differ
diff --git a/docs/assets/sql-formatter-rules/rules.jpg b/docs/assets/sql-formatter-rules/rules.jpg
new file mode 100644
index 0000000000..34c95c656a
Binary files /dev/null and b/docs/assets/sql-formatter-rules/rules.jpg differ
diff --git a/docs/content/docs/sql-formatter.cn.mdx b/docs/content/docs/sql-formatter.cn.mdx
index 8984b5c535..14335906dd 100644
--- a/docs/content/docs/sql-formatter.cn.mdx
+++ b/docs/content/docs/sql-formatter.cn.mdx
@@ -21,6 +21,7 @@ DBX 当前对以下方言使用专用格式化语法:
| PostgreSQL、openGauss、GaussDB、KingbaseES、Redshift 等兼容连接 | PostgreSQL |
| SQLite、Turso、rqlite、Cloudflare D1 | SQLite |
| SQL Server | Transact-SQL |
+| Oracle、OceanBase Oracle 模式 | PL/SQL |
| ClickHouse | ClickHouse |
| 其他 SQL 数据库 | 通用 SQL;必要时再尝试 PostgreSQL 语法 |
@@ -32,7 +33,7 @@ MongoDB 查询编辑器使用单独的 Mongo Shell 格式化器,不使用本
`classic` 使用 sql-formatter 自身的排版,也是 v0.6.16 之前 DBX 的默认风格。如需精确还原此前输出,可把**表达式宽度**设为 `50`、**FROM 子句布局**设为换行;JSON 中对应为 `"expressionWidth": 50`、`"fromClauseLayout": "newLine"`,与 `"layoutStyle": "classic"` 并列。除 Oracle 外结果与 v0.6.15 一致:Oracle 的字节/多字节函数变体(`SUBSTRB`、`INSTR2`、`LENGTHB` 等同族函数)保留较新的修复,会被规范为函数形式。
-切换排版风格只切引擎,不会顺带改写其它选项。两种缩进样式(`tabularLeft`、`tabularRight`)在两种风格下都使用 sql-formatter 自身的排版。
+未启用自定义规则时,切换排版风格不会顺带改写其它选项,两种表格式缩进(`tabularLeft`、`tabularRight`)都使用 sql-formatter 自身的排版。
## 配置格式化选项
@@ -47,7 +48,7 @@ MongoDB 查询编辑器使用单独的 Mongo Shell 格式化器,不使用本
| Tab 宽度 | `2` 或 `4` |
| 逻辑操作符换行 | `before`、`after`,或 `none` 保持在同一行 |
| FROM 子句排版 | `sameLine` 让首个表留在 `FROM` 行,`newLine` 让它换到下一行 |
-| 表达式宽度 | `50`、`80` 或 `120` |
+| 表达式宽度 | `20`–`500` 的整数,例如 `76`;长字面量不会被截断 |
| 查询间空行 | `0`、`1` 或 `2` |
| 保留空行 | 保留语句之间的空行 |
| 紧凑操作符 | 减少操作符周围的空格 |
@@ -56,9 +57,37 @@ MongoDB 查询编辑器使用单独的 Mongo Shell 格式化器,不使用本
**恢复默认值**会恢复当前代码定义的默认格式化设置。设置窗口中的改动需要点击 **应用** 才会持久化。
+## 分别控制 SELECT、INSERT 和 UPDATE
+
+在原格式化面板中启用自定义规则,再分别调整三类列表。自定义规则默认关闭;开启后使用规则布局,可与关键字左对齐或右对齐组合。关闭开关会恢复原先选择的基础布局,包括 `classic`,并保留已填写的规则值。
+
+四种列表模式适用于通用列表,也可由 SELECT 字段、INSERT 目标列与 VALUES 行、UPDATE SET 项分别覆盖:
+
+| 模式 | 排版方式 |
+| --- | --- |
+| `singleLine` | 列表保持单行,允许超出目标宽度;行注释仍保留必要的换行 |
+| `fit` | 放得下时单行,否则每项一行 |
+| `vertical` | 每项一行 |
+| `wrap` | 每行放入尽可能多的完整项,超过目标宽度时换行 |
+
+DML 选择 `inherit` 时继承通用规则。通用规则也用于函数参数、IN、GROUP BY、ORDER BY 等列表,不拆分字符串中的逗号。嵌套列表或条件要求的换行优先于外层短语句合并。
+
+其他细粒度选项:
+
+- `listItemAlignment` 选择续行对齐首项(`firstItem`)或缩进一级(`indent`)。`alignSelectAliases` 和 `alignUpdateAssignments` 分别控制多行显式 `AS` 与 SET 等号对齐;无法安全对齐时保留正常排版。
+- `selectCommaPosition`、`insertCommaPosition`、`updateCommaPosition` 分别选择前置、后置逗号,或以 `inherit` 使用全局 `commaPosition`。
+- `whereLogicalOperatorNewline`、`onLogicalOperatorNewline`、`expressionLogicalOperatorNewline` 分别控制 WHERE、JOIN ON 和其他表达式的 AND/OR,接受 `before`、`after`、`none` 或 `inherit`。`newlineBeforeJoinOn` 控制 ON 前换行。BETWEEN 自身的 AND 不会被当作条件分隔符。
+- `collapseShortStatements` 允许短语句合并为单行,但不能覆盖明确要求的换行。`emptyLineMode` 可移除代码空行(`remove`)、将连续空行合并为一行(`single`)、保留空行(`preserve`),或以 `inherit` 沿用原 `preserveEmptyLines`;字符串和注释内部空行不受影响。
+
+自定义规则生效时,`remove` 和 `single` 也将生成的查询间空行分别限制为 `0` 和 `1`;关闭规则或降级到基础布局后恢复原先保存的查询间隔。
+
+先在面板内输入 SQL、选择方言并观察即时预览,再应用设置。预览不会执行 SQL,也不会覆盖已打开的查询。用同一方言和设置在编辑器中格式化相同 SQL,结果与预览一致;选区外文本保持原样,可通过编辑器撤销恢复。
+
+完整过程块等超出规则模型的输入仍使用已选择的基础布局,并提示本次未应用自定义规则。需要细调过程内的查询时,选中独立 SELECT、INSERT 或 UPDATE 再格式化。本功能不提供 PL/SQL 过程声明、`:=` 赋值对齐或任意大小写词典。
+
## JSON 模式与导入导出
-JSON 模式适合精确编辑、复制或迁移格式化器配置。当前配置文件只包含 `version`、`formatter` 和 `options`:
+JSON 模式适合精确编辑、复制或迁移格式化器配置。配置文件包含 `version`、`formatter` 和 `options`;以下旧配置示例仍可导入,省略的新规则使用默认值:
```json
{
@@ -96,6 +125,8 @@ JSON 编辑器会实时校验配置。以下情况会阻止应用或导入:
点击 **导出配置** 会下载 `dbx-sql-formatter.json`。导入只替换 SQL 格式化选项,不会修改连接、编辑器快捷键或其他 DBX 设置。完整设置迁移请参阅[配置云同步](/cn/docs/cloud-sync)。
+导出会保存全部自定义规则。当前版本可导入缺少新字段的 v1/v2 配置及旧应用设置备份;旧版程序可能拒绝含新字段的配置,跨版本迁移时请保留原文件。
+
## 参数识别
`paramTypes` 为 `null` 时使用格式化器默认识别规则。需要额外语法时,可以配置:
diff --git a/docs/content/docs/sql-formatter.mdx b/docs/content/docs/sql-formatter.mdx
index eeefa06ea1..f73dbb27bb 100644
--- a/docs/content/docs/sql-formatter.mdx
+++ b/docs/content/docs/sql-formatter.mdx
@@ -21,6 +21,7 @@ DBX currently uses dedicated formatter grammars for:
| PostgreSQL, openGauss, GaussDB, KingbaseES, Redshift, and related profiles | PostgreSQL |
| SQLite, Turso, rqlite, and Cloudflare D1 | SQLite |
| SQL Server | Transact-SQL |
+| Oracle and OceanBase Oracle mode | PL/SQL |
| ClickHouse | ClickHouse |
| Other SQL databases | Generic SQL, with one PostgreSQL-grammar retry when needed |
@@ -32,7 +33,7 @@ The default `dbx` layout uses DBX's layout rules: explicit `AS` aliases align, a
`classic` uses sql-formatter's own layout and is also the DBX default from before v0.6.16. To reproduce that earlier output exactly, set **Expression width** to `50` and **FROM clause layout** to the new-line value; the JSON equivalent is `"expressionWidth": 50` and `"fromClauseLayout": "newLine"` next to `"layoutStyle": "classic"`. The result matches v0.6.15 except on Oracle, where the byte/multibyte function variants (`SUBSTRB`, `INSTR2`, `LENGTHB` and the rest of that family) keep the newer fix that normalizes them as functions.
-Switching the layout style only changes the engine; it never rewrites the other options. The two indent styles (`tabularLeft`, `tabularRight`) always use sql-formatter's own layout, in either mode.
+With custom rules disabled, switching the layout style never rewrites the other options. The two tabular indent styles (`tabularLeft`, `tabularRight`) use sql-formatter's own layout.
## Configure Formatting Options
@@ -47,7 +48,7 @@ Open **Settings → SQL Formatter**. Form mode exposes:
| Tab width | `2` or `4` |
| Logical operator newline | `before`, `after`, or `none` to keep them on the same line |
| FROM clause layout | `sameLine` keeps the first table on the `FROM` line, `newLine` moves it below |
-| Expression width | `50`, `80`, or `120` |
+| Expression width | An integer from `20` to `500`, such as `76`; long literals are never truncated |
| Lines between queries | `0`, `1`, or `2` |
| Preserve empty lines | Keeps blank lines between statements |
| Dense operators | Reduces spaces around operators |
@@ -56,9 +57,37 @@ Open **Settings → SQL Formatter**. Form mode exposes:
**Restore Defaults** restores the formatter settings defined by the current DBX build. Click **Apply** in the settings dialog to persist changes.
+## Separate SELECT, INSERT, and UPDATE Rules
+
+Enable custom rules in the existing formatter panel to configure the three list types independently. Custom rules are off by default. Enabling them selects the rule layout, which supports left- or right-aligned keywords. Disabling them restores the selected base layout, including `classic`, without discarding your rule values.
+
+Choose a general list mode, then override it for SELECT projections, INSERT target columns and each VALUES row, or UPDATE SET assignments:
+
+| Mode | Layout |
+| --- | --- |
+| `singleLine` | Keep the list on one line, even beyond the target width; line comments still require a line break |
+| `fit` | Use one line if the list fits; otherwise put each item on its own line |
+| `vertical` | Put each item on its own line |
+| `wrap` | Pack complete items onto each line up to the target width |
+
+Choose `inherit` for a DML list to use the general rule. General rules also apply to function arguments, IN, GROUP BY, and ORDER BY lists, without splitting commas inside literals. Required breaks in nested lists and conditions take precedence over collapsing an outer short statement.
+
+Additional controls:
+
+- `listItemAlignment` aligns continuation lines with the first item (`firstItem`) or one indent step (`indent`). `alignSelectAliases` and `alignUpdateAssignments` independently align multiline explicit `AS` aliases and SET equals signs when safe.
+- `selectCommaPosition`, `insertCommaPosition`, and `updateCommaPosition` independently select leading or trailing commas, or `inherit` the global `commaPosition`.
+- `whereLogicalOperatorNewline`, `onLogicalOperatorNewline`, and `expressionLogicalOperatorNewline` control AND/OR in WHERE, JOIN ON, and other expressions. Values are `before`, `after`, `none`, or `inherit`. `newlineBeforeJoinOn` starts ON on a new line. BETWEEN's own AND is not a condition separator.
+- `collapseShortStatements` allows short statements on one line but cannot override required breaks. `emptyLineMode` removes code-only blank lines (`remove`), collapses consecutive blank lines to one (`single`), preserves them (`preserve`), or inherits `preserveEmptyLines` (`inherit`). Blank lines inside literals and comments remain intact.
+
+While custom rules are applied, `remove` and `single` also limit generated spacing between queries to `0` and `1` blank lines, respectively. Disabling custom rules or falling back to the base layout restores the saved query spacing.
+
+Edit the sample SQL and dialect in the panel to preview changes before applying them. The preview never executes SQL or replaces an open query. Formatting the same SQL in the editor with the same dialect and settings produces the same result; text outside a selection stays unchanged and editor undo restores the original.
+
+Inputs outside the rule model, such as complete procedural blocks, retain the selected base formatting behavior and report that custom rules were not applied. Select an independent SELECT, INSERT, or UPDATE inside a procedure to apply the rules to that selection. PL/SQL declarations, `:=` assignment alignment, and arbitrary casing dictionaries are not provided.
+
## JSON Mode and Import / Export
-JSON mode is useful for exact editing, copying, or moving formatter settings. The current file contains only `version`, `formatter`, and `options`:
+JSON mode is useful for exact editing, copying, or moving formatter settings. A file contains `version`, `formatter`, and `options`. This older example still imports; omitted custom-rule options receive their defaults:
```json
{
@@ -96,6 +125,8 @@ The JSON editor validates the draft continuously. DBX blocks apply or import whe
**Export Config** downloads `dbx-sql-formatter.json`. Import replaces only SQL formatter options; it does not change connections, editor shortcuts, or other DBX settings. Use [Configuration Cloud Sync](/en/docs/cloud-sync) when you need a broader settings migration.
+Exports include all custom rules. This version accepts older v1/v2 formatter files and application-setting backups that lack the new fields. Older application versions may reject files containing new fields, so keep the original file when moving between versions.
+
## Parameter Recognition
Set `paramTypes` to `null` to use the formatter defaults. Configure additional parameter syntax with an object such as: