25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(sql): format CASE and REPLACE in mysql view definitions
zipg2ca2dda15b3f
diff --git a/apps/desktop/src/components/editor/__tests__/QueryEditor.formatCompressRequestReplay.spec.ts b/apps/desktop/src/components/editor/__tests__/QueryEditor.formatCompressRequestReplay.spec.tsindex 5a2988e259..bf9899615b 100644--- a/apps/desktop/src/components/editor/__tests__/QueryEditor.formatCompressRequestReplay.spec.ts+++ b/apps/desktop/src/components/editor/__tests__/QueryEditor.formatCompressRequestReplay.spec.ts@@ -268,4 +268,25 @@ describe("QueryEditor format/compress request replay", () => {expect(editorView.state.selection.main.anchor).toBe(0);expect(editorView.state.selection.main.head).toBe(formatted.length);});++ it.each([+ ["whole document", false, 13],+ ["full selection", true, 14],+ ] 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" });+ await waitForEditor(host);+ const editorView = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!;+ editorView.dispatch({ selection: { anchor: 0, head: selectAll ? source.length : 0 } });++ state.formatRequestId = requestId;+ await vi.waitFor(() => expect(emits.at(-1)).toContain("\n"), WAIT);++ expect(editorView.state.doc.toString()).toContain("REPLACE('a', 'a', 'b')");+ expect(editorView.state.doc.toString()).toContain("AS `结果`");+ if (selectAll) {+ expect(editorView.state.selection.main.from).toBe(0);+ expect(editorView.state.selection.main.to).toBe(editorView.state.doc.length);+ }+ });});diff --git a/apps/desktop/src/lib/__tests__/sql/mysqlReplaceFormatter.spec.ts b/apps/desktop/src/lib/__tests__/sql/mysqlReplaceFormatter.spec.tsnew file mode 100644index 0000000000..9c6725d50d--- /dev/null+++ b/apps/desktop/src/lib/__tests__/sql/mysqlReplaceFormatter.spec.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from "vitest";+import { formatSqlForDisplay, formatSqlForEditing, formatSqlText } from "@/lib/sql/sqlFormatter";+import { tokenizeSqlSemantic } from "@/lib/sql/semantic/tokens";++function sqlTokens(sql: string) {+ return tokenizeSqlSemantic(sql, "mysql").map(({ kind, normalized }) => ({ kind, normalized }));+}++const viewSql =+ "ALTER ALGORITHM=UNDEFINED DEFINER=`root`@`127.0.0.1` SQL SECURITY DEFINER VIEW `v_format_repro` AS WITH `库存处理` AS (SELECT CAST(CASE WHEN `单位` LIKE '%/%' THEN REPLACE(SUBSTRING_INDEX(`单位`,'/',1),'只','1') ELSE REPLACE(`单位`,'只','1') END AS UNSIGNED) * `实收数量` AS `数量` FROM `库存`) SELECT `数量` FROM `库存处理`;";++describe("MySQL REPLACE function formatting", () => {+ it.each(["standard", "tabularLeft", "tabularRight"] as const)("formats CASE expressions in view DDL using the %s layout", async (indentStyle) => {+ const formatted = await formatSqlText(viewSql, "mysql", { indentStyle });++ expect(formatted.split("\n").length).toBeGreaterThan(1);+ expect(sqlTokens(formatted)).toEqual(sqlTokens(viewSql));+ expect(formatted).toContain("`root` @`127.0.0.1`");+ });++ it.each([formatSqlForEditing, formatSqlForDisplay])("formats the view through the editing and display entry points", async (format) => {+ const formatted = await format(viewSql, "mysql");+ expect(formatted).not.toBe(viewSql);+ expect(formatted.split("\n").length).toBeGreaterThan(1);+ });++ it("uses function casing for REPLACE calls and preserves quoted identifiers and literals", async () => {+ const source = "select case when 1 then RePlAcE('REPLACE INTO','INTO','结果') end as `REPLACE`";+ const formatted = await formatSqlText(source, "mysql", { keywordCase: "upper", functionCase: "lower" });++ expect(formatted).toContain("THEN replace('REPLACE INTO', 'INTO', '结果')");+ expect(formatted).toContain("AS `REPLACE`");+ });++ it("recognizes calls separated from their parentheses by comments", async () => {+ const source = "SELECT CASE WHEN 1 THEN replace /* block */ ('a','a','b') ELSE RePlAcE -- line\n('c','c','d') END AS `结果`";+ const formatted = await formatSqlText(source, "mysql", { functionCase: "lower" });++ expect(formatted).toContain("replace/* block */");+ expect(formatted).toMatch(/replace -- line\n\s*\(/);+ expect(sqlTokens(formatted)).toEqual(sqlTokens(source));+ });++ it("keeps REPLACE statements as clauses while formatting function calls inside them", async () => {+ const source = "replace into `库存` (`单位`) values ('a'); replace low_priority into `库存` set `单位` = REPLACE('a','a','b'); replace delayed `库存` (`单位`) values ('c');";+ const formatted = await formatSqlText(source, "mysql", { keywordCase: "upper", functionCase: "lower" });++ expect(formatted).toContain("REPLACE INTO");+ expect(formatted).toContain("REPLACE LOW_PRIORITY INTO");+ expect(formatted).toContain("REPLACE DELAYED");+ expect(formatted).toContain("replace('a', 'a', 'b')");+ expect(formatted).toContain("`库存`");+ });++ it("retains MySQL's existing SET datatype and VALUES function handling", async () => {+ const source = "CREATE TABLE `t` (`x` SET('a','b')); INSERT INTO `t` VALUES ('a') ON DUPLICATE KEY UPDATE `x` = VALUES(`x`);";+ const formatted = await formatSqlText(source, "mysql");++ expect(formatted).toMatch(/SET\s*\('a', 'b'\)/);+ expect(formatted).toContain("VALUES(`x`)");+ });+});diff --git a/apps/desktop/src/lib/sql/sqlFormatter.ts b/apps/desktop/src/lib/sql/sqlFormatter.tsindex 33a40927c4..988f3d0a1d 100644--- a/apps/desktop/src/lib/sql/sqlFormatter.ts+++ b/apps/desktop/src/lib/sql/sqlFormatter.ts@@ -9,6 +9,37 @@ export const MAX_SQL_FORMAT_CHARS = 1_000_000;type SqlFormatterModule = typeof import("sql-formatter");+// MySQL's REPLACE is both a write statement and a string function. The+// upstream tokenizer prioritizes the statement token, which cannot appear in+// a CASE branch. Resolve calls by the next non-comment token without changing+// REPLACE INTO / LOW_PRIORITY / DELAYED statements or the source text.+let mysqlFunctionSafeDialect: SqlFormatterModule["mysql"] | null = null;++function resolveMysqlFunctionSafeDialect(sqlFormatter: SqlFormatterModule): SqlFormatterModule["mysql"] {+ if (mysqlFunctionSafeDialect) return mysqlFunctionSafeDialect;++ const options = sqlFormatter.mysql.tokenizerOptions;+ mysqlFunctionSafeDialect = {+ ...sqlFormatter.mysql,+ tokenizerOptions: {+ ...options,+ postProcess: (inputTokens) => {+ const tokens = options.postProcess?.(inputTokens) ?? inputTokens;+ return tokens.map((token, index) => {+ if (token.type !== "RESERVED_CLAUSE" || token.text !== "REPLACE") return token;++ let nextIndex = index + 1;+ while (tokens[nextIndex]?.type === "LINE_COMMENT" || tokens[nextIndex]?.type === "BLOCK_COMMENT") nextIndex += 1;+ if (tokens[nextIndex]?.type !== "OPEN_PAREN") return token;++ return { ...token, type: "RESERVED_FUNCTION_NAME" as (typeof tokens)[number]["type"] };+ });+ },+ },+ };+ return mysqlFunctionSafeDialect;+}+// sql-formatter classifies ClickHouse date-part abbreviations as reserved// keywords even where ClickHouse accepts them as ordinary identifiers. Keep// them identifier-like so keyword casing cannot rewrite aliases such as `m`.@@ -389,7 +420,7 @@ export async function formatSqlText(sql: string, dialect: SqlFormatDialect = "ge},}: options;- const resolvedDialect = dialect === "clickhouse" ? resolveClickHouseIdentifierSafeDialect(sqlFormatter) : dialect === "oracle" ? resolveOracleExtendedDialect(sqlFormatter) : undefined;+ const resolvedDialect = dialect === "mysql" ? resolveMysqlFunctionSafeDialect(sqlFormatter) : dialect === "clickhouse" ? resolveClickHouseIdentifierSafeDialect(sqlFormatter) : dialect === "oracle" ? resolveOracleExtendedDialect(sqlFormatter) : undefined;const formatWithFallback = (input: string): string => {try {if (resolvedDialect) {