feat(grid): improve production watermark and sql formatting

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-10-01 01:04:20 +08:00
1 parent 2fa5b9298a
commit 7721019218
10 files changed
+525 -335

No files matched your search

+12 -6
View File
@@ -146,14 +146,17 @@ describe("sqlFormatter", () => {
expect(formatted).toBe('CREATE VIEW "TEMP_TEST_VIEW" AS\nSELECT trunc(sysdate) AS dates,\n -- 测试\n (SELECT sysdate FROM dual t) AS nows\nFROM dual;');
});
it("collapses a short OceanBase Oracle view DDL onto one line (issue #7540)", async () => {
// The default style joins a statement that fits the line width onto one
// line, so a short view body comes back with its keywords cased rather
// than spread over several.
it("keeps a short OceanBase Oracle view projection readable (issue #7540)", async () => {
// A view body still keeps each projected field on its own line while its
// surrounding clauses retain the default layout.
const singleLine = `create or replace view "APP"."ACTIVE_USERS" as select ID, NAME from USERS where STATUS = 'ACTIVE'`;
const formatted = await formatSqlForDisplay(singleLine, sqlFormatDialectForDbType("oceanbase-oracle"));
expect(formatted).toBe(`CREATE OR REPLACE VIEW "APP"."ACTIVE_USERS" AS SELECT ID, NAME FROM USERS WHERE STATUS = 'ACTIVE'`);
expect(formatted).toBe(`CREATE OR REPLACE VIEW "APP"."ACTIVE_USERS" AS
SELECT ID,
NAME
FROM USERS
WHERE STATUS = 'ACTIVE'`);
expect(formatted).toContain("'ACTIVE'");
expect(formatted).toContain('"ACTIVE_USERS"');
});
@@ -339,7 +342,10 @@ OR inside$$ as note
// Alias casing is the tokenizer's business, not the keyword casing's: the
// date part stays an identifier, so `keywordCase: "upper"` leaves it alone.
expect(formatted).toBe(`SELECT ${identifier}, t.${identifier} FROM material ${identifier} LIMIT 100;`);
expect(formatted).toBe(`SELECT ${identifier},
t.${identifier}
FROM material ${identifier}
LIMIT 100;`);
expect(formatted).toContain("SELECT");
expect(formatted).toContain("FROM");
expect(formatted).toContain("LIMIT");
+47 -16
View File
@@ -31,10 +31,8 @@ describe("sql layout", () => {
// The subquery's clauses align under the `(` that opens it, and the closing
// `)` stays on the last clause's line.
//
// The subquery's two select elements could be split; the screenshots in
// #827 and #4850 disagree on that point (both are two-element lists, one
// split, one not), so the keeping rule here is the one #4850's rendering
// matches.
// Expanded subqueries use the same one-field-per-line rule as the outer
// SELECT, while their clauses remain aligned under the opening parenthesis.
expect(await format(sql)).toBe(
lines(
"SELECT loc_id,",
@@ -42,7 +40,8 @@ describe("sql layout", () => {
" loc_type,",
" delivery_emp_num,",
" update_time",
"FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY loc_id ORDER BY update_time DESC) AS rn",
"FROM (SELECT *,",
" ROW_NUMBER() OVER (PARTITION BY loc_id ORDER BY update_time DESC) AS rn",
" FROM responsible_area_info",
" WHERE DATE_FORMAT(update_time, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')) t",
"WHERE rn = 1;",
@@ -62,9 +61,12 @@ describe("sql layout", () => {
// subquery expands rather than pushing `ON` onto a line of its own.
expect(await format(sql)).toBe(
lines(
"SELECT HIMMS_XDSBDJ.HIMMS_XDSBDJ_ID, HIMMS_XDSBDJ.YNKE, himms_zwxsysj_sysj(V_HIMMS_XDSBDJ.HIMMS_XDSBDJ_ID) AS SJSYSJ",
"SELECT HIMMS_XDSBDJ.HIMMS_XDSBDJ_ID,",
" HIMMS_XDSBDJ.YNKE,",
" himms_zwxsysj_sysj(V_HIMMS_XDSBDJ.HIMMS_XDSBDJ_ID) AS SJSYSJ",
"FROM HIMMS_XDSBDJ",
" LEFT JOIN (SELECT himms_xdsbdj_id, MAX(SJ) SJ",
" LEFT JOIN (SELECT himms_xdsbdj_id,",
" MAX(SJ) SJ",
" FROM himms_zwxqdjc",
" GROUP BY himms_xdsbdj_id) SUB_QDJC ON HIMMS_XDSBDJ.HIMMS_XDSBDJ_ID = SUB_QDJC.himms_xdsbdj_id",
"WHERE HIMMS_XDSBDJ.tybz IS NULL;",
@@ -121,7 +123,7 @@ describe("sql layout", () => {
// `logicalOperatorNewline: "before"` starts each continuation line with the
// operator, aligned under the condition's first operand like any other
// clause item.
expect(await format(sql)).toBe(lines("SELECT a, b", "FROM t", "WHERE alpha = 1", " AND beta = 2", " AND gamma = 3", " AND delta = 4", " AND epsilon = 5", " AND zeta = 6", " AND eta = 7", " AND theta = 8;"));
expect(await format(sql)).toBe(lines("SELECT a,", " b", "FROM t", "WHERE alpha = 1", " AND beta = 2", " AND gamma = 3", " AND delta = 4", " AND epsilon = 5", " AND zeta = 6", " AND eta = 7", " AND theta = 8;"));
});
it("puts a wrapped condition's operators where the setting asks", async () => {
@@ -130,7 +132,7 @@ describe("sql layout", () => {
// `after` ends the previous line with the operator instead.
expect(await format(sql, { logicalOperatorNewline: "after" })).toContain("WHERE alpha = 1 AND\n beta = 2 AND");
// `none` keeps the condition on the clause's line, however long it gets.
expect(await format(sql, { logicalOperatorNewline: "none" })).toBe(lines("SELECT a, b", "FROM t", "WHERE alpha = 1 AND beta = 2 AND gamma = 3 AND delta = 4 AND epsilon = 5 AND zeta = 6 AND eta = 7 AND theta = 8;"));
expect(await format(sql, { logicalOperatorNewline: "none" })).toBe(lines("SELECT a,", " b", "FROM t", "WHERE alpha = 1 AND beta = 2 AND gamma = 3 AND delta = 4 AND epsilon = 5 AND zeta = 6 AND eta = 7 AND theta = 8;"));
});
it("expands a parenthesized list that does not fit, aligned under its first item", async () => {
@@ -167,13 +169,40 @@ describe("sql layout", () => {
it("collapses each clause independently", async () => {
const sql = "SELECT (SELECT count(*) FROM orders o WHERE o.customer_id = c.id AND o.status = 'paid') AS order_count, c.name FROM customers c;";
// The scalar subquery fits, the select list does not: only the second one
// breaks.
expect(await format(sql)).toBe(lines("SELECT (SELECT count(*) FROM orders o WHERE o.customer_id = c.id AND o.status = 'paid') AS order_count, c.name", "FROM customers c;"));
// The scalar subquery stays compact within its own SELECT field.
expect(await format(sql)).toBe(lines("SELECT (SELECT count(*) FROM orders o WHERE o.customer_id = c.id AND o.status = 'paid') AS order_count,", " c.name", "FROM customers c;"));
});
it("never joins a CASE onto one line", async () => {
expect(await format("SELECT CASE WHEN a = 1 THEN 'one' WHEN a = 2 THEN 'two' ELSE 'other' END AS label FROM t;")).toBe(lines("SELECT CASE", " WHEN a = 1 THEN 'one'", " WHEN a = 2 THEN 'two'", " ELSE 'other'", " END AS label", "FROM t;"));
it("keeps a CASE expression compact (#10783)", async () => {
expect(await format("SELECT CASE WHEN a = 1 THEN 'one' WHEN a = 2 THEN 'two' ELSE 'other' END AS label FROM t;")).toBe("SELECT CASE WHEN a = 1 THEN 'one' WHEN a = 2 THEN 'two' ELSE 'other' END AS label FROM t;");
});
it("puts each SELECT field on its own line even in a short query (#10783)", async () => {
expect(await format("SELECT id, CASE WHEN a = 1 THEN 'one' ELSE 'other' END AS label, coalesce(a, b) FROM t;")).toBe(lines("SELECT id,", " CASE WHEN a = 1 THEN 'one' ELSE 'other' END AS label,", " coalesce(a, b)", "FROM t;"));
});
it("puts fields on separate lines when SELECT has a modifier (#10783)", async () => {
expect(await format("SELECT DISTINCT a, b FROM t;")).toBe(lines("SELECT DISTINCT a,", " b", "FROM t;"));
expect(await format("SELECT DISTINCT ON (key) a, b FROM t;")).toBe(lines("SELECT DISTINCT ON (KEY) a,", " b", "FROM t;"));
});
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;");
expect(await format(sql)).toBe(expected);
expect(await format(expected)).toBe(expected);
});
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");
expect(commented).toContain("ELSE 'other'");
expect(await format(commented)).toBe(commented);
const longCase = await format(`SELECT id, CASE WHEN a = 1 THEN '${"x".repeat(100)}' ELSE 'other' END AS label FROM t;`);
expect(longCase).toContain("CASE\n");
expect(longCase).toContain("END AS label");
expect(await format(longCase)).toBe(longCase);
});
it("gives a set operation its own line", async () => {
@@ -187,7 +216,7 @@ describe("sql layout", () => {
});
it("keeps PostgreSQL casts tight", async () => {
expect(await format("select coalesce(a, b)::text, (x + y)::int from t;", {}, "postgres")).toBe("SELECT coalesce(a, b)::text, (x + y)::int FROM t;");
expect(await format("select coalesce(a, b)::text, (x + y)::int from t;", {}, "postgres")).toBe(lines("SELECT coalesce(a, b)::text,", " (x + y)::int", "FROM t;"));
});
it("keeps the comma of a MySQL LIMIT offset", async () => {
@@ -243,7 +272,9 @@ describe("sql layout", () => {
// keyword alone deleted every branch after the first one.
expect(await format(sql)).toBe(
lines(
"SELECT a.id, a.starttime, t.name AS taskName",
"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)",
+100 -2
View File
@@ -1,4 +1,4 @@
import type { AstNode, ClauseNode, KeywordNode, LimitClauseNode, ParenthesisNode, SetOperationNode } from "sql-formatter/dist/esm/parser/ast.js";
import type { AstNode, CaseExpressionNode, ClauseNode, KeywordNode, LimitClauseNode, ParenthesisNode, SetOperationNode } from "sql-formatter/dist/esm/parser/ast.js";
import type { SqlLayoutRenderers } from "./internals";
/**
@@ -242,6 +242,79 @@ export function keywordText(text: string, ctx: SqlLayoutContext): string {
}
}
/** Whether an AST value contains comments that must retain their own lines. */
function containsComments(value: unknown, seen = new Set<object>()): boolean {
if (!value || typeof value !== "object") return false;
const object = value as object;
if (seen.has(object)) return false;
seen.add(object);
const record = value as Record<string, unknown>;
if (record.type === "line_comment" || record.type === "block_comment" || record.type === "disable_comment") return true;
if (Array.isArray(record.leadingComments) && record.leadingComments.length > 0) return true;
if (Array.isArray(record.trailingComments) && record.trailingComments.length > 0) return true;
return Object.entries(record).some(([key, child]) => key !== "leadingComments" && key !== "trailingComments" && containsComments(child, seen));
}
/**
* Renders a CASE expression as one expression when every branch fits. The
* regular sql-formatter inline renderer deliberately expands CASE branches;
* keeping the expression together makes a CASE projection obey the same
* one-field-per-line rule as every other SELECT item.
*/
function renderCompactCaseExpression(ctx: SqlLayoutContext, node: CaseExpressionNode, width: number): string | null {
if (containsComments(node)) return null;
const parts: string[] = [keywordText(node.caseKw.text, ctx)];
const append = (text: string | null): boolean => {
if (!text) return false;
parts.push(text);
return parts.join(" ").length <= width;
};
if (node.expr.length > 0 && !append(renderInline(collapsedContext(ctx), node.expr, width))) return null;
for (const clause of node.clauses) {
if (clause.type === "case_when") {
if (!append(keywordText(clause.whenKw.text, ctx))) return null;
if (!append(renderInline(collapsedContext(ctx), clause.condition, width))) return null;
if (!append(keywordText(clause.thenKw.text, 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(renderInline(collapsedContext(ctx), clause.result, width))) return null;
}
}
if (!append(keywordText(node.endKw.text, ctx))) return null;
return parts.join(" ");
}
/** Keeps CASE expressions inside functions/parentheses compact as well. */
function compactNestedCases(ctx: SqlLayoutContext, node: AstNode, width: number): AstNode {
switch (node.type) {
case "case_expression": {
const text = renderCompactCaseExpression(ctx, node, width);
// This already-formatted expression is opaque to the upstream renderer;
// the original AST remains available for the multiline fallback.
return text ? ({ type: "literal", text } as AstNode) : node;
}
case "parenthesis":
return { ...node, children: node.children.map((child) => compactNestedCases(ctx, child, width)) };
case "function_call":
case "parameterized_data_type":
case "array_subscript":
return { ...node, parenthesis: compactNestedCases(ctx, node.parenthesis, width) as ParenthesisNode };
case "property_access":
return { ...node, object: compactNestedCases(ctx, node.object, width) };
case "between_predicate":
return { ...node, expr1: node.expr1.map((child) => compactNestedCases(ctx, child, width)), expr2: node.expr2.map((child) => compactNestedCases(ctx, child, width)) };
default:
return node;
}
}
export function splitByComma(children: AstNode[]): AstNode[][] {
const groups: AstNode[][] = [];
let current: AstNode[] = [];
@@ -257,6 +330,11 @@ export function splitByComma(children: AstNode[]): AstNode[][] {
return groups;
}
/** Whether a clause name is SELECT, including modifiers such as DISTINCT or ALL. */
export function isProjectionClauseName(name: string): boolean {
return /^SELECT(?:\s|$)/i.test(name.trim());
}
/**
* Keywords that introduce an object name rather than an expression operand, so
* a parenthesis directly after that name is a definition list, not a call:
@@ -343,7 +421,27 @@ export function renderInline(ctx: SqlLayoutContext, nodes: AstNode[], width: num
if (group) return group;
}
const direct = ctx.renderers.inline(nodes, width);
const caseAt = nodes.findIndex((node) => node.type === "case_expression");
if (caseAt >= 0) {
const prefix = caseAt === 0 ? "" : renderInline(collapsedContext(ctx), nodes.slice(0, caseAt), width);
if (prefix === null) return null;
const caseText = renderCompactCaseExpression(ctx, nodes[caseAt] as CaseExpressionNode, width - prefix.length - (prefix ? 1 : 0));
if (!caseText) return null;
let text = prefix ? `${prefix}${separatorBefore(nodes[caseAt], ctx)}${caseText}` : caseText;
const tailNodes = nodes.slice(caseAt + 1);
if (tailNodes.length > 0) {
const tail = renderInline(collapsedContext(ctx), tailNodes, width - text.length - 1);
if (!tail) return null;
text += `${separatorBefore(tailNodes[0], ctx)}${tail}`;
}
return text.length <= width ? text : null;
}
const direct = ctx.renderers.inline(
nodes.map((node) => compactNestedCases(ctx, node, width)),
width,
);
if (direct) return direct;
const joinsOperators = ctx.joinLogicalOperators ?? ctx.options.logicalOperatorNewline === "none";
+30 -8
View File
@@ -1,6 +1,25 @@
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";
import {
clauseChildContext,
collapsedContext,
emitText,
endsWithLineComment,
isBodyNode,
isCallParen,
isJoinKeyword,
isLineComment,
isLogicalOperator,
isParenthesis,
isProjectionClauseName,
keywordText,
limitChildren,
renderInline,
splitByComma,
splitLogicalOperands,
Writer,
type SqlLayoutContext,
} from "./primitives";
export type { SqlLayoutContext, SqlLayoutOptions } from "./primitives";
@@ -13,9 +32,10 @@ export type { SqlLayoutContext, SqlLayoutOptions } from "./primitives";
* them.
* - A clause's first item stays on the keyword's line, and its remaining items
* align under the first item's column.
* - Short element lists stay collapsed.
* - A statement whose clauses all fit the line width is emitted as a single
* line.
* - SELECT fields each get their own line; other short element lists stay
* collapsed.
* - A statement with a single SELECT field whose clauses all fit the line
* width is emitted as a single line.
* - Join keywords are indented relative to their FROM clause.
*
* Alignment is *column-relative*, not indent-level-relative: a subquery's
@@ -30,19 +50,20 @@ export type { SqlLayoutContext, SqlLayoutOptions } from "./primitives";
/**
* Emits one clause: its keyword, then its items — the first kept on the keyword's
* line and the rest aligned under it — unless the whole list is short enough to
* stay on one line.
* line and the rest aligned under it. SELECT fields always split; other lists
* 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 items = splitByComma(clause.children);
const itemColumn = baseColumn + keyword.length + 1;
const projection = isProjectionClauseName(clause.nameKw.text);
// `FROM` is the one clause DBX lets users push its first source off of, so it
// skips both the collapse and the "element on the keyword's line" rule.
const sourceOnOwnLine = clause.nameKw.text.toUpperCase() === "FROM" && !ctx.options.fromClauseSourceOnSameLine;
const childCtx = clauseChildContext(ctx, clause);
if (!sourceOnOwnLine && items.length <= ctx.options.keepElementsOnOneLine) {
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) {
writer.write(`${keyword} ${flat}`);
@@ -282,7 +303,8 @@ function writeBodyNode(writer: Writer, node: AstNode, baseColumn: number, ctx: S
/** Emits a whole statement, one clause per line unless the statement collapses. */
function printStatement(statement: StatementNode, ctx: SqlLayoutContext): string | null {
const collapsed = renderInline(collapsedContext(ctx), statement.children, ctx.options.lineWidth);
const hasMultiItemProjection = statement.children.some((node) => node.type === "clause" && isProjectionClauseName(node.nameKw.text) && splitByComma(node.children).length > 1);
const collapsed = hasMultiItemProjection ? null : renderInline(collapsedContext(ctx), statement.children, ctx.options.lineWidth);
if (collapsed) return statement.hasSemicolon ? `${collapsed};` : collapsed;
if (isCreateTable(statement)) return createTableLayout(statement, ctx);