From 798029fd6adca67af2c591128c579431d773e95f Mon Sep 17 00:00:00 2001 From: zipg Date: Mon, 28 Sep 2026 21:13:01 +0800 Subject: [PATCH] fix(sql): keep parenthesized UNION ALL branches in formatting --- .../src/lib/__tests__/sql/sqlLayout.spec.ts | 39 ++++++++++++ apps/desktop/src/lib/sql/layout/printer.ts | 63 ++++++++++++++++--- 2 files changed, 92 insertions(+), 10 deletions(-) diff --git a/apps/desktop/src/lib/__tests__/sql/sqlLayout.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlLayout.spec.ts index 1a24fd74c2..f50e4e6e9d 100644 --- a/apps/desktop/src/lib/__tests__/sql/sqlLayout.spec.ts +++ b/apps/desktop/src/lib/__tests__/sql/sqlLayout.spec.ts @@ -229,6 +229,45 @@ describe("sql layout", () => { expect(await format("SELECT a, b FROM t WHERE x = 1;", { indentStyle: "tabularLeft" })).toBe(lines("SELECT a,", " b", "FROM t", "WHERE x = 1;")); }); + it("keeps every branch of a union whose operands are parenthesized (#10472)", async () => { + const sql = lines( + "SELECT a.id, a.starttime, t.name AS taskName", + "FROM ( (SELECT l.id, l.starttime FROM `log_1_4` l WHERE l.taskid = 'abc' ORDER BY l.starttime DESC LIMIT 0, 10)", + "UNION ALL (SELECT l.id, l.starttime FROM `log_2_4` l WHERE l.taskid = 'abc' ORDER BY l.starttime DESC LIMIT 0, 10)", + "UNION ALL (SELECT l.id, l.starttime FROM `log_3_4` l WHERE l.taskid = 'abc' ORDER BY l.starttime DESC LIMIT 0, 10) ) a", + "INNER JOIN task t ON a.taskid = t.id WHERE 1 = 1 ORDER BY a.starttime DESC LIMIT 0, 10", + ); + + // A bare `SELECT` after the operator becomes a sibling clause, but a + // parenthesized branch stays inside the set-operation node. Printing the + // keyword alone deleted every branch after the first one. + expect(await format(sql)).toBe( + lines( + "SELECT a.id, a.starttime, t.name AS taskName", + "FROM ((SELECT l.id, l.starttime FROM `log_1_4` l WHERE l.taskid = 'abc' ORDER BY l.starttime DESC LIMIT 0, 10)", + " UNION ALL", + " (SELECT l.id, l.starttime FROM `log_2_4` l WHERE l.taskid = 'abc' ORDER BY l.starttime DESC LIMIT 0, 10)", + " UNION ALL", + " (SELECT l.id, l.starttime FROM `log_3_4` l WHERE l.taskid = 'abc' ORDER BY l.starttime DESC LIMIT 0, 10)) a", + " INNER JOIN task t ON a.taskid = t.id", + "WHERE 1 = 1", + "ORDER BY a.starttime DESC", + "LIMIT 0, 10", + ), + ); + }); + + it("drops no branch of a long parenthesized union chain (#10472)", async () => { + const branches = Array.from({ length: 12 }, (_, index) => `SELECT l.id, l.payload FROM log_${index + 1}_4 l WHERE l.taskid = 'abc' AND l.ytenant_id = '0000MEJRT61ACN8QOZ0000' ORDER BY l.starttime DESC LIMIT 0, 10`); + const sql = `SELECT a.id FROM ( ${branches.map((branch) => `(${branch})`).join(" UNION ALL ")} ) a`; + + const formatted = await format(sql); + + for (let index = 0; index < branches.length; index += 1) expect(formatted).toContain(`log_${index + 1}_4`); + expect(formatted.match(/UNION ALL/g)).toHaveLength(branches.length - 1); + expect(formatted.match(/0000MEJRT61ACN8QOZ0000/g)).toHaveLength(branches.length); + }); + it("formats a dialect without its own grammar", async () => { expect(await format("select * from t where a = 1 and b = 2;", {}, "generic")).toBe("SELECT * FROM t WHERE a = 1 AND b = 2;"); }); diff --git a/apps/desktop/src/lib/sql/layout/printer.ts b/apps/desktop/src/lib/sql/layout/printer.ts index 2166ca62be..37f19110e0 100644 --- a/apps/desktop/src/lib/sql/layout/printer.ts +++ b/apps/desktop/src/lib/sql/layout/printer.ts @@ -1,4 +1,4 @@ -import type { AstNode, ClauseNode, LimitClauseNode, ParenthesisNode, StatementNode } from "sql-formatter/dist/esm/parser/ast.js"; +import type { AstNode, ClauseNode, LimitClauseNode, ParenthesisNode, SetOperationNode, StatementNode } from "sql-formatter/dist/esm/parser/ast.js"; import { createTableLayout, isCreateTable } from "./ddl"; import { clauseChildContext, collapsedContext, emitText, endsWithLineComment, isBodyNode, isCallParen, isJoinKeyword, isLineComment, isLogicalOperator, isParenthesis, keywordText, limitChildren, renderInline, splitByComma, splitLogicalOperands, Writer, type SqlLayoutContext } from "./primitives"; @@ -108,6 +108,52 @@ function measureParen(writer: Writer, nodes: AstNode[], index: number, ctx: SqlL return renderInline(collapseCtx, nodes.slice(index + 1, end), remaining) ? inner : null; } +/** + * Emits a parenthesis group: inline while it fits — together with the rest of + * the join element it opens — and expanded, re-based on the `(`'s own column, + * when it does not. + */ +function writeParenthesis(writer: Writer, nodes: AstNode[], index: number, ctx: SqlLayoutContext): void { + const node = nodes[index] as ParenthesisNode; + const inner = measureParen(writer, nodes, index, ctx); + if (inner) { + writer.write(`${node.openParen}${inner}${node.closeParen}`); + return; + } + writer.write(node.openParen); + printBlock(writer, node.children, writer.column, ctx); + writer.write(node.closeParen); +} + +/** + * 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. + */ +function printSetOperation(writer: Writer, node: SetOperationNode, baseColumn: number, ctx: SqlLayoutContext): void { + writer.write(keywordText(node.nameKw.text, ctx)); + if (node.children.length === 0) return; + writer.newline(baseColumn); + printSetOperationOperand(writer, node.children, ctx); +} + +/** Emits the operand a set operation carries inside its own node. */ +function printSetOperationOperand(writer: Writer, nodes: AstNode[], ctx: SqlLayoutContext): void { + if (nodes.length === 1 && isParenthesis(nodes[0])) { + 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. + emitText(writer, ctx.renderers.block(nodes).trim(), writer.column, endsWithLineComment(nodes)); +} + /** * Emits a condition that does not fit on one line, breaking it at its top-level * logical operators the way `logicalOperatorNewline` asks: `before` starts each @@ -166,14 +212,7 @@ function printElement(writer: Writer, nodes: AstNode[], baseColumn: number, ctx: if (isParenthesis(node)) { if (!isCallParen(nodes, index, ctx)) writer.space(); - const inner = measureParen(writer, nodes, index, ctx); - if (inner) { - writer.write(`${node.openParen}${inner}${node.closeParen}`); - } else { - writer.write(node.openParen); - printBlock(writer, node.children, writer.column, ctx); - writer.write(node.closeParen); - } + writeParenthesis(writer, nodes, index, ctx); index += 1; continue; } @@ -232,8 +271,12 @@ function printBlock(writer: Writer, nodes: AstNode[], baseColumn: number, ctx: S /** 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); - else if (node.type === "set_operation") writer.write(keywordText(node.nameKw.text, ctx)); + else if (node.type === "set_operation") printSetOperation(writer, node, baseColumn, ctx); else if (node.type === "limit_clause") printLimitClause(writer, node, ctx); + // A parenthesized group that is not a clause (a set operation's branch, a + // statement wrapped in parentheses) is laid out like any other parenthesis so + // its contents stay in this style instead of dropping to the generic renderer. + else if (isParenthesis(node)) writeParenthesis(writer, [node], 0, ctx); else emitText(writer, ctx.renderers.block([node]).trim(), writer.column, isLineComment(node)); }