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。

fix(editor): convert editor text from the keyword-case toggle

HARRISON18980ecdc27f
diff --git a/apps/desktop/src/App.vue b/apps/desktop/src/App.vue
index da4eaca9f3..1d28942995 100644
--- a/apps/desktop/src/App.vue
+++ b/apps/desktop/src/App.vue
@@ -486,6 +486,8 @@ const cursorPos = ref(0);
const previewChangesAvailable = ref(false);
const formatSqlRequest = ref<{ id: number; tabId: string } | null>(null);
const compressSqlRequest = ref<{ id: number; tabId: string } | null>(null);
+/** Toolbar `a`/`A`: keyword-only re-case for the acting editor (issue #11828). */
+const keywordCaseRequest = ref<{ id: number; tabId: string; mode: "upper" | "lower" } | null>(null);
const activeOutputView = computed<TabOutputView>({
get: () => activeTab.value?.uiState?.activeOutputView ?? "result",
set: (view) => {
@@ -2145,14 +2147,30 @@ function compressActiveSql(tabId?: string) {
};
}
-function toggleSqlKeywordCase() {
+function toggleSqlKeywordCase(tabId: string) {
const sqlFormatter = settingsStore.editorSettings.sqlFormatter;
+ const keywordCase = sqlFormatter.keywordCase === "lower" ? "upper" : "lower";
+ // Clicking the button and formatting must agree, so the preference flips and
+ // the editor re-cases the current document (or selection) to match — the
+ // button is labeled "使用大写/小写 SQL 关键字", and issue #11828 reported it as
+ // doing nothing because only the preference moved.
settingsStore.updateEditorSettings({
sqlFormatter: {
...sqlFormatter,
- keywordCase: sqlFormatter.keywordCase === "lower" ? "upper" : "lower",
+ keywordCase,
},
});
+
+ const tab = resolveToolbarTab(tabId);
+ if (!tab || tab.mode !== "query") return;
+ const connection = connectionStore.getConfig(tab.connectionId);
+ const databaseType = effectiveDatabaseTypeForConnection(connection) ?? connection?.db_type;
+ if (!canFormatSqlForDatabaseType(databaseType)) return;
+ keywordCaseRequest.value = {
+ id: (keywordCaseRequest.value?.id ?? 0) + 1,
+ tabId: tab.id,
+ mode: keywordCase,
+ };
}
function defaultSavedSqlName(title: string) {
@@ -5038,6 +5056,7 @@ onUnmounted(() => {
:active-output-view="activeOutputView"
:format-sql-request="formatSqlRequest"
:compress-sql-request="compressSqlRequest"
+ :keyword-case-request="keywordCaseRequest"
:selected-sql="selectedSql"
:cursor-pos="cursorPos"
:block-dangerous-redis-commands="blockDangerousRedisCommands"
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue
index e4ff3a9524..5c4364d05a 100644
--- a/apps/desktop/src/components/editor/QueryEditor.vue
+++ b/apps/desktop/src/components/editor/QueryEditor.vue
@@ -11,6 +11,7 @@
// (delivery is same-tick), never a pending undelivered one.
let lastHandledFormatRequestId = 0;
let lastHandledCompressRequestId = 0;
+let lastHandledKeywordCaseRequestId = 0;
let vimMappingsApplied = false;
let vimClipboardConfigured = false;
</script>
@@ -70,6 +71,7 @@ import { executableStatementRangeAtCursor, executableStatementRangeCacheForDoc,
import { looksLikeDmlStatement } from "@/lib/sql/dmlChangePreview";
import { canFormatSqlForDatabaseType, formatSqlText, compressSqlText } from "@/lib/sql/sqlFormatter";
+import { applySqlKeywordCase, loadSqlKeywordSpans } from "@/lib/sql/sqlKeywordCase";
import { detectAndFormatStructured } from "@/lib/sql/autoFormat";
import { restoreSqlFromSourcePaste } from "@/lib/sql/sqlSourcePaste";
import { enabledSqlParameterSyntaxes, resolveSqlVariableSyntaxToggles } from "@/lib/sql/sqlVariableSyntax";
@@ -1786,6 +1788,50 @@ function compressCurrentSql() {
});
}
+/**
+ * Toolbar `a`/`A`: re-case only the keywords of the selection, or of the whole
+ * document when there is none (issue #11828).
+ *
+ * The toolbar flips `keywordCase` at the same time, so this must agree with
+ * what a later 格式化 would produce for keywords — hence the keyword spans come
+ * from sql-formatter's own lexer ({@link loadSqlKeywordSpans}) rather than a
+ * word list. When the input cannot be classified the document is left as-is:
+ * `convertSqlSelectionCase` remains the explicit "convert everything" command
+ * in the context menu.
+ */
+async function convertCurrentSqlKeywordCase(mode: "upper" | "lower") {
+ if (props.readOnly) return;
+ // Mongo/Elasticsearch/Redis documents are not SQL. Their text can still look
+ // enough like a statement for the lexer to accept it — an ES request line
+ // `GET /_search` lexes as `GET` + path — so gate on the tab's real language
+ // rather than on whether tokenizing happens to succeed.
+ if (queryEditorSelectionLanguage() !== "sql") return;
+ const currentView = view.value;
+ if (!currentView) return;
+
+ const originalState = currentView.state;
+ const selection = originalState.selection.main;
+ const convertsSelection = !selection.empty;
+ const from = convertsSelection ? selection.from : 0;
+ const to = convertsSelection ? selection.to : originalState.doc.length;
+ const source = originalState.sliceDoc(from, to);
+ if (!source.trim()) return;
+
+ const formatDialect = props.formatDialect ?? props.dialect ?? "generic";
+ const spans = await loadSqlKeywordSpans(source, formatDialect);
+ // Edit races the await: the user may have typed, or switched tabs, since the
+ // request arrived. Re-check everything before dispatching.
+ if (!spans || currentView !== view.value || currentView.state !== originalState || originalState.sliceDoc(from, to) !== source) return;
+
+ const converted = applySqlKeywordCase(source, { from: 0, to: source.length }, mode, spans);
+ if (converted === source) return;
+
+ currentView.dispatch({
+ changes: { from, to, insert: converted },
+ selection: convertsSelection ? { anchor: from, head: from + converted.length } : { anchor: from + converted.length },
+ });
+}
+
const batchSelection = useQueryEditorBatchSelection({
view,
settingsStore,
@@ -2417,6 +2463,19 @@ watch(
},
);
+watch(
+ () => props.keywordCaseRequestId,
+ (val) => {
+ if (!val || val <= lastHandledKeywordCaseRequestId) return;
+ lastHandledKeywordCaseRequestId = val;
+ // The direction travels with the request: the id alone says "a click
+ // happened", but the mode is what the toggle switched to, and reading it
+ // back from settings could race a second click.
+ const mode = props.keywordCaseRequestMode;
+ if (mode) void convertCurrentSqlKeywordCase(mode);
+ },
+);
+
watch([() => props.executionError, () => props.executionErrorSql, () => props.executionErrorResult], () => {
reconfigureDiagnostics();
});
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 68cc5c5e1b..66c8eb1405 100644
--- a/apps/desktop/src/components/editor/__tests__/QueryEditor.formatCompressRequestReplay.spec.ts
+++ b/apps/desktop/src/components/editor/__tests__/QueryEditor.formatCompressRequestReplay.spec.ts
@@ -32,11 +32,13 @@ type EditorState = {
modelValue: string;
formatRequestId: number | undefined;
compressRequestId: number | undefined;
+ keywordCaseRequestId: number | undefined;
+ keywordCaseRequestMode: "upper" | "lower" | undefined;
};
const WAIT = { timeout: 5000, interval: 20 };
-function mountEditor(initial: { modelValue: string; tabId: string; databaseType?: DatabaseType; formatRequestId?: number; compressRequestId?: number }) {
+function mountEditor(initial: { modelValue: string; tabId: string; databaseType?: DatabaseType; formatRequestId?: number; compressRequestId?: number; keywordCaseRequestId?: number; keywordCaseRequestMode?: "upper" | "lower" }) {
const pinia = createPinia();
setActivePinia(pinia);
const state = reactive<EditorState>({
@@ -44,6 +46,8 @@ function mountEditor(initial: { modelValue: string; tabId: string; databaseType?
modelValue: initial.modelValue,
formatRequestId: initial.formatRequestId,
compressRequestId: initial.compressRequestId,
+ keywordCaseRequestId: initial.keywordCaseRequestId,
+ keywordCaseRequestMode: initial.keywordCaseRequestMode,
});
const emits: string[] = [];
const formatErrors: string[] = [];
@@ -58,6 +62,8 @@ function mountEditor(initial: { modelValue: string; tabId: string; databaseType?
autoFocus: false,
formatRequestId: state.formatRequestId,
compressRequestId: state.compressRequestId,
+ keywordCaseRequestId: state.keywordCaseRequestId,
+ keywordCaseRequestMode: state.keywordCaseRequestMode,
"onUpdate:modelValue": (value: string) => {
emits.push(value);
// Mirror the app: App.vue writes the emitted text back into the tab
@@ -296,4 +302,72 @@ describe("QueryEditor format/compress request replay", () => {
expect(editorView.state.selection.main.to).toBe(editorView.state.doc.length);
}
});
+
+ // #11828: the toolbar `a`/`A` button used to only flip the formatter
+ // preference, so clicking it left the text untouched and read as broken.
+ it("re-cases keywords in place for the whole document", async () => {
+ const source = "select id, name from users where status = 'active'";
+ const { state, emits, host } = mountEditor({ modelValue: source, tabId: "keyword-case" });
+ await waitForEditor(host);
+
+ state.keywordCaseRequestMode = "upper";
+ state.keywordCaseRequestId = 1;
+ await vi.waitFor(() => expect(emits.at(-1)).toBe("SELECT id, name FROM users WHERE status = 'active'"), WAIT);
+ });
+
+ it("re-cases only the selected range when there is a selection", async () => {
+ const source = "select a from t";
+ const { state, emits, host } = mountEditor({ modelValue: source, tabId: "keyword-case" });
+ await waitForEditor(host);
+ const editorView = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!;
+ const from = source.indexOf("from");
+ editorView.dispatch({ selection: { anchor: from, head: from + 4 } });
+
+ state.keywordCaseRequestMode = "upper";
+ state.keywordCaseRequestId = 2;
+ await vi.waitFor(() => expect(emits.at(-1)).toBe("select a FROM t"), WAIT);
+ });
+
+ it("keeps column names and string literals untouched while converting keywords", async () => {
+ // `status` / `note` are ordinary identifiers, and the literal's text must
+ // survive even though it contains keyword spellings.
+ const source = "select status, note from t where note = 'from where'";
+ const { state, emits, host } = mountEditor({ modelValue: source, tabId: "keyword-case" });
+ await waitForEditor(host);
+
+ state.keywordCaseRequestMode = "upper";
+ state.keywordCaseRequestId = 3;
+ await vi.waitFor(() => expect(emits.at(-1)).toBe("SELECT status, note FROM t WHERE note = 'from where'"), WAIT);
+ });
+
+ it("does not re-case a non-SQL document such as an Elasticsearch request", async () => {
+ const source = "GET /_search\n{}";
+ const { state, emits, host } = mountEditor({ modelValue: source, tabId: "es", databaseType: "elasticsearch" });
+ await waitForEditor(host);
+
+ state.keywordCaseRequestMode = "upper";
+ state.keywordCaseRequestId = 4;
+ await settle();
+ await settle();
+
+ expect(emits).toEqual([]);
+ });
+
+ it("does not replay a stale keyword-case request on a fresh mount", async () => {
+ const first = mountEditor({ modelValue: "select 1", tabId: "keyword-case" });
+ await waitForEditor(first.host);
+ first.state.keywordCaseRequestMode = "upper";
+ first.state.keywordCaseRequestId = 5;
+ await vi.waitFor(() => expect(first.emits.at(-1)).toBe("SELECT 1"), WAIT);
+ first.unmount();
+
+ // A remount re-arms the same stale id; the module-scope cursor must consume
+ // it instead of converting again.
+ const second = mountEditor({ modelValue: "SELECT 1", tabId: "keyword-case", keywordCaseRequestId: 5, keywordCaseRequestMode: "upper" });
+ await waitForEditor(second.host);
+ await settle();
+ await settle();
+
+ expect(second.emits).toEqual([]);
+ });
});
diff --git a/apps/desktop/src/components/editor/queryEditorTypes.ts b/apps/desktop/src/components/editor/queryEditorTypes.ts
index d1ae624494..b598e6ed69 100644
--- a/apps/desktop/src/components/editor/queryEditorTypes.ts
+++ b/apps/desktop/src/components/editor/queryEditorTypes.ts
@@ -20,6 +20,9 @@ export interface QueryEditorProps {
formatDialect?: SqlFormatDialect;
formatRequestId?: number;
compressRequestId?: number;
+ /** Toolbar `a`/`A`: convert keywords in place, matching `keywordCaseRequestMode`. */
+ keywordCaseRequestId?: number;
+ keywordCaseRequestMode?: "upper" | "lower";
executionError?: string;
executionErrorSql?: string;
executionErrorResult?: QueryResult;
diff --git a/apps/desktop/src/components/layout/ContentArea.vue b/apps/desktop/src/components/layout/ContentArea.vue
index 67a5f4756b..0d80795a6b 100644
--- a/apps/desktop/src/components/layout/ContentArea.vue
+++ b/apps/desktop/src/components/layout/ContentArea.vue
@@ -2013,6 +2013,8 @@ defineExpose({
:format-dialect="activeSqlFormatDialect"
:format-request-id="formatSqlRequest?.tabId === activeTab.id ? formatSqlRequest.id : undefined"
:compress-request-id="compressSqlRequest?.tabId === activeTab.id ? compressSqlRequest.id : undefined"
+ :keyword-case-request-id="keywordCaseRequest?.tabId === activeTab.id ? keywordCaseRequest.id : undefined"
+ :keyword-case-request-mode="keywordCaseRequest?.tabId === activeTab.id ? keywordCaseRequest.mode : undefined"
:execution-error="activeQueryError"
:execution-error-sql="activeTab.lastExecutedSql"
:execution-error-result="activeQueryError ? activeTab.result : undefined"
diff --git a/apps/desktop/src/components/layout/EditorGroup.vue b/apps/desktop/src/components/layout/EditorGroup.vue
index ff69fc150a..cd8272a0fc 100644
--- a/apps/desktop/src/components/layout/EditorGroup.vue
+++ b/apps/desktop/src/components/layout/EditorGroup.vue
@@ -62,6 +62,7 @@ const surfaceProps = computed<ContentAreaSurfaceProps>(() => ({
activeOutputView: props.activeOutputView,
formatSqlRequest: props.formatSqlRequest,
compressSqlRequest: props.compressSqlRequest,
+ keywordCaseRequest: props.keywordCaseRequest,
selectedSql: props.selectedSql,
cursorPos: props.cursorPos,
blockDangerousRedisCommands: props.blockDangerousRedisCommands,
@@ -243,7 +244,7 @@ const groupExecutableSql = computed(() => {
@compress-sql="activeTab && toolbar.compressSql(activeTab.id)"
@fold-all="activeSurfaceRef?.foldAll?.()"
@unfold-all="activeSurfaceRef?.unfoldAll?.()"
- @toggle-sql-keyword-case="toolbar.toggleSqlKeywordCase()"
+ @toggle-sql-keyword-case="activeTab && toolbar.toggleSqlKeywordCase(activeTab.id)"
@save-sql="(tabId: string) => toolbar.saveSql(tabId)"
@change-encoding="changeExternalSqlEncoding"
@open-sql="toolbar.openSqlFile()"
diff --git a/apps/desktop/src/components/layout/QueryEditorSurface.vue b/apps/desktop/src/components/layout/QueryEditorSurface.vue
index df958922b6..b8f513efb8 100644
--- a/apps/desktop/src/components/layout/QueryEditorSurface.vue
+++ b/apps/desktop/src/components/layout/QueryEditorSurface.vue
@@ -15,6 +15,7 @@ const surfaceProps = computed<ContentAreaSurfaceProps>(() => ({
activeOutputView: props.activeOutputView,
formatSqlRequest: props.formatSqlRequest,
compressSqlRequest: props.compressSqlRequest,
+ keywordCaseRequest: props.keywordCaseRequest,
selectedSql: props.selectedSql,
cursorPos: props.cursorPos,
blockDangerousRedisCommands: props.blockDangerousRedisCommands,
diff --git a/apps/desktop/src/components/layout/QueryResultSurface.vue b/apps/desktop/src/components/layout/QueryResultSurface.vue
index 32ca1997ff..357c189554 100644
--- a/apps/desktop/src/components/layout/QueryResultSurface.vue
+++ b/apps/desktop/src/components/layout/QueryResultSurface.vue
@@ -18,6 +18,7 @@ const surfaceProps = computed<ContentAreaSurfaceProps>(() => ({
activeOutputView: props.activeOutputView,
formatSqlRequest: props.formatSqlRequest,
compressSqlRequest: props.compressSqlRequest,
+ keywordCaseRequest: props.keywordCaseRequest,
selectedSql: props.selectedSql,
cursorPos: props.cursorPos,
blockDangerousRedisCommands: props.blockDangerousRedisCommands,
diff --git a/apps/desktop/src/components/layout/SqlEditorWorkspace.vue b/apps/desktop/src/components/layout/SqlEditorWorkspace.vue
index 4c94470f19..331d61b48c 100644
--- a/apps/desktop/src/components/layout/SqlEditorWorkspace.vue
+++ b/apps/desktop/src/components/layout/SqlEditorWorkspace.vue
@@ -50,6 +50,7 @@ const surfaceProps = computed(() => ({
activeOutputView: props.activeOutputView,
formatSqlRequest: props.formatSqlRequest,
compressSqlRequest: props.compressSqlRequest,
+ keywordCaseRequest: props.keywordCaseRequest,
selectedSql: props.selectedSql,
cursorPos: props.cursorPos,
blockDangerousRedisCommands: props.blockDangerousRedisCommands,
diff --git a/apps/desktop/src/components/layout/__tests__/AppTabBar.portal.spec.ts b/apps/desktop/src/components/layout/__tests__/AppTabBar.portal.spec.ts
index 16ade06b52..3f60cf4dcf 100644
--- a/apps/desktop/src/components/layout/__tests__/AppTabBar.portal.spec.ts
+++ b/apps/desktop/src/components/layout/__tests__/AppTabBar.portal.spec.ts
@@ -98,7 +98,7 @@ function mountNavigation(placement: "top" | "bottom" | "left" | "right", empty =
<div v-show="pages.driverActive" data-test="driver-page">Drivers</div>
</AppTabBar>
<div v-show="!active" data-test="editor-workspace-wrapper">
- <SqlEditorWorkspace ref="workspace" :active-tab="store.tabs.find(tab => tab.id === store.activeTabId)" :show-tab-navigation="store.tabs.length > 0 || pages.settingsOpen || pages.driverOpen" active-output-view="result" executable-sql="SELECT 1" :format-sql-request="null" :compress-sql-request="null" selected-sql="" :cursor-pos="0" :block-dangerous-redis-commands="false" :tab-bar-width="navigation.width" :tab-bar-collapsed="navigation.collapsed">
+ <SqlEditorWorkspace ref="workspace" :active-tab="store.tabs.find(tab => tab.id === store.activeTabId)" :show-tab-navigation="store.tabs.length > 0 || pages.settingsOpen || pages.driverOpen" active-output-view="result" executable-sql="SELECT 1" :format-sql-request="null" :compress-sql-request="null" :keyword-case-request="null" selected-sql="" :cursor-pos="0" :block-dangerous-redis-commands="false" :tab-bar-width="navigation.width" :tab-bar-collapsed="navigation.collapsed">
<template #empty><div data-test="welcome"><button @click="store.createTab('mysql-local', 'app', 'New query', 'query')">New query</button></div></template>
</SqlEditorWorkspace>
</div>
diff --git a/apps/desktop/src/components/layout/__tests__/EditorGroup.mount.spec.ts b/apps/desktop/src/components/layout/__tests__/EditorGroup.mount.spec.ts
index f5323f82f4..e347d5858e 100644
--- a/apps/desktop/src/components/layout/__tests__/EditorGroup.mount.spec.ts
+++ b/apps/desktop/src/components/layout/__tests__/EditorGroup.mount.spec.ts
@@ -113,6 +113,7 @@ describe("EditorGroup mount contract", () => {
activeOutputView: "result",
formatSqlRequest: null,
compressSqlRequest: null,
+ keywordCaseRequest: null,
selectedSql: "",
cursorPos: 0,
blockDangerousRedisCommands: false,
@@ -174,6 +175,7 @@ describe("EditorGroup mount contract", () => {
activeOutputView: "result",
formatSqlRequest: null,
compressSqlRequest: null,
+ keywordCaseRequest: null,
selectedSql: "",
cursorPos: 0,
blockDangerousRedisCommands: false,
@@ -204,6 +206,7 @@ describe("EditorGroup mount contract", () => {
cancelExecution: vi.fn(),
explain: vi.fn(),
saveSql: vi.fn(),
+ toggleSqlKeywordCase: vi.fn(),
};
const host = createHost();
@@ -217,6 +220,7 @@ describe("EditorGroup mount contract", () => {
activeOutputView: "result",
formatSqlRequest: null,
compressSqlRequest: null,
+ keywordCaseRequest: null,
selectedSql: "",
cursorPos: 0,
blockDangerousRedisCommands: false,
@@ -238,6 +242,9 @@ describe("EditorGroup mount contract", () => {
(toolbar as any).__vueParentComponent.emit("cancel");
(toolbar as any).__vueParentComponent.emit("explain");
(toolbar as any).__vueParentComponent.emit("saveSql", queryId);
+ // #11828: the keyword-case toggle must carry the acting tab, otherwise App
+ // cannot tell which editor to re-case (the button used to take no tab).
+ (toolbar as any).__vueParentComponent.emit("toggleSqlKeywordCase");
await nextTick();
expect(actions.captureExecutionSnapshot).toHaveBeenCalledWith(queryId);
expect(actions.toolbarExecute).toHaveBeenCalledWith("pointer", queryId);
@@ -245,6 +252,7 @@ describe("EditorGroup mount contract", () => {
expect(actions.cancelExecution).toHaveBeenCalledWith(queryId);
expect(actions.explain).toHaveBeenCalledWith(queryId);
expect(actions.saveSql).toHaveBeenCalledWith(queryId);
+ expect(actions.toggleSqlKeywordCase).toHaveBeenCalledWith(queryId);
// Data tab: no SQL toolbar — the data grid carries its own built-in bar.
app.unmount();
@@ -258,6 +266,7 @@ describe("EditorGroup mount contract", () => {
activeOutputView: "result",
formatSqlRequest: null,
compressSqlRequest: null,
+ keywordCaseRequest: null,
selectedSql: "",
cursorPos: 0,
blockDangerousRedisCommands: false,
diff --git a/apps/desktop/src/components/layout/editorToolbarActions.ts b/apps/desktop/src/components/layout/editorToolbarActions.ts
index 1719df6a0d..c6b4926ed2 100644
--- a/apps/desktop/src/components/layout/editorToolbarActions.ts
+++ b/apps/desktop/src/components/layout/editorToolbarActions.ts
@@ -35,7 +35,8 @@ export interface EditorToolbarActions {
explain(tabId: string): void;
formatSql(tabId: string): void;
compressSql(tabId: string): void;
- toggleSqlKeywordCase(): void;
+ /** Flips the keyword-case preference and re-cases the acting tab's editor to match. */
+ toggleSqlKeywordCase(tabId: string): void;
saveSql(tabId: string): void;
openSqlFile(): void;
importResultArchive(): void;
diff --git a/apps/desktop/src/components/layout/querySurfaces.ts b/apps/desktop/src/components/layout/querySurfaces.ts
index 8676f06d8e..be939420d6 100644
--- a/apps/desktop/src/components/layout/querySurfaces.ts
+++ b/apps/desktop/src/components/layout/querySurfaces.ts
@@ -64,6 +64,8 @@ export interface ContentAreaSurfaceProps {
activeOutputView: TabOutputView;
formatSqlRequest: { id: number; tabId: string } | null;
compressSqlRequest: { id: number; tabId: string } | null;
+ /** Toolbar `a`/`A`: re-case keywords in the acting tab's editor (issue #11828). */
+ keywordCaseRequest: { id: number; tabId: string; mode: "upper" | "lower" } | null;
selectedSql: string;
cursorPos: number;
blockDangerousRedisCommands: boolean;
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlKeywordCase.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlKeywordCase.spec.ts
new file mode 100644
index 0000000000..fcefd2e5c3
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/sql/sqlKeywordCase.spec.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it } from "vitest";
+import { applySqlKeywordCase, loadSqlKeywordSpans } from "@/lib/sql/sqlKeywordCase";
+
+async function convert(sql: string, mode: "upper" | "lower", dialect: Parameters<typeof loadSqlKeywordSpans>[1] = "mysql", range?: { from: number; to: number }) {
+ const spans = await loadSqlKeywordSpans(sql, dialect);
+ expect(spans).not.toBeNull();
+ return applySqlKeywordCase(sql, range ?? { from: 0, to: sql.length }, mode, spans!);
+}
+
+describe("loadSqlKeywordSpans", () => {
+ it("returns null for a dialect with no SQL grammar", async () => {
+ expect(await loadSqlKeywordSpans("MATCH (n) RETURN n", "cypher")).toBeNull();
+ });
+
+ it("returns an empty list for blank input", async () => {
+ expect(await loadSqlKeywordSpans(" \n ", "mysql")).toEqual([]);
+ });
+
+ it("declines input the lexer rejects instead of guessing", async () => {
+ // An unclosed string literal is a normal mid-typing state; the caller must
+ // leave the document alone rather than re-case a partial guess.
+ expect(await loadSqlKeywordSpans("select 'unclosed from t", "postgres")).toBeNull();
+ });
+
+ it("reports one span per multi-word clause, not one per word", async () => {
+ const sql = "select a from t group by a";
+ const spans = await loadSqlKeywordSpans(sql, "mysql");
+ const texts = spans!.map((span) => sql.slice(span.from, span.to));
+ expect(texts).toEqual(["select", "from", "group by"]);
+ });
+});
+
+describe("applySqlKeywordCase", () => {
+ it("converts keywords and leaves identifiers alone (#11828)", async () => {
+ await expect(convert("select id, name from users where id = 1", "upper")).resolves.toBe("SELECT id, name FROM users WHERE id = 1");
+ await expect(convert("SELECT id, name FROM users WHERE id = 1", "lower")).resolves.toBe("select id, name from users where id = 1");
+ });
+
+ it("re-cases a multi-word clause as a unit and leaves look-alike identifiers alone", async () => {
+ // PostgreSQL lexes `key` as an identifier, and `by` as one outside the
+ // clause, so only the clause moves. A plain word list would have
+ // upper-cased both columns — the exact corruption this must avoid.
+ await expect(convert("select by, key from t group by by", "upper", "postgres")).resolves.toBe("SELECT by, key FROM t GROUP BY by");
+ // MySQL genuinely reserves `by`/`key`, and its own formatter upper-cases
+ // them too; matching 格式化 is the contract here.
+ await expect(convert("select by, key from t group by by", "upper", "mysql")).resolves.toBe("SELECT BY, KEY FROM t GROUP BY BY");
+ });
+
+ it("protects string literals, quoted identifiers and comments", async () => {
+ const sql = `select 'select from' as s, "key" from t -- group by\nwhere x = 'AND'`;
+ await expect(convert(sql, "upper")).resolves.toBe(`SELECT 'select from' AS s, "key" FROM t -- group by\nWHERE x = 'AND'`);
+ });
+
+ it("leaves MySQL backtick identifiers intact", async () => {
+ await expect(convert("select `select`, `from` from t", "upper")).resolves.toBe("SELECT `select`, `from` FROM t");
+ });
+
+ it("does not touch function names or data types", async () => {
+ // The toolbar toggles *keyword* case; functions/data types follow their own
+ // settings, exactly as sql-formatter's keywordCase does.
+ await expect(convert("select count(*), cast(a as int) from t", "upper")).resolves.toBe("SELECT count(*), cast(a AS int) FROM t");
+ });
+
+ it("converts CASE expressions and logical operators", async () => {
+ await expect(convert("select case when a then b else c end from t where x and y or z", "upper")).resolves.toBe("SELECT CASE WHEN a THEN b ELSE c END FROM t WHERE x AND y OR z");
+ });
+
+ it("re-cases backtick-quoted identifiers pasted into a PostgreSQL editor", async () => {
+ // DBX's formatter options treat backticks as opaque under PostgreSQL; the
+ // keyword scan has to tolerate them for the same reason.
+ await expect(convert("select `weird` from t", "upper", "postgres")).resolves.toBe("SELECT `weird` FROM t");
+ });
+
+ it("converts only the requested slice, for the caller to dispatch", async () => {
+ // The return value replaces [from, to) at the call site, so it is the
+ // converted range itself and not the whole document.
+ const sql = "select a from t";
+ const from = sql.indexOf("from");
+ const spans = await loadSqlKeywordSpans(sql, "mysql");
+ expect(applySqlKeywordCase(sql, { from, to: from + 4 }, "upper", spans!)).toBe("FROM");
+ });
+
+ it("returns the range unchanged when it holds no keyword", async () => {
+ const sql = "select status, name from t";
+ const from = sql.indexOf("status");
+ await expect(convert(sql, "upper", "mysql", { from, to: from + 6 })).resolves.toBe("status");
+ });
+
+ it("converts every dialect's own clause vocabulary", async () => {
+ await expect(convert("select top 5 a from t", "upper", "sqlserver")).resolves.toBe("SELECT TOP 5 a FROM t");
+ await expect(convert("select a from t minus select b from u", "upper", "oracle")).resolves.toBe("SELECT a FROM t MINUS SELECT b FROM u");
+ });
+});
diff --git a/apps/desktop/src/lib/sql/sqlFormatter.ts b/apps/desktop/src/lib/sql/sqlFormatter.ts
index 0055b647df..56c8bdcbb0 100644
--- a/apps/desktop/src/lib/sql/sqlFormatter.ts
+++ b/apps/desktop/src/lib/sql/sqlFormatter.ts
@@ -167,6 +167,18 @@ function formatterLanguage(dialect: SqlFormatDialect) {
}
}
+/**
+ * sql-formatter's language key for a format dialect, or `null` for a dialect
+ * that has no SQL grammar at all (Cypher — see {@link formatSqlText}, which
+ * routes it to the Cypher formatter before reaching sql-formatter).
+ *
+ * Exported so callers that need sql-formatter's own tokenization — keyword-only
+ * case conversion — resolve the dialect exactly the way formatting does.
+ */
+export function formatterLanguageForDialect(dialect: SqlFormatDialect): string | null {
+ return dialect === "cypher" ? null : formatterLanguage(dialect);
+}
+
function splitTrailingStandaloneDot(sql: string): { body: string; suffix: string } | null {
const match = /\s+\.(\s*)$/.exec(sql);
if (!match || match.index === 0) return null;
diff --git a/apps/desktop/src/lib/sql/sqlKeywordCase.ts b/apps/desktop/src/lib/sql/sqlKeywordCase.ts
new file mode 100644
index 0000000000..55cea8c75f
--- /dev/null
+++ b/apps/desktop/src/lib/sql/sqlKeywordCase.ts
@@ -0,0 +1,117 @@
+import { loadEngine } from "@/lib/sql/layout/internals";
+import { formatterLanguageForDialect, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
+
+/**
+ * Re-casing SQL keywords in place, without touching identifiers.
+ *
+ * The toolbar's `a`/`A` button used to only flip the formatter preference, so
+ * clicking it changed nothing on screen (issue #11828). It now converts the
+ * text immediately *and* updates the preference, which means it needs a
+ * keyword-only case conversion.
+ *
+ * `convertSqlSelectionCase` (the context menu's 转为大写/小写) cannot serve
+ * here: it re-cases every non-protected word, so it also rewrites unquoted
+ * identifiers — a semantic change on case-sensitive engines (PostgreSQL, MySQL
+ * on Linux). "Keywords only" needs to know which words are keywords, and for a
+ * multi-word clause the words are not independently classified: in
+ * `select by from t group by by` the first `by` is a column while `group by`
+ * is one keyword phrase.
+ *
+ * So classification comes from sql-formatter's own lexer, reached through the
+ * `sql-formatter/dist/` alias in {@link loadEngine}. That is also what keeps
+ * this in sync with the formatter: the token types below are exactly the ones
+ * whose text `keywordCase` rewrites, so a click and a later 格式化 agree.
+ */
+
+/**
+ * sql-formatter token types that follow `keywordCase`.
+ *
+ * `RESERVED_FUNCTION_NAME` and `RESERVED_DATA_TYPE` are deliberately absent:
+ * the formatter re-cases those under `functionCase` / `dataTypeCase`, and the
+ * toolbar button promises "keywords".
+ */
+const KEYWORD_TOKEN_TYPES = new Set(["RESERVED_SELECT", "RESERVED_CLAUSE", "RESERVED_SET_OPERATION", "RESERVED_JOIN", "RESERVED_KEYWORD", "RESERVED_KEYWORD_PHRASE", "ARRAY_KEYWORD", "CASE", "WHEN", "THEN", "ELSE", "END", "BETWEEN", "AND", "OR", "XOR", "LIMIT"]);
+
+export interface SqlKeywordSpan {
+ from: number;
+ to: number;
+}
+
+export type SqlKeywordCaseMode = "upper" | "lower";
+
+/**
+ * PostgreSQL has no backtick identifiers, but users paste MySQL-style SQL into
+ * a PostgreSQL editor. DBX's formatter options already treat complete backtick
+ * spans as opaque so formatting survives that; the tokenizer needs the same
+ * allowance or one pasted identifier would abort the whole scan.
+ */
+const POSTGRES_BACKTICK_PARAM_TYPES = { custom: [{ regex: "`(?:``|[^`])*`" }] };
+
+/**
+ * The keyword spans of `sql`, as offsets into that exact string, in order.
+ *
+ * Returns `null` — never a partial list — when this input cannot be classified:
+ * a non-SQL dialect (Cypher), sql-formatter internals unavailable, or an input
+ * the lexer rejects (an unclosed string, i.e. mid-typing). Callers leave the
+ * text alone on `null`; guessing is what could rewrite an identifier.
+ */
+export async function loadSqlKeywordSpans(sql: string, dialect: SqlFormatDialect): Promise<SqlKeywordSpan[] | null> {
+ if (!sql.trim()) return [];
+ const language = formatterLanguageForDialect(dialect);
+ if (!language) return null;
+
+ const engine = await loadEngine();
+ if (!engine) return null;
+
+ const dialectOptions = engine.dialects[language] ?? engine.dialects.sql;
+ if (!dialectOptions) return null;
+
+ const paramTypes = language === "postgresql" ? POSTGRES_BACKTICK_PARAM_TYPES : {};
+ let tokens;
+ try {
+ tokens = engine.createDialect(dialectOptions).tokenizer.tokenize(sql, paramTypes);
+ } catch {
+ return null;
+ }
+
+ const spans: SqlKeywordSpan[] = [];
+ for (const token of tokens) {
+ if (!KEYWORD_TOKEN_TYPES.has(token.type as string)) continue;
+ // `raw` is verbatim source, so a phrase that spans a line break still
+ // slices back to exactly those characters.
+ spans.push({ from: token.start, to: token.start + token.raw.length });
+ }
+ return spans;
+}
+
+/**
+ * Re-cases the keyword `spans` intersecting `[from, to)`, copying every other
+ * byte through untouched.
+ *
+ * `spans` come from {@link loadSqlKeywordSpans} for the same document text, so
+ * this stays a pure slice-and-join with no re-tokenizing. Returns the converted
+ * slice, or that slice unchanged when no keyword actually differs in case.
+ */
+export function applySqlKeywordCase(sql: string, range: { from: number; to: number }, mode: SqlKeywordCaseMode, spans: readonly SqlKeywordSpan[]): string {
+ const from = Math.max(0, Math.min(range.from, sql.length));
+ const to = Math.max(from, Math.min(range.to, sql.length));
+
+ let converted = "";
+ let cursor = from;
+ let changed = false;
+ for (const span of spans) {
+ const start = Math.max(from, span.from);
+ const end = Math.min(to, span.to);
+ if (end <= start) continue;
+ converted += sql.slice(cursor, start);
+ const text = sql.slice(start, end);
+ const replacement = mode === "upper" ? text.toUpperCase() : text.toLowerCase();
+ if (replacement !== text) changed = true;
+ converted += replacement;
+ cursor = end;
+ }
+
+ if (!changed) return sql.slice(from, to);
+ converted += sql.slice(cursor, to);
+ return converted;
+}