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): preserve keyword case in layout formatter
lxk955845fe37b86f6
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlLayout.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlLayout.spec.tsindex 5e0bcf4c21..de750cd6b2 100644--- a/apps/desktop/src/lib/__tests__/sql/sqlLayout.spec.ts+++ b/apps/desktop/src/lib/__tests__/sql/sqlLayout.spec.ts@@ -359,4 +359,28 @@ describe("sql layout", () => {),);});++ it("preserves keyword case when keywordCase is preserve (#11382)", async () => {+ const sql = lines("select id as emp_id, name as emp_name", "from employees", "where status = 1 and dept = 'sales'", "order by id desc", "limit 10;");+ expect(await format(sql, { keywordCase: "preserve" })).toBe(lines("select id as emp_id,", " name as emp_name", "from employees", "where status = 1", " and dept = 'sales'", "order by id desc", "limit 10;"));+ });++ it("converts keyword case to lower when keywordCase is lower (#11382)", async () => {+ const sql = lines("SELECT id AS emp_id, name AS emp_name", "FROM employees", "WHERE status = 1 AND dept = 'sales'", "ORDER BY id DESC", "LIMIT 10;");+ expect(await format(sql, { keywordCase: "lower" })).toBe(lines("select id as emp_id,", " name as emp_name", "from employees", "where status = 1", " and dept = 'sales'", "order by id desc", "limit 10;"));+ });++ it("preserves keyword case in join, union, case expression and ddl (#11382)", async () => {+ const joinSql = "select a.id from t1 left join t2 on t1.id = t2.id;";+ expect(await format(joinSql, { keywordCase: "preserve" })).toBe(lines("select a.id", "from t1", " left join t2 on t1.id = t2.id;"));++ const unionSql = lines("select 1", "union all", "select 2;");+ expect(await format(unionSql, { keywordCase: "preserve" })).toBe(lines("select 1", "union all", "select 2;"));++ const caseSql = "select case when a = 1 then 'one' else 'other' end as val from t;";+ expect(await format(caseSql, { keywordCase: "preserve" })).toBe("select case when a = 1 then 'one' else 'other' end as val from t;");++ const ddlSql = "create table test (id int, name varchar(255));";+ expect(await format(ddlSql, { keywordCase: "preserve" })).toBe("create table test (id int, name varchar(255));");+ });});diff --git a/apps/desktop/src/lib/sql/layout/ddl.ts b/apps/desktop/src/lib/sql/layout/ddl.tsindex 739c0d008d..3e10ab230e 100644--- a/apps/desktop/src/lib/sql/layout/ddl.ts+++ b/apps/desktop/src/lib/sql/layout/ddl.ts@@ -93,7 +93,7 @@ export function createTableLayout(statement: StatementNode, ctx: SqlLayoutContexconst nameText = renderInline(ctx, [name], ctx.options.lineWidth - clause.nameKw.text.length - 1);if (!nameText) throw new Error("a CREATE TABLE table name must fit on one line");- writer.write(`${keywordText(clause.nameKw.text, ctx)} ${nameText}`);+ writer.write(`${keywordText(clause.nameKw, ctx)} ${nameText}`);writer.newline(0);writer.write("(");@@ -160,7 +160,7 @@ function emitDefinition(writer: Writer, nodes: AstNode[], indent: number, ctx: Sconst [first, second] = nodes;if (first?.type === "keyword" && second?.type === "identifier") {- writer.write(`${keywordText(first.text, ctx)} ${renderInline(ctx, [second], ctx.options.lineWidth) ?? second.text}`);+ writer.write(`${keywordText(first, ctx)} ${renderInline(ctx, [second], ctx.options.lineWidth) ?? second.text}`);writer.newline(indent + ctx.options.indentWidth);writer.write(ctx.renderers.block(nodes.slice(2)).trim());if (endsWithLineComment(nodes.slice(2))) writer.markLineComment();diff --git a/apps/desktop/src/lib/sql/layout/primitives.ts b/apps/desktop/src/lib/sql/layout/primitives.tsindex 7a6e807492..143ca9cc03 100644--- a/apps/desktop/src/lib/sql/layout/primitives.ts+++ b/apps/desktop/src/lib/sql/layout/primitives.ts@@ -199,16 +199,20 @@ export function endsWithLineComment(nodes: AstNode[]): boolean {* The keyword a node opens its line with, or `null` for a node that is part of* an expression. Clauses, set operations and limit clauses each start a line.*/-export function bodyKeyword(node: AstNode): string | null {+export function bodyKeywordNode(node: AstNode): KeywordNode | null {if (node.type === "clause" || node.type === "set_operation") {- return (node as ClauseNode | SetOperationNode).nameKw.text;+ return (node as ClauseNode | SetOperationNode).nameKw;}if (node.type === "limit_clause") {- return (node as LimitClauseNode).limitKw.text;+ return (node as LimitClauseNode).limitKw;}return null;}+export function bodyKeyword(node: AstNode): string | null {+ return bodyKeywordNode(node)?.text ?? null;+}+export function isBodyNode(node: AstNode): boolean {return bodyKeyword(node) !== null;}@@ -238,14 +242,17 @@ export function limitChildren(node: LimitClauseNode): AstNode[] {return node.offset ? [...node.offset, LIMIT_SEPARATOR, ...node.count] : [...node.count];}-export function keywordText(text: string, ctx: SqlLayoutContext): string {+export function keywordText(token: AstNode | string, ctx: SqlLayoutContext): string {+ const text = typeof token === "string" ? token : (token as KeywordNode).text;+ const raw = typeof token === "object" && token && "raw" in token && typeof (token as KeywordNode).raw === "string" ? (token as KeywordNode).raw : undefined;switch (ctx.options.keywordCase) {case "upper":return text.toUpperCase();case "lower":return text.toLowerCase();+ case "preserve":default:- return text;+ return raw ? raw.replace(/\s+/g, " ") : text;}}@@ -273,7 +280,7 @@ function containsComments(value: unknown, seen = new Set<object>()): boolean {function renderCompactCaseExpression(ctx: SqlLayoutContext, node: CaseExpressionNode, width: number): string | null {if (containsComments(node)) return null;- const parts: string[] = [keywordText(node.caseKw.text, ctx)];+ const parts: string[] = [keywordText(node.caseKw, ctx)];const append = (text: string | null): boolean => {if (!text) return false;parts.push(text);@@ -284,17 +291,17 @@ function renderCompactCaseExpression(ctx: SqlLayoutContext, node: CaseExpressionfor (const clause of node.clauses) {if (clause.type === "case_when") {- if (!append(keywordText(clause.whenKw.text, ctx))) return null;+ if (!append(keywordText(clause.whenKw, ctx))) return null;if (!append(renderInline(collapsedContext(ctx), clause.condition, width))) return null;- if (!append(keywordText(clause.thenKw.text, ctx))) return null;+ if (!append(keywordText(clause.thenKw, ctx))) return null;if (!append(renderInline(collapsedContext(ctx), clause.result, width))) return null;} else {- if (!append(keywordText(clause.elseKw.text, ctx))) return null;+ if (!append(keywordText(clause.elseKw, ctx))) return null;if (!append(renderInline(collapsedContext(ctx), clause.result, width))) return null;}}- if (!append(keywordText(node.endKw.text, ctx))) return null;+ if (!append(keywordText(node.endKw, ctx))) return null;return parts.join(" ");}@@ -460,15 +467,16 @@ export function renderInline(ctx: SqlLayoutContext, nodes: AstNode[], width: numconst parts: string[] = [];let used = 0;for (const node of nodes) {- const keyword = bodyKeyword(node);- if (!keyword) return null;+ const kwNode = bodyKeywordNode(node);+ if (!kwNode) return null;const childCtx = node.type === "limit_clause" ? ctx : clauseChildContext(ctx, node as ClauseNode);const children = node.type === "limit_clause" ? limitChildren(node as LimitClauseNode) : (node as ClauseNode).children;- const text = renderInline(childCtx, children, width - used - keyword.length - 2);+ const kwText = keywordText(kwNode, ctx);+ const text = renderInline(childCtx, children, width - used - kwText.length - 2);if (!text) return null;- used += (parts.length > 0 ? 1 : 0) + keyword.length + 1 + text.length;+ used += (parts.length > 0 ? 1 : 0) + kwText.length + 1 + text.length;if (used > width) return null;- parts.push(`${keywordText(keyword, ctx)} ${text}`);+ parts.push(`${kwText} ${text}`);}return parts.join(" ");}@@ -580,7 +588,7 @@ function renderLogicalJoin(ctx: SqlLayoutContext, nodes: AstNode[], width: numbecontinue;}if (!flush()) return null;- const operator = keywordText(node.text, ctx);+ const operator = keywordText(node, ctx);used += operator.length + 1;parts.push(operator);}diff --git a/apps/desktop/src/lib/sql/layout/printer.ts b/apps/desktop/src/lib/sql/layout/printer.tsindex 9341eadff4..89d40ca776 100644--- a/apps/desktop/src/lib/sql/layout/printer.ts+++ b/apps/desktop/src/lib/sql/layout/printer.ts@@ -54,7 +54,7 @@ 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 {- const keyword = keywordText(clause.nameKw.text, ctx);+ const keyword = keywordText(clause.nameKw, ctx);const items = splitByComma(clause.children);const itemColumn = baseColumn + keyword.length + 1;const projection = isProjectionClauseName(clause.nameKw.text);@@ -123,7 +123,7 @@ function alignedProjectionItems(items: AstNode[][], ctx: SqlLayoutContext, lineWconst expression = renderInline(ctx, item.slice(0, asIndex), lineWidth);const alias = renderInline(ctx, item.slice(asIndex + 1), lineWidth);if (!expression || !alias) return null;- return { expression, alias, asKeyword: keywordText(asNode.text, ctx), aliasColumn: 0 };+ return { expression, alias, asKeyword: keywordText(asNode, ctx), aliasColumn: 0 };});if (!parsed.some(Boolean)) return null;@@ -135,7 +135,7 @@ function alignedProjectionItems(items: AstNode[][], ctx: SqlLayoutContext, lineW/** Emits a `LIMIT` clause, which sql-formatter renders as keyword + expressions. */function printLimitClause(writer: Writer, clause: LimitClauseNode, ctx: SqlLayoutContext): void {- const keyword = keywordText(clause.limitKw.text, ctx);+ const keyword = keywordText(clause.limitKw, ctx);const children = limitChildren(clause);const flat = renderInline(ctx, children, ctx.options.lineWidth - writer.column - keyword.length - 1);if (flat) {@@ -206,7 +206,7 @@ function writeParenthesis(writer: Writer, nodes: AstNode[], index: number, ctx:* sibling-clause form (`SELECT ... UNION ALL SELECT ...`) puts it as well.*/function printSetOperation(writer: Writer, node: SetOperationNode, baseColumn: number, ctx: SqlLayoutContext): void {- writer.write(keywordText(node.nameKw.text, ctx));+ writer.write(keywordText(node.nameKw, ctx));if (node.children.length === 0) return;writer.newline(baseColumn);printSetOperationOperand(writer, node.children, ctx);@@ -241,7 +241,7 @@ function printCondition(writer: Writer, operands: AstNode[][], baseColumn: numbecontinue;}- const operator = keywordText(head.text, ctx);+ const operator = keywordText(head, ctx);if (ctx.options.logicalOperatorNewline === "before") {writer.newline(column);writer.write(operator);@@ -290,7 +290,7 @@ function printElement(writer: Writer, nodes: AstNode[], baseColumn: number, ctx:// A JOIN keyword opens a new line one "Join indent" in from the FROM clause.if (isJoinKeyword(node)) {writer.newline(baseColumn + ctx.options.joinIndentWidth);- writer.write(keywordText(node.text, ctx));+ writer.write(keywordText(node, ctx));index += 1;continue;}diff --git a/packages/app-tests/sqlFormatter.test.ts b/packages/app-tests/sqlFormatter.test.tsindex d319fafb2f..fdd2614dbd 100644--- a/packages/app-tests/sqlFormatter.test.ts+++ b/packages/app-tests/sqlFormatter.test.ts@@ -319,3 +319,21 @@ test("Oracle: formats byte and code-point function variants with functionCase",assert.match(formattedUpper, /\bINSTRB\(/);assert.match(formattedUpper, /\bLENGTHB\(/);});++test("formats SQL preserving original keyword case when keywordCase is preserve (#11382)", async () => {+ const sql = "select id, name as user_name from users where id = 1 and status in (1, 2) order by id desc limit 10";+ const formatted = await formatSqlText(sql, "generic", { keywordCase: "preserve" });+ assert.match(formatted, /^select\b/);+ assert.match(formatted, /\bas\b/);+ assert.match(formatted, /\bfrom\b/);+ assert.match(formatted, /\bwhere\b/);+ assert.match(formatted, /\band\b/);+ assert.match(formatted, /\bin\b/);+ assert.match(formatted, /\border by\b/);+ assert.match(formatted, /\bdesc\b/);+ assert.match(formatted, /\blimit\b/);+ assert.doesNotMatch(formatted, /\bSELECT\b/);+ assert.doesNotMatch(formatted, /\bFROM\b/);+ assert.doesNotMatch(formatted, /\bWHERE\b/);+});+