From 906f5c271c5c401859d24af73d75d9a172b9d55c Mon Sep 17 00:00:00 2001 From: onenewcode Date: Thu, 1 Oct 2026 22:51:20 +0800 Subject: [PATCH] feat(formatter): align select aliases --- .../lib/__tests__/sql/sqlFormatter.spec.ts | 4 +- .../src/lib/__tests__/sql/sqlLayout.spec.ts | 21 ++++++++- apps/desktop/src/lib/sql/layout/printer.ts | 45 ++++++++++++++++++- packages/app-tests/sqlFormatter.test.ts | 10 +++++ 4 files changed, 77 insertions(+), 3 deletions(-) diff --git a/apps/desktop/src/lib/__tests__/sql/sqlFormatter.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlFormatter.spec.ts index 1e7c5509bf..88680a99b2 100644 --- a/apps/desktop/src/lib/__tests__/sql/sqlFormatter.spec.ts +++ b/apps/desktop/src/lib/__tests__/sql/sqlFormatter.spec.ts @@ -464,7 +464,9 @@ LIMIT 100;`); const formatted = await formatSqlForEditing(sql, sqlFormatDialectForDbType("dameng")); - expect(formatted).toContain('JS1.REC_CREATOR AS "recCreator"'); + const aliasLines = formatted.split("\n").filter((line) => line.includes(' AS "recCreator')); + expect(aliasLines).toHaveLength(2); + expect(aliasLines[0]!.indexOf(" AS ")).toBe(aliasLines[1]!.indexOf(" AS ")); // Known and unknown functions alike are written without a space before the // parenthesis. expect(formatted).toContain("DECODE("); diff --git a/apps/desktop/src/lib/__tests__/sql/sqlLayout.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlLayout.spec.ts index 78dc11b5f6..5442bfc2c7 100644 --- a/apps/desktop/src/lib/__tests__/sql/sqlLayout.spec.ts +++ b/apps/desktop/src/lib/__tests__/sql/sqlLayout.spec.ts @@ -188,11 +188,30 @@ describe("sql layout", () => { it("keeps nested and simple CASE expressions compact", async () => { const sql = "SELECT SUM(CASE WHEN a = 1 AND b = 2 THEN 1 ELSE 0 END) AS total, CASE a WHEN 1 THEN CASE b WHEN 2 THEN 'x y' END ELSE 'other' END AS label FROM t;"; - const expected = lines("SELECT SUM(CASE WHEN a = 1 AND b = 2 THEN 1 ELSE 0 END) AS total,", " CASE a WHEN 1 THEN CASE b WHEN 2 THEN 'x y' END ELSE 'other' END AS label", "FROM t;"); + const expected = lines("SELECT SUM(CASE WHEN a = 1 AND b = 2 THEN 1 ELSE 0 END) AS total,", " CASE a WHEN 1 THEN CASE b WHEN 2 THEN 'x y' END ELSE 'other' END AS label", "FROM t;"); expect(await format(sql)).toBe(expected); expect(await format(expected)).toBe(expected); }); + it("falls back to unaligned fields when an aligned alias would overflow the line width", async () => { + // Alignment pads every alias to one column past the widest expression, so + // the short expression's long alias lands exactly at the 120-column width; + // one more character and the whole list keeps the plain one-space layout. + const fitting = `SELECT ${"a".repeat(60)} AS total, ${"b".repeat(30)} AS ${"y".repeat(49)} FROM t;`; + expect(await format(fitting)).toBe(lines(`SELECT ${"a".repeat(60)} AS total,`, ` ${"b".repeat(30)}${" ".repeat(31)}AS ${"y".repeat(49)}`, "FROM t;")); + + const overflowing = `SELECT ${"a".repeat(60)} AS total, ${"b".repeat(30)} AS ${"y".repeat(50)} FROM t;`; + expect(await format(overflowing)).toBe(lines(`SELECT ${"a".repeat(60)} AS total,`, ` ${"b".repeat(30)} AS ${"y".repeat(50)}`, "FROM t;")); + }); + + it("keeps an unaliased field plain while the aliased ones align", async () => { + expect(await format("SELECT a, b AS x, c AS yyy FROM t;")).toBe(lines("SELECT a,", " b AS x,", " c AS yyy", "FROM t;")); + + // The alignment column comes from the aliased expressions only, so the + // bare field stays untouched beside the padded aliases. + expect(await format("SELECT a, bb AS x, c AS yyy FROM t;")).toBe(lines("SELECT a,", " bb AS x,", " c AS yyy", "FROM t;")); + }); + it("preserves comments and width wrapping inside CASE expressions", async () => { const commented = await format(lines("SELECT id, CASE WHEN a = 1 THEN 'one' -- retain this", "ELSE 'other' END AS label FROM t;")); expect(commented).toContain("-- retain this\n"); diff --git a/apps/desktop/src/lib/sql/layout/printer.ts b/apps/desktop/src/lib/sql/layout/printer.ts index 467b7ae523..28fb53eef3 100644 --- a/apps/desktop/src/lib/sql/layout/printer.ts +++ b/apps/desktop/src/lib/sql/layout/printer.ts @@ -63,6 +63,12 @@ function printClause(writer: Writer, clause: ClauseNode, baseColumn: number, ctx const sourceOnOwnLine = clause.nameKw.text.toUpperCase() === "FROM" && !ctx.options.fromClauseSourceOnSameLine; const childCtx = clauseChildContext(ctx, clause); + // Align explicit SELECT aliases to the same column, matching the tabular + // layout used by DBX for CREATE TABLE definitions. Only use this path when + // every aliased item can be rendered as a single line; otherwise the normal + // element printer preserves the formatter's existing wrapping behavior. + const alignedAliases = projection && items.length > 1 ? alignedProjectionItems(items, childCtx, ctx.options.lineWidth - itemColumn) : null; + if (!sourceOnOwnLine && !(projection && items.length > 1) && items.length <= ctx.options.keepElementsOnOneLine) { const flat = renderInline(childCtx, clause.children, ctx.options.lineWidth - writer.column - keyword.length - 1); if (flat) { @@ -79,11 +85,48 @@ function printClause(writer: Writer, clause: ClauseNode, baseColumn: number, ctx } else { writer.newline(itemColumn); } - printElement(writer, item, baseColumn, childCtx); + if (alignedAliases) { + const aligned = alignedAliases[index]; + if (aligned) { + writer.write(aligned.expression); + writer.write(" ".repeat(aligned.aliasColumn - aligned.expression.length)); + writer.write(`${aligned.asKeyword} ${aligned.alias}`); + } else { + printElement(writer, item, baseColumn, childCtx); + } + } else { + printElement(writer, item, baseColumn, childCtx); + } if (index < items.length - 1) writer.write(","); }); } +interface AlignedProjectionItem { + expression: string; + alias: string; + asKeyword: string; + aliasColumn: number; +} + +function alignedProjectionItems(items: AstNode[][], ctx: SqlLayoutContext, lineWidth: number): Array | null { + const parsed = items.map((item) => { + const asIndex = item.findIndex((node) => node.type === "keyword" && node.text.toUpperCase() === "AS"); + if (asIndex <= 0 || asIndex >= item.length - 1) return null; + const asNode = item[asIndex]; + if (asNode?.type !== "keyword") return null; + const 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 }; + }); + + if (!parsed.some(Boolean)) return null; + const expressionWidth = Math.max(...parsed.filter((item): item is AlignedProjectionItem => item !== null).map((item) => item.expression.length)); + const aliasColumn = expressionWidth + 1; + if (parsed.some((item) => item && item.expression.length + (aliasColumn - item.expression.length) + item.asKeyword.length + 1 + item.alias.length > lineWidth)) return null; + return parsed.map((item) => (item ? { ...item, aliasColumn } : null)); +} + /** 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); diff --git a/packages/app-tests/sqlFormatter.test.ts b/packages/app-tests/sqlFormatter.test.ts index da3e85e3cf..18da440376 100644 --- a/packages/app-tests/sqlFormatter.test.ts +++ b/packages/app-tests/sqlFormatter.test.ts @@ -36,6 +36,16 @@ test("puts each SELECT field on its own line even when the statement fits on one assert.equal(await formatSqlText(formatted, "postgres"), formatted); }); +test("aligns explicit SELECT aliases to the widest expression", async () => { + const formatted = await formatSqlText("select bh.id as unique_value, bh.title as title, bh.house_type as type from biz_house bh", "mysql"); + + assert.equal( + formatted, + "SELECT bh.id AS unique_value,\n bh.title AS title,\n bh.house_type AS type\nFROM biz_house bh", + ); + assert.equal(await formatSqlText(formatted, "mysql"), formatted); +}); + test("collapses a single-field statement that fits on one line", async () => { const formatted = await formatSqlText("select id from users where active = 1 order by id", "postgres");