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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(sql): keep consecutive case expressions from splitting procedures
Mo-Moore5136322a74f2
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlStatementRanges.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlStatementRanges.spec.tsindex 6e45b8d594..bd4d8f63d2 100644--- a/apps/desktop/src/lib/__tests__/sql/sqlStatementRanges.spec.ts+++ b/apps/desktop/src/lib/__tests__/sql/sqlStatementRanges.spec.ts@@ -909,6 +909,28 @@ END;`;}});+ it("keeps DECODE consecutive CASE expressions inside Oracle-family procedures", () => {+ // Punctuation between `end` and the next `case` must not look like PL/SQL `END CASE`.+ const procedure = `CREATE OR REPLACE PROCEDURE dm.sp_demo IS+BEGIN+ INSERT INTO t(c)+ SELECT decode(+ company_no,+ 'A', (case when x = 1 then 'one' else 'other' end),+ 'B', (case when y = 2 then 'two' else 'other' end)+ ) as business_type_name+ FROM src;+ COMMIT;+EXCEPTION+ WHEN OTHERS THEN+ NULL;+END sp_demo;`;++ for (const database of ["oracle", "oceanbase-oracle"] as const) {+ expect(rangeSqlTexts(splitSqlStatementRanges(procedure, database))).toEqual([procedure]);+ }+ });+it("keeps SAP HANA DO blocks together", () => {const ranges = splitSqlStatementRanges(sapHanaDoBlockFixture, "saphana");diff --git a/apps/desktop/src/lib/sql/sqlStatementRanges.ts b/apps/desktop/src/lib/sql/sqlStatementRanges.tsindex 16e2e9c0fc..1b14d786d5 100644--- a/apps/desktop/src/lib/sql/sqlStatementRanges.ts+++ b/apps/desktop/src/lib/sql/sqlStatementRanges.ts@@ -1967,11 +1967,10 @@ function isMysqlRoutineDdlStartFromWords(words: readonly string[]): boolean {* whole BEGIN/CASE/END nesting from the top on every semicolon while typing).** Semantics mirror the non-incremental token walk exactly: `lastWordToken` plays- * the role of `previousWordToken(tokens, index)` (both reset to null once a- * semicolon is crossed), and `pendingEndAwaitingSuffix` defers resolving an "END"- * token's effect on `blockStack` until the following token arrives, which plays- * the role of `nextWordToken(tokens, index)`'s lookahead without needing to- * revisit already-processed tokens.+ * the role of the previous word token (both reset to null once a semicolon is+ * crossed), and `pendingEndAwaitingSuffix` defers resolving an "END" token's+ * effect on `blockStack` until the following token arrives, which plays the role+ * of next-word lookahead without needing to revisit already-processed tokens.*/interface MysqlRoutineBlockCompleteness {processedTokenCount: number;@@ -2305,17 +2304,17 @@ function sapHanaScriptBlockIsComplete(sql: string): boolean {if (token.kind !== "word") continue;if (token.value === "BEGIN") {- if (previousWordToken(tokens, index) === "END") continue;+ if (previousAdjacentWord(sql, tokens, index) === "END") continue;blockDepth += 1;sawBegin = true;continue;}if (token.value === "CASE") {- if (previousWordToken(tokens, index) !== "END") caseDepth += 1;+ if (previousAdjacentWord(sql, tokens, index) !== "END") caseDepth += 1;continue;}if (token.value === "END") {- const next = nextWordToken(tokens, index);+ const next = nextAdjacentWord(sql, tokens, index);if (SAP_HANA_SCRIPT_BLOCK_TERMINATORS.has(next ?? "")) continue;if (caseDepth > 0) {caseDepth -= 1;@@ -2376,7 +2375,7 @@ function oraclePlSqlBlockEnd(sql: string): number | null {}if (token.value === "BEGIN") {if (tokens[index - 1]?.kind === "word" && tokens[index - 1]?.value === "TRANSACTION") continue;- const previous = previousWordToken(tokens, index);+ const previous = previousAdjacentWord(sql, tokens, index);if (previous === "END") continue;sawBegin = true;if (stack[stack.length - 1] === "DECLARATION" || stack[stack.length - 1] === "ROUTINE") stack[stack.length - 1] = "BLOCK";@@ -2384,18 +2383,18 @@ function oraclePlSqlBlockEnd(sql: string): number | null {continue;}if (token.value === "IF") {- const previous = previousWordToken(tokens, index);+ const previous = previousAdjacentWord(sql, tokens, index);if (previous !== "END" && previous !== "ELSIF") stack.push("IF");continue;}if (token.value === "LOOP") {- if (previousWordToken(tokens, index) !== "END") stack.push("LOOP");+ if (previousAdjacentWord(sql, tokens, index) !== "END") stack.push("LOOP");continue;}if (token.value === "CASE") {- // Both CASE statements and CASE expressions own an END. The CASE token- // following END CASE is ignored below, so it cannot start a new scope.- if (previousWordToken(tokens, index) !== "END") stack.push("CASE");+ // Both CASE statements and CASE expressions own an END. Only a source-adjacent+ // `END CASE` suffix is ignored — `end ), (case` must open a new CASE scope.+ if (previousAdjacentWord(sql, tokens, index) !== "END") stack.push("CASE");continue;}if (token.value === "END") {@@ -2406,7 +2405,7 @@ function oraclePlSqlBlockEnd(sql: string): number | null {stack.pop();continue;}- const next = nextWordToken(tokens, index);+ const next = nextAdjacentWord(sql, tokens, index);const target = ORACLE_PL_SQL_TERMINATORS.has(next ?? "") ? next : top === "OBJECT_BODY" || top === "OBJECT_SPEC" ? top : "BLOCK";if (top === target || (target === "BLOCK" && top === "BLOCK")) stack.pop();continue;@@ -2532,18 +2531,52 @@ function oraclePlSqlTokens(sql: string): OraclePlSqlToken[] {return tokens;}-function previousWordToken(tokens: Array<{ kind: "word" | "semicolon"; value: string }>, index: number): string | null {+/** True when `sql[from..to)` is only whitespace or comments (no punctuation / identifiers). */+function isSourceAdjacentGap(sql: string, from: number, to: number): boolean {+ let i = from;+ while (i < to) {+ const ch = sql[i];+ const next = sql[i + 1] ?? "";+ if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") {+ i += 1;+ continue;+ }+ if (ch === "-" && next === "-") {+ i += 2;+ while (i < to && sql[i] !== "\n") i += 1;+ continue;+ }+ if (ch === "/" && next === "*") {+ i += 2;+ while (i + 1 < to && !(sql[i] === "*" && sql[i + 1] === "/")) i += 1;+ i = Math.min(to, i + 2);+ continue;+ }+ return false;+ }+ return true;+}++/**+ * Previous word only when nothing but whitespace/comments sits between it and `tokens[index]`+ * in the source. Prevents `end ), (case` from looking like PL/SQL `END CASE`.+ */+function previousAdjacentWord(sql: string, tokens: readonly OraclePlSqlToken[], index: number): string | null {for (let i = index - 1; i >= 0; i -= 1) {if (tokens[i].kind === "semicolon") return null;- if (tokens[i].kind === "word") return tokens[i].value;+ if (tokens[i].kind === "word") {+ return isSourceAdjacentGap(sql, tokens[i].to, tokens[index].from) ? tokens[i].value : null;+ }}return null;}-function nextWordToken(tokens: Array<{ kind: "word" | "semicolon"; value: string }>, index: number): string | null {+function nextAdjacentWord(sql: string, tokens: readonly OraclePlSqlToken[], index: number): string | null {for (let i = index + 1; i < tokens.length; i += 1) {if (tokens[i].kind === "semicolon") return null;- if (tokens[i].kind === "word") return tokens[i].value;+ if (tokens[i].kind === "word") {+ return isSourceAdjacentGap(sql, tokens[index].to, tokens[i].from) ? tokens[i].value : null;+ }}return null;}diff --git a/crates/dbx-sql-core/src/sql.rs b/crates/dbx-sql-core/src/sql.rsindex 5086f5f26a..24334aaed9 100644--- a/crates/dbx-sql-core/src/sql.rs+++ b/crates/dbx-sql-core/src/sql.rs@@ -3070,7 +3070,7 @@ impl HanaScriptBlock {for (index, token) in self.tokens.iter().enumerate() {if token.is_word("BEGIN") {- if previous_word_token(&self.tokens, index).is_some_and(|previous| previous == "END") {+ if previous_adjacent_word(&self.tokens, index).is_some_and(|previous| previous == "END") {continue;}block_depth += 1;@@ -3078,13 +3078,13 @@ impl HanaScriptBlock {continue;}if token.is_word("CASE") {- if previous_word_token(&self.tokens, index).is_none_or(|previous| previous != "END") {+ if previous_adjacent_word(&self.tokens, index).is_none_or(|previous| previous != "END") {case_depth += 1;}continue;}if token.is_word("END") {- let next = next_word_token(&self.tokens, index);+ let next = next_adjacent_word(&self.tokens, index);if matches!(next, Some("IF" | "FOR" | "WHILE")) {continue;}@@ -3118,6 +3118,9 @@ enum OraclePlSqlToken {/// the server rejected the truncated statement (#10434).QuotedIdentifier,Semicolon,+ /// Punctuation / operators / numbers. Kept so `end ), (case` is not treated as the+ /// PL/SQL closer `END CASE` (adjacent-word checks must not skip across these).+ Other,}impl OraclePlSqlBlock {@@ -3244,11 +3247,12 @@ impl OraclePlSqlBlock {} else if token.is_word("CASE") {// Both CASE expressions and CASE statements own an END.// The CASE token that follows END CASE is a suffix, not a scope start.- if previous_word_token(&self.tokens, index) != Some("END") {+ // Require source adjacency: `end ), (case` must open a new CASE scope.+ if previous_adjacent_word(&self.tokens, index) != Some("END") {scopes.push(OraclePlSqlScope::Case);}} else if token.is_word("END") {- let next = self.tokens.get(index + 1).and_then(OraclePlSqlToken::as_word);+ let next = next_adjacent_word(&self.tokens, index);if matches!(next, Some("IF" | "LOOP")) {continue;}@@ -3312,11 +3316,11 @@ impl OraclePlSqlBlock {match word {"BEGIN" => scopes.push(OraclePlSqlScope::Block),- "CASE" if previous_word_token(&self.tokens, index) != Some("END") => {+ "CASE" if previous_adjacent_word(&self.tokens, index) != Some("END") => {scopes.push(OraclePlSqlScope::Case);}"END" => {- let next = self.tokens.get(index + 1).and_then(OraclePlSqlToken::as_word);+ let next = next_adjacent_word(&self.tokens, index);if matches!(next, Some("IF" | "LOOP")) {continue;}@@ -3438,7 +3442,8 @@ impl OraclePlSqlToken {Token::Word(word) if word.quote_style.is_none() => Some(Self::Word(word.value.to_ascii_uppercase())),Token::Word(_) => Some(Self::QuotedIdentifier),Token::SemiColon => Some(Self::Semicolon),- _ => None,+ Token::Whitespace(_) | Token::Placeholder(_) => None,+ _ => Some(Self::Other),}}@@ -3449,7 +3454,7 @@ impl OraclePlSqlToken {fn as_word(&self) -> Option<&str> {match self {Self::Word(value) => Some(value),- Self::QuotedIdentifier | Self::Semicolon => None,+ Self::QuotedIdentifier | Self::Semicolon | Self::Other => None,}}@@ -3462,18 +3467,36 @@ impl OraclePlSqlToken {}}-fn previous_word_token(tokens: &[OraclePlSqlToken], index: usize) -> Option<&str> {- tokens[..index].iter().rev().find_map(OraclePlSqlToken::as_word)+/// Word immediately before `index` in the token stream (no skipping punctuation).+/// Used for `END CASE` / `END IF` pairing so `end ), (case` is not treated as `END CASE`.+fn previous_adjacent_word(tokens: &[OraclePlSqlToken], index: usize) -> Option<&str> {+ index.checked_sub(1).and_then(|previous| tokens.get(previous)).and_then(OraclePlSqlToken::as_word)}-fn next_word_token(tokens: &[OraclePlSqlToken], index: usize) -> Option<&str> {- tokens[index + 1..].iter().find_map(OraclePlSqlToken::as_word)+fn next_adjacent_word(tokens: &[OraclePlSqlToken], index: usize) -> Option<&str> {+ tokens.get(index + 1).and_then(OraclePlSqlToken::as_word)+}++fn push_other_token(tokens: &mut Vec<OraclePlSqlToken>) {+ if tokens.last() != Some(&OraclePlSqlToken::Other) {+ tokens.push(OraclePlSqlToken::Other);+ }}fn oracle_plsql_tokens(sql: &str) -> Vec<OraclePlSqlToken> {let dialect = OracleDialect {};if let Ok(tokens) = Tokenizer::new(&dialect, sql).tokenize() {- return tokens.into_iter().filter_map(OraclePlSqlToken::from_sqlparser_token).collect();+ let mut out = Vec::new();+ for token in tokens {+ if let Some(mapped) = OraclePlSqlToken::from_sqlparser_token(token) {+ if mapped == OraclePlSqlToken::Other {+ push_other_token(&mut out);+ } else {+ out.push(mapped);+ }+ }+ }+ return out;}oracle_plsql_tokens_fallback(sql)@@ -3520,6 +3543,8 @@ fn oracle_plsql_tokens_fallback(sql: &str) -> Vec<OraclePlSqlToken> {}}}+ // String literals separate keywords the same way punctuation does.+ push_other_token(&mut tokens);continue;}@@ -3550,7 +3575,10 @@ fn oracle_plsql_tokens_fallback(sql: &str) -> Vec<OraclePlSqlToken> {}}tokens.push(OraclePlSqlToken::word(token));+ continue;}++ push_other_token(&mut tokens);}tokens@@ -6429,6 +6457,31 @@ SELECT 1;";}}+ #[test]+ fn oracle_like_split_keeps_decode_consecutive_case_expressions_inside_procedure() {+ // Punctuation between `end` and the next `case` must not look like PL/SQL `END CASE`,+ // or CREATE PROCEDURE is truncated at the INSERT terminator (OceanBase OBE-00900 near insert).+ let procedure = "\+CREATE OR REPLACE PROCEDURE dm.sp_demo IS+BEGIN+ INSERT INTO t(c)+ SELECT decode(+ company_no,+ 'A', (case when x = 1 then 'one' else 'other' end),+ 'B', (case when y = 2 then 'two' else 'other' end)+ ) as business_type_name+ FROM src;+ COMMIT;+EXCEPTION+ WHEN OTHERS THEN+ NULL;+END sp_demo;";++ for database in [DatabaseType::Oracle, DatabaseType::OceanbaseOracle] {+ assert_eq!(split_sql_statements_for_database(procedure, database), vec![procedure.to_string()]);+ }+ }+#[test]fn oracle_like_split_ignores_end_tokens_inside_q_quoted_strings() {let sql = "\