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

+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);