feat(formatter): align select aliases

This commit is contained in:
onenewcode authored and GitHub committed 2026-10-01 22:51:20 +08:00
1 parent 35a08e667b
commit 906f5c271c
4 files changed
+77 -3

No files matched your search

+3 -1
View File
@@ -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(");
+20 -1
View File
@@ -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");
+44 -1
View File
@@ -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<AlignedProjectionItem | null> | 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);