Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(sql): preserve Oracle package and multiline expression indentation (#13798)

imcman9e0dc5af92a3
diff --git a/apps/desktop/src/lib/__tests__/sql/routineBlockLayout.spec.ts b/apps/desktop/src/lib/__tests__/sql/routineBlockLayout.spec.ts
index e0ffd98c03..caf2f1bd85 100644
--- a/apps/desktop/src/lib/__tests__/sql/routineBlockLayout.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/routineBlockLayout.spec.ts
@@ -97,3 +97,37 @@ describe("routine block layout", () => {
}
});
});
+
+describe("Oracle package layout #13650", () => {
+ const sql =
+ "create or replace package body pkg is procedure p(p_date in date default sysdate) is cursor goods_cur is select * from goods for update; v_count number; v_log varchar2(200); begin v_count := 1; insert into logs(id, log) values(v_count,v_log); end p; procedure q is begin null; end q; end pkg;";
+
+ it.each([false, true])("indents member signatures, declarations and named ends (custom rules=%s)", async (customRulesEnabled) => {
+ const options = { customRulesEnabled };
+ const result = await formatSqlText(sql, "oracle", options);
+ expect(result).toMatch(/^CREATE OR replace PACKAGE BODY pkg IS\n PROCEDURE p .* IS\n/);
+ expect(result).toContain("\n CURSOR goods_cur IS\n SELECT *\n FROM goods\n FOR UPDATE;\n v_count number;");
+ expect(result).toContain("\n BEGIN\n v_count := 1;");
+ expect(result).toContain("\n END p;\n PROCEDURE q IS\n BEGIN\n NULL;\n END q;\nEND pkg;");
+ expect(tokenStream(result, "oracle")).toEqual(tokenStream(sql, "oracle"));
+ expect(await formatSqlText(result, "oracle", options)).toBe(result);
+ });
+
+ it("keeps package initialization outside member bodies", async () => {
+ const source = "create or replace package body pkg is procedure p is begin null; end p; begin p; end pkg;";
+ const result = await formatSqlText(source, "oracle");
+ expect(result).toContain("\n END p;\nBEGIN\n p;\nEND pkg;");
+ expect(tokenStream(result, "oracle")).toEqual(tokenStream(source, "oracle"));
+ expect(await formatSqlText(result, "oracle")).toBe(result);
+ });
+});
+
+describe("Oracle package boundaries #13650", () => {
+ it.each([2, 4] as const)("keeps quoted member ends and nested blocks with indent=%s", async (tabWidth) => {
+ const source = 'create or replace package body "Pkg" is procedure "Run" is v number; begin if v > 0 then begin null; end; else null; end if; end "Run"; end "Pkg";';
+ const result = await formatSqlText(source, "oracle", { tabWidth });
+ expect(result).toContain(`\n${" ".repeat(tabWidth)}END "Run";\nEND "Pkg";`);
+ expect(tokenStream(result, "oracle")).toEqual(tokenStream(source, "oracle"));
+ expect(await formatSqlText(result, "oracle", { tabWidth })).toBe(result);
+ });
+});
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlFormatterRules.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlFormatterRules.spec.ts
index c57f1a8691..c922903031 100644
--- a/apps/desktop/src/lib/__tests__/sql/sqlFormatterRules.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/sqlFormatterRules.spec.ts
@@ -384,3 +384,31 @@ describe("configurable SQL formatting rules (issue #8570)", () => {
expect(result).toMatch(new RegExp(`${name}\\(a,\\n\\s*b\\)`));
});
});
+
+describe("Oracle formatting regressions #13650", () => {
+ const settings = { customRulesEnabled: true, listLayout: "vertical", selectListLayout: "vertical" } as const;
+
+ it.each([false, true])("aligns fields after standalone comments (tabs=%s)", async (useTabs) => {
+ const sql = "select a,\n-- h2.f_get_busnorgshortname(max(t.d_busno)) as busno,\nmax(t.bargainno) as bargainno,max(t.bargainid) as bargainid from t;";
+ const options = { ...settings, useTabs };
+ const result = await formatSqlText(sql, "oracle", options);
+ const lines = result.split("\n");
+ const comment = lines.find((line) => line.includes("-- h2."))!;
+ const field = lines.find((line) => line.includes("max(t.bargainno)"))!;
+ const next = lines.find((line) => line.includes("max(t.bargainid)"))!;
+ expect(comment.trimStart()).toBe("-- h2.f_get_busnorgshortname(max(t.d_busno)) as busno,");
+ expect(field.match(/^\s*/)?.[0]).toBe(next.match(/^\s*/)?.[0]);
+ expect(comment.match(/^\s*/)?.[0]).toBe(next.match(/^\s*/)?.[0]);
+ expect(result).not.toContain("\n\n--");
+ expect(tokenizeSqlSemantic(result, "oracle").map((token) => token.normalized)).toEqual(tokenizeSqlSemantic(sql, "oracle").map((token) => token.normalized));
+ expect(await formatSqlText(result, "oracle", options)).toBe(result);
+ });
+
+ it.each(["oracle", "postgres", "mysql"] as const)("aligns multiline CASE and END with the field in %s", async (dialect) => {
+ const sql = "select a.entryid,case when employeename like '测试%' then employeename else employeename end as result_label from employee_special_tl a;";
+ const result = await formatSqlText(sql, dialect, settings);
+ expect(result).toContain("\n CASE\n WHEN employeename LIKE '测试%' THEN\n employeename\n ELSE\n employeename\n END AS result_label");
+ expect(tokenizeSqlSemantic(result, dialect).map((token) => token.normalized)).toEqual(tokenizeSqlSemantic(sql, dialect).map((token) => token.normalized));
+ expect(await formatSqlText(result, dialect, settings)).toBe(result);
+ });
+});
diff --git a/apps/desktop/src/lib/sql/layout/printer.ts b/apps/desktop/src/lib/sql/layout/printer.ts
index e1ad2f2d09..bbbbcc5d0f 100644
--- a/apps/desktop/src/lib/sql/layout/printer.ts
+++ b/apps/desktop/src/lib/sql/layout/printer.ts
@@ -213,7 +213,9 @@ function printRuleList(writer: Writer, items: AstNode[][], baseColumn: number, c
writer.write(" ".repeat(alignment.aliasColumn - alignment.expression.length));
writer.write(`${alignment.asKeyword} ${alignment.alias}`);
} else {
- printRuleElement(writer, itemNodes, baseColumn, ctx);
+ // An item's nested blocks and leading comments belong to its actual
+ // column, not the enclosing clause's keyword column (#13650).
+ printRuleElement(writer, itemNodes, writer.column, ctx);
}
if (comma === "after" && index < items.length - 1) writer.write(",");
});
@@ -265,7 +267,7 @@ function printRuleElement(writer: Writer, nodes: AstNode[], baseColumn: number,
for (let index = 0; index < nodes.length;) {
const node = nodes[index];
if (node.type === "line_comment" || node.type === "block_comment" || node.type === "disable_comment") {
- if (/[\r\n]/.test(node.precedingWhitespace)) writer.newline(baseColumn);
+ if (/[\r\n]/.test(node.precedingWhitespace) && writer.column !== baseColumn) writer.newline(baseColumn);
else writer.space();
writer.write(node.text);
if (node.type !== "block_comment") writer.markLineComment();
@@ -328,8 +330,9 @@ function printRuleElement(writer: Writer, nodes: AstNode[], baseColumn: number,
writer.space();
writer.write(keywordText(branch.thenKw, ctx));
} else writer.write(keywordText(branch.elseKw, ctx));
- writer.space();
- printRuleElement(writer, branch.result, baseColumn + ctx.options.indentWidth, caseCtx);
+ if (inlineCase) writer.space();
+ else writer.newline(baseColumn + ctx.options.indentWidth * 2);
+ printRuleElement(writer, branch.result, inlineCase ? baseColumn : baseColumn + ctx.options.indentWidth * 2, caseCtx);
printRuleComments(writer, branch.trailingComments, writer.column, ctx);
}
if (inlineCase) writer.space();
diff --git a/apps/desktop/src/lib/sql/layout/rules.ts b/apps/desktop/src/lib/sql/layout/rules.ts
index 5aa33d925e..41402c74b4 100644
--- a/apps/desktop/src/lib/sql/layout/rules.ts
+++ b/apps/desktop/src/lib/sql/layout/rules.ts
@@ -63,7 +63,7 @@ export function hasRuleLineBreak(ctx: SqlLayoutContext, nodes: AstNode[]): boole
case "between_predicate":
return hasRuleLineBreak(ctx, [...node.expr1, ...node.expr2]);
case "case_expression":
- return hasRuleLineBreak({ ...ctx, listKind: "general", logicalContext: "expression" }, [...node.expr, ...node.clauses]);
+ return ruleListLayout({ ...ctx, listKind: "general" }) === "vertical" || hasRuleLineBreak({ ...ctx, listKind: "general", logicalContext: "expression" }, [...node.expr, ...node.clauses]);
case "case_when":
return hasRuleLineBreak(ctx, [...node.condition, ...node.result]);
case "case_else":
diff --git a/apps/desktop/src/lib/sql/routineBlockLayout.ts b/apps/desktop/src/lib/sql/routineBlockLayout.ts
index fbd5e5b202..b7035956fa 100644
--- a/apps/desktop/src/lib/sql/routineBlockLayout.ts
+++ b/apps/desktop/src/lib/sql/routineBlockLayout.ts
@@ -107,6 +107,11 @@ export function indentRoutineBlocks(sql: string, dialectId: string, indentWidth:
let forceBreak = false;
let previousWord = "";
let previousToken: SqlSemanticToken | undefined;
+ const oracle = dialectId === "oracle";
+ const packageBody = oracle && tokens.some((value, index) => value.normalized === "package" && wordAt(tokens, index + 1) === "body");
+ const declarationLevels: number[] = [];
+ let cursorHeader = false;
+ let cursorQuery = false;
const flush = () => {
const trimmed = current.replace(/\s+$/, "");
@@ -128,6 +133,15 @@ export function indentRoutineBlocks(sql: string, dialectId: string, indentWidth:
const nextWord = nextSignificantToken(tokens, index)?.normalized ?? "";
const previous = previousSignificantToken(tokens, index);
const isBlockBegin = word === "begin" && tokenValue.depth === 0 && !NON_BLOCK_BEGIN.has(nextWord);
+ // Package members have their own signatures and declaration sections.
+ // They must not inherit the package header's completed state.
+ const startsMember = packageBody && (word === "procedure" || word === "function") && (previous?.text === ";" || previousWord === "is" || previousWord === "as");
+ if (startsMember) {
+ startLine();
+ headerDone = false;
+ }
+ if (oracle && word === "cursor" && tokenValue.depth === 0 && declarationLevels[declarationLevels.length - 1] === level - 1) cursorHeader = true;
+ if (isBlockBegin && declarationLevels[declarationLevels.length - 1] === level - 1) level = declarationLevels.pop()!;
// A `CASE` expression owns its `THEN`/`ELSE`/`END`; none of them is block syntax.
const closesCase = word === "end" && tokenValue.depth === 0 && caseDepth > 0;
const isBlockEnd = word === "end" && tokenValue.depth === 0 && caseDepth === 0;
@@ -144,16 +158,17 @@ export function indentRoutineBlocks(sql: string, dialectId: string, indentWidth:
// A signature stays on one line even when the printer split it: the clause
// rules have no clause to hang a routine header on, so some dialects emit it
// one token per line.
- const joinsHeader = !headerDone && !isHeaderSeparator && !isBlockBegin;
+ const joinsHeader = (!headerDone && !isHeaderSeparator && !isBlockBegin) || (packageBody && isHeaderSeparator) || cursorHeader;
// `BEGIN TRY` / `END CATCH` name their block with a second keyword, which
// the clause layout treats as its own token and breaks away.
- const joinsBlockSuffix = (previousWord === "begin" && (word === "try" || word === "catch")) || (previousWord === "end" && END_SUFFIXES.has(word));
+ const joinsBlockSuffix = (previousWord === "begin" && (word === "try" || word === "catch")) || (previousWord === "end" && (END_SUFFIXES.has(word) || (oracle && previous?.normalized === "end" && (tokenValue.kind === "word" || tokenValue.kind === "quoted_identifier"))));
+ if (joinsBlockSuffix) forceBreak = false;
- if (forceBreak || (gap.includes("\n") && !joinsHeader && !joinsBlockSuffix)) {
+ if ((forceBreak && !joinsBlockSuffix) || (gap.includes("\n") && !joinsHeader && !joinsBlockSuffix)) {
startLine();
forceBreak = false;
}
- if (isStatementStart || isBlockBegin || isBlockEnd || closesThenBlock || isHeaderSeparator || breaksBeforeElse) startLine();
+ if (isStatementStart || isBlockBegin || isBlockEnd || closesThenBlock || (isHeaderSeparator && !packageBody) || breaksBeforeElse) startLine();
if (isBlockEnd || closesThenBlock) level = Math.max(0, level - 1);
// The gap is empty exactly where the input had no whitespace (`a.b`, `(x)`),
@@ -194,11 +209,26 @@ export function indentRoutineBlocks(sql: string, dialectId: string, indentWidth:
forceBreak = true;
} else if (tokenValue.kind === "punctuation" && tokenValue.text === ";" && tokenValue.depth === 0) {
forceBreak = true;
+ if (cursorQuery) {
+ level = Math.max(0, level - 1);
+ cursorQuery = false;
+ }
} else if (tokenValue.kind === "comment" && (tokenValue.text.startsWith("--") || tokenValue.text.startsWith("#"))) {
forceBreak = true;
} else if (isHeaderSeparator) {
headerDone = true;
forceBreak = true;
+ if (oracle) {
+ declarationLevels.push(level);
+ level += 1;
+ }
+ }
+
+ if (cursorHeader && word === "is") {
+ cursorHeader = false;
+ cursorQuery = true;
+ level += 1;
+ forceBreak = true;
}
if (word) previousWord = word;