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): keep top-level SQL Server BEGIN blocks as one batch

caiyq925-cellafc9374f9073
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlStatementRanges.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlStatementRanges.spec.ts
index e0313d28f2..252e8433fe 100644
--- a/apps/desktop/src/lib/__tests__/sql/sqlStatementRanges.spec.ts
+++ b/apps/desktop/src/lib/__tests__/sql/sqlStatementRanges.spec.ts
@@ -2510,6 +2510,85 @@ WHERE t2.product_name = '12345'
expect(rangeSqlTexts(ranges)).toEqual(["BEGIN TRAN", "UPDATE dbo.T SET x = 1", "COMMIT"]);
});
+ const sqlServerTryCatchBatch = [
+ "SET XACT_ABORT ON;",
+ "",
+ "BEGIN TRY",
+ " BEGIN TRANSACTION;",
+ "",
+ " UPDATE [dbo].[Documents]",
+ " SET [Deleted] = 0",
+ " WHERE [Deleted] = 1;",
+ "",
+ " DECLARE @Updated int = @@ROWCOUNT;",
+ "",
+ " IF EXISTS (SELECT 1 FROM [dbo].[Documents] WHERE [Deleted] = 1)",
+ " THROW 50001, N'Rows with Deleted = 1 still exist.', 1;",
+ "",
+ " COMMIT TRANSACTION;",
+ "",
+ " SELECT N'OK' AS Result, @Updated AS RowsUpdated;",
+ "END TRY",
+ "BEGIN CATCH",
+ " IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;",
+ " THROW;",
+ "END CATCH;",
+ ].join("\n");
+ // The batch range starts at the real `BEGIN TRY` token, so the blank line
+ // and semicolon around the statement are not part of it.
+ const sqlServerTryCatchRange = sqlServerTryCatchBatch.slice(sqlServerTryCatchBatch.indexOf("BEGIN TRY")).replace(/;$/, "");
+
+ // #13051: a top-level BEGIN TRY ... END TRY BEGIN CATCH ... END CATCH script
+ // must execute as one batch — splitting it at the top-level `;` sends
+ // fragments like `BEGIN TRANSACTION` alone and SQL Server rejects them.
+ it("keeps a SQL Server top-level TRY/CATCH script as one batch after the leading statement", () => {
+ const ranges = executableStatementRanges(sqlServerTryCatchBatch, "sqlserver");
+
+ expect(rangeSqlTexts(ranges)).toEqual(["SET XACT_ABORT ON", sqlServerTryCatchRange]);
+ });
+
+ it("keeps the statement after END CATCH as its own SQL Server range", () => {
+ const ranges = executableStatementRanges(`${sqlServerTryCatchBatch}\nSELECT 999;`, "sqlserver");
+
+ expect(rangeSqlTexts(ranges)).toEqual(["SET XACT_ABORT ON", sqlServerTryCatchRange, "SELECT 999"]);
+ });
+
+ it("keeps two consecutive SQL Server TRY/CATCH scripts as two ranges", () => {
+ const second = sqlServerTryCatchBatch.replace(/\[dbo\]\.\[Documents\]/g, "[dbo].[Docs]");
+ const ranges = executableStatementRanges(`${sqlServerTryCatchBatch}\n${second};`, "sqlserver");
+
+ expect(rangeSqlTexts(ranges)).toEqual(["SET XACT_ABORT ON", sqlServerTryCatchRange, "SET XACT_ABORT ON", second.slice(second.indexOf("BEGIN TRY")).replace(/;$/, "")]);
+ });
+
+ it("keeps a SQL Server top-level plain BEGIN/END block whole", () => {
+ const sql = ["BEGIN", " SELECT 1;", " SELECT 2;", "END"].join("\n");
+ const ranges = executableStatementRanges(sql, "sqlserver");
+
+ expect(rangeSqlTexts(ranges)).toEqual([sql]);
+ });
+
+ // A bare `BEGIN` is the first keystroke of every SQL Server block: the merge
+ // reads the word after `BEGIN` to tell a block from `BEGIN TRAN`, and a
+ // missing token must not be treated as one (it crashed the splitter).
+ it("splits a lone SQL Server BEGIN without merging", () => {
+ expect(rangeSqlTexts(splitSqlStatementRanges("BEGIN", "sqlserver"))).toEqual(["BEGIN"]);
+ });
+
+ it("splits a SQL Server BEGIN terminated by a semicolon without merging", () => {
+ expect(rangeSqlTexts(splitSqlStatementRanges("BEGIN;", "sqlserver"))).toEqual(["BEGIN"]);
+ });
+
+ it("splits a SQL Server BEGIN followed by a comment without merging", () => {
+ expect(rangeSqlTexts(splitSqlStatementRanges("BEGIN -- draft block", "sqlserver"))).toEqual(["BEGIN"]);
+ });
+
+ it("ends a SQL Server TRY batch without a CATCH at END TRY", () => {
+ const sql = ["BEGIN TRY", " SELECT 1;", "END TRY", "SELECT 999;"].join("\n");
+ const ranges = executableStatementRanges(sql, "sqlserver");
+
+ expect(rangeSqlTexts(ranges)).toEqual(["BEGIN TRY\n SELECT 1;\nEND TRY", "SELECT 999"]);
+ });
+
// The depth carried across fragments decides where a batch ends: fragments
// after the closing `END` are independent statements, so every following
// statement keeps its own execution icon.
diff --git a/apps/desktop/src/lib/sql/sqlStatementRanges.ts b/apps/desktop/src/lib/sql/sqlStatementRanges.ts
index d07b9ab66f..3193e67314 100644
--- a/apps/desktop/src/lib/sql/sqlStatementRanges.ts
+++ b/apps/desktop/src/lib/sql/sqlStatementRanges.ts
@@ -1025,6 +1025,13 @@ function scanSqlServerControlFlow(sql: string, from: number, to: number, databas
if (word === "END") {
if (next !== undefined && SQLSERVER_NON_BLOCK_END_KEYWORDS.has(next)) continue;
openBlocks -= 1;
+ // `END TRY` must be followed by `BEGIN CATCH` within the same batch
+ // (#13051): when the carried TRY block closes right where a CATCH block
+ // opens, the batch continues instead of ending at the pair — the
+ // following `BEGIN` re-opens the depth in its own branch below.
+ if (initialOpenBlocks > 0 && openBlocks === 0 && next === "TRY" && words[index + 2] === "BEGIN" && words[index + 3] === "CATCH") {
+ continue;
+ }
// Only the closure of the *carried* block is a statement boundary: a
// block opened and closed inside this fragment (`IF ... BEGIN ... END`
// in one piece) belongs to the statement that contains it. A closure
@@ -1033,8 +1040,11 @@ function scanSqlServerControlFlow(sql: string, from: number, to: number, databas
// branch tail carries no semicolon) must still be able to replace it;
// a closure followed by anything else is final.
if (initialOpenBlocks > 0 && openBlocks === 0 && (closedAt === null || wordAfterClose === "ELSE")) {
- closedAt = ends[index];
- wordAfterClose = next ?? "";
+ // `END TRY`/`END CATCH` are two-token closers; the statement boundary
+ // sits after the pair, not between `END` and its keyword.
+ const closesPairedKeyword = next === "TRY" || next === "CATCH";
+ closedAt = closesPairedKeyword ? (ends[index + 1] ?? ends[index]) : ends[index];
+ wordAfterClose = (closesPairedKeyword ? words[index + 2] : next) ?? "";
}
continue;
}
@@ -1046,27 +1056,52 @@ function scanSqlServerControlFlow(sql: string, from: number, to: number, databas
return { openBlocks, closedAt, wordAfterClose, sawBlockBegin, hasControlFlowElse };
}
+/**
+ * True when the first word is `BEGIN` followed by a keyword that opens a real
+ * block — a plain `BEGIN ... END`, `BEGIN TRY`, `BEGIN CATCH` — rather than a
+ * transaction or conversation, which has no matching `END` (#13051).
+ */
+function opensSqlServerTopLevelBlock(sql: string, from: number, databaseType?: DatabaseType, parameterOptions?: SqlParameterOptions): boolean {
+ const firstToken = nextSqlWordToken(sql, from, databaseType, parameterOptions);
+ if (firstToken?.word !== "BEGIN") return false;
+ const secondToken = nextSqlWordToken(sql, firstToken.end, databaseType, parameterOptions);
+ return secondToken != null && !SQLSERVER_NON_BLOCK_BEGIN_KEYWORDS.has(secondToken.word);
+}
+
/**
* True when `statement` is a whole T-SQL control-flow batch: an `IF`/`WHILE`
* whose body is a `BEGIN ... END` block or whose branches are plain statements
- * with an `ELSE`. Such a batch contains no independent statements, so it must
- * stay one execution range instead of being split at the line-oriented
- * `BEGIN`/`EXEC`/`END` tokens.
+ * with an `ELSE`, or a top-level block statement (`BEGIN ... END`, `BEGIN TRY
+ * ... END TRY BEGIN CATCH ... END CATCH`). Such a batch contains no
+ * independent statements, so it must stay one execution range instead of
+ * being split at the line-oriented `BEGIN`/`EXEC`/`END` tokens.
*/
function isSqlServerControlFlowBatch(sql: string, statement: RawStatement, databaseType?: DatabaseType, parameterOptions?: SqlParameterOptions): boolean {
if (databaseType !== "sqlserver") return false;
const firstWord = nextSqlWordToken(sql, statement.from, databaseType, parameterOptions)?.word;
- if (firstWord !== "IF" && firstWord !== "WHILE") return false;
+ const opensTopLevelBlock = opensSqlServerTopLevelBlock(sql, statement.from, databaseType, parameterOptions);
+ if (firstWord !== "IF" && firstWord !== "WHILE" && !opensTopLevelBlock) return false;
const scan = scanSqlServerControlFlow(sql, statement.from, statement.to, databaseType, parameterOptions);
- return scan.hasControlFlowElse || (scan.sawBlockBegin && scan.openBlocks === 0);
+ if (firstWord === "IF" || firstWord === "WHILE") {
+ return scan.hasControlFlowElse || (scan.sawBlockBegin && scan.openBlocks === 0);
+ }
+ // A top-level `BEGIN` block is one batch by itself: keep it whole whether
+ // the block is balanced or still open mid-typing. `BEGIN TRAN[SACTION]` and
+ // friends never reach this branch.
+ return true;
}
/**
* T-SQL does not end a `BEGIN ... END` block at a semicolon, so splitting on
* every top-level `;` cuts `IF ... BEGIN ... ; ... END` batches into fragments
* whose `BEGIN`/`EXEC`/`END` lines then look like independent statements
- * (#9336). Re-join the fragments of such a batch so it stays one range.
+ * (#9336). Top-level block statements — a plain `BEGIN ... END`, `BEGIN TRY
+ * ... END TRY` plus its mandatory `BEGIN CATCH ... END CATCH` — hit the same
+ * split and are re-joined here too (#13051); only `BEGIN` keywords that start
+ * a transaction or conversation (`BEGIN TRAN[SACTION]`, `BEGIN DISTRIBUTED
+ * TRANSACTION`, `BEGIN DIALOG CONVERSATION`) have no matching `END` and stay
+ * split.
*/
function mergeSqlServerControlFlowBatches(sql: string, statements: RawStatement[], databaseType: DatabaseType, parameterOptions?: SqlParameterOptions): RawStatement[] {
const merged: RawStatement[] = [];
@@ -1074,8 +1109,11 @@ function mergeSqlServerControlFlowBatches(sql: string, statements: RawStatement[
while (pending.length > 0) {
const first = pending.shift()!;
- const firstWord = nextSqlWordToken(sql, first.from, databaseType, parameterOptions)?.word;
- if (firstWord !== "IF" && firstWord !== "WHILE") {
+ const firstToken = nextSqlWordToken(sql, first.from, databaseType, parameterOptions);
+ const secondToken = firstToken ? nextSqlWordToken(sql, firstToken.end, databaseType, parameterOptions) : null;
+ const firstWord = firstToken?.word;
+ const opensTopLevelBlock = firstWord === "BEGIN" && secondToken != null && !SQLSERVER_NON_BLOCK_BEGIN_KEYWORDS.has(secondToken.word);
+ if (firstWord !== "IF" && firstWord !== "WHILE" && !opensTopLevelBlock) {
merged.push(first);
continue;
}
diff --git a/crates/dbx-sql-core/src/sql.rs b/crates/dbx-sql-core/src/sql.rs
index 54e3ab9c2b..bf2692773b 100644
--- a/crates/dbx-sql-core/src/sql.rs
+++ b/crates/dbx-sql-core/src/sql.rs
@@ -1832,22 +1832,29 @@ fn find_sqlserver_statement_at_cursor(sql: &str, cursor_pos: usize) -> String {
for (idx, batch) in batches.iter().enumerate() {
if cursor >= batch.start && cursor <= batch.end {
- if starts_with_sqlserver_control_flow_batch(&batch.text)
- || (profile.keeps_sqlserver_module_batch_at_cursor && starts_with_sqlserver_module_ddl(&batch.text))
- {
+ // Module DDL is checked before the block scan: a procedure body is
+ // itself a `BEGIN ... END` block, and the whole `CREATE`/`ALTER`
+ // batch is the execution unit there.
+ if profile.keeps_sqlserver_module_batch_at_cursor && starts_with_sqlserver_module_ddl(&batch.text) {
return batch.text.clone();
}
+ if let Some(statement) =
+ sqlserver_control_flow_statement_at(&batch.text, Some(cursor.saturating_sub(batch.start)))
+ {
+ return statement;
+ }
let relative_cursor = sql[..cursor].encode_utf16().count() - sql[..batch.start].encode_utf16().count();
return find_statement_at_cursor_with_options(&batch.text, relative_cursor, SqlParsingOptions::default());
}
if cursor < batch.start {
if let Some(prev) = idx.checked_sub(1).and_then(|prev_idx| batches.get(prev_idx)) {
- if starts_with_sqlserver_control_flow_batch(&prev.text)
- || (profile.keeps_sqlserver_module_batch_at_cursor && starts_with_sqlserver_module_ddl(&prev.text))
- {
+ if profile.keeps_sqlserver_module_batch_at_cursor && starts_with_sqlserver_module_ddl(&prev.text) {
return prev.text.clone();
}
+ if let Some(statement) = sqlserver_control_flow_statement_at(&prev.text, None) {
+ return statement;
+ }
let relative_cursor = prev.text.encode_utf16().count();
return find_statement_at_cursor_with_options(
&prev.text,
@@ -1862,12 +1869,271 @@ fn find_sqlserver_statement_at_cursor(sql: &str, cursor_pos: usize) -> String {
batches.last().map(|batch| batch.text.clone()).unwrap_or_else(|| sql.trim().to_string())
}
+/// A top-level token of a SQL Server batch: a word or a `;` terminator outside
+/// string literals, quoted identifiers, comments and parentheses. `CASE ... END`
+/// inside a condition or select list therefore never looks like a block.
+struct SqlServerTopLevelToken<'a> {
+ text: &'a str,
+ start: usize,
+ end: usize,
+}
+
+impl SqlServerTopLevelToken<'_> {
+ fn is_word(&self, keyword: &str) -> bool {
+ self.text.eq_ignore_ascii_case(keyword)
+ }
+}
+
+fn sqlserver_top_level_tokens(sql: &str) -> Vec<SqlServerTopLevelToken<'_>> {
+ let bytes = sql.as_bytes();
+ let mut tokens = Vec::new();
+ let mut paren_depth = 0usize;
+ let mut index = 0usize;
+
+ while index < bytes.len() {
+ match bytes[index] {
+ quote @ (b'\'' | b'"') => {
+ index += 1;
+ while index < bytes.len() {
+ if bytes[index] == quote {
+ if bytes.get(index + 1) == Some(&quote) {
+ index += 2;
+ continue;
+ }
+ index += 1;
+ break;
+ }
+ index += 1;
+ }
+ }
+ b'[' => {
+ index += 1;
+ while index < bytes.len() {
+ if bytes[index] == b']' {
+ if bytes.get(index + 1) == Some(&b']') {
+ index += 2;
+ continue;
+ }
+ index += 1;
+ break;
+ }
+ index += 1;
+ }
+ }
+ b'-' if bytes.get(index + 1) == Some(&b'-') => {
+ index += 2;
+ while index < bytes.len() && bytes[index] != b'\n' {
+ index += 1;
+ }
+ }
+ b'/' if bytes.get(index + 1) == Some(&b'*') => {
+ index += 2;
+ while index < bytes.len() && !(bytes[index] == b'*' && bytes.get(index + 1) == Some(&b'/')) {
+ index += 1;
+ }
+ index = (index + 2).min(bytes.len());
+ }
+ b'(' => {
+ paren_depth += 1;
+ index += 1;
+ }
+ b')' => {
+ paren_depth = paren_depth.saturating_sub(1);
+ index += 1;
+ }
+ b';' if paren_depth == 0 => {
+ tokens.push(SqlServerTopLevelToken { text: ";", start: index, end: index + 1 });
+ index += 1;
+ }
+ byte if paren_depth == 0 && (byte == b'_' || byte.is_ascii_alphabetic()) => {
+ let start = index;
+ index += 1;
+ while index < bytes.len() {
+ let next = bytes[index];
+ if next == b'_' || next.is_ascii_alphanumeric() || next == b'$' {
+ index += 1;
+ } else {
+ break;
+ }
+ }
+ tokens.push(SqlServerTopLevelToken { text: &sql[start..index], start, end: index });
+ }
+ _ => index += 1,
+ }
+ }
+
+ tokens
+}
+
+/// `tokens[index]` opens a real block (`BEGIN ... END`, `BEGIN TRY`,
+/// `BEGIN CATCH`) rather than a transaction or conversation, which has no
+/// matching `END`.
+fn sqlserver_begins_block(tokens: &[SqlServerTopLevelToken<'_>], index: usize) -> bool {
+ let Some(next) = tokens.get(index + 1) else {
+ return false;
+ };
+ next.text != ";"
+ && !["TRANSACTION", "TRAN", "DISTRIBUTED", "DIALOG", "CONVERSATION"].iter().any(|keyword| next.is_word(keyword))
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum SqlServerBlockKind {
+ Begin,
+ Case,
+}
+
+struct SqlServerBlockFrame {
+ kind: SqlServerBlockKind,
+ start: usize,
+ /// An `IF`/`WHILE`/`ELSE` appeared since the last top-level `;`, so this
+ /// block is a branch body and its control statement is the execution unit.
+ control_statement: bool,
+}
+
+/// Byte span of a top-level SQL Server `BEGIN ... END` block.
+#[derive(Clone, Copy)]
+struct SqlServerControlFlowBlock {
+ start: usize,
+ end: usize,
+ control_statement: bool,
+}
+
+/// Top-level `BEGIN ... END` blocks of a batch (`BEGIN TRY ... END TRY BEGIN
+/// CATCH ... END CATCH` counts as one). `CASE` frames keep their own `END` from
+/// closing the surrounding block, and an unclosed block runs to the end of the
+/// batch so a block being typed stays whole.
+fn sqlserver_top_level_blocks(sql: &str) -> Vec<SqlServerControlFlowBlock> {
+ let tokens = sqlserver_top_level_tokens(sql);
+ let mut blocks = Vec::new();
+ let mut stack: Vec<SqlServerBlockFrame> = Vec::new();
+ let mut pending_try: Option<SqlServerBlockFrame> = None;
+ let mut in_control_statement = false;
+
+ for (index, token) in tokens.iter().enumerate() {
+ if token.text == ";" {
+ in_control_statement = false;
+ continue;
+ }
+ if token.is_word("IF") || token.is_word("WHILE") || token.is_word("ELSE") {
+ in_control_statement = true;
+ continue;
+ }
+ if token.is_word("BEGIN") {
+ if !sqlserver_begins_block(&tokens, index) {
+ continue;
+ }
+ let frame = match pending_try.take() {
+ Some(frame) if stack.is_empty() => frame,
+ _ => SqlServerBlockFrame {
+ kind: SqlServerBlockKind::Begin,
+ start: token.start,
+ control_statement: in_control_statement,
+ },
+ };
+ stack.push(frame);
+ continue;
+ }
+ if token.is_word("CASE") {
+ stack.push(SqlServerBlockFrame {
+ kind: SqlServerBlockKind::Case,
+ start: token.start,
+ control_statement: in_control_statement,
+ });
+ continue;
+ }
+ if !token.is_word("END") {
+ continue;
+ }
+ let next = tokens.get(index + 1);
+ // `END CONVERSATION`/`END DIALOG` close a conversation, not a block.
+ if next.is_some_and(|next| next.is_word("CONVERSATION") || next.is_word("DIALOG")) {
+ continue;
+ }
+ let Some(frame) = stack.pop() else {
+ continue;
+ };
+ if frame.kind != SqlServerBlockKind::Begin || !stack.is_empty() {
+ continue;
+ }
+ // `END TRY`/`END CATCH` are two-token closers: the span includes the
+ // keyword so the boundary sits after the pair.
+ let end = match next {
+ Some(next) if next.is_word("TRY") || next.is_word("CATCH") => next.end,
+ _ => token.end,
+ };
+ if next.is_some_and(|next| next.is_word("TRY"))
+ && tokens.get(index + 2).is_some_and(|token| token.is_word("BEGIN"))
+ && tokens.get(index + 3).is_some_and(|token| token.is_word("CATCH"))
+ {
+ // `END TRY` immediately followed by `BEGIN CATCH`: both halves are
+ // one batch, so the CATCH block continues the TRY block's span.
+ pending_try = Some(frame);
+ continue;
+ }
+ blocks.push(SqlServerControlFlowBlock { start: frame.start, end, control_statement: frame.control_statement });
+ }
+
+ if let Some(frame) = pending_try {
+ // `END TRY` without its `BEGIN CATCH` yet: keep the half written batch
+ // whole while the user is still typing it.
+ blocks.push(SqlServerControlFlowBlock {
+ start: frame.start,
+ end: sql.len(),
+ control_statement: frame.control_statement,
+ });
+ } else if let Some(frame) = stack.first() {
+ if frame.kind == SqlServerBlockKind::Begin {
+ blocks.push(SqlServerControlFlowBlock {
+ start: frame.start,
+ end: sql.len(),
+ control_statement: frame.control_statement,
+ });
+ }
+ }
+
+ blocks
+}
+
+/// Text of the SQL Server control-flow statement that contains `cursor` (a byte
+/// offset into `sql`), or `None` when the batch is ordinary `;`-separated
+/// statements. `None` for the cursor means it sits after this batch, so any
+/// top-level block keeps the whole batch.
+///
+/// `IF`/`WHILE` batches and top-level `BEGIN ... END` blocks contain no
+/// independent statements: a `;` inside them does not end an execution range
+/// (#9336), and a batch that only *contains* the block, after a leading
+/// `SET XACT_ABORT ON;` for instance, still has to run it as one unit (#13051).
+fn sqlserver_control_flow_statement_at(sql: &str, cursor: Option<usize>) -> Option<String> {
+ if starts_with_sqlserver_control_flow_batch(sql) {
+ return Some(sql.to_string());
+ }
+ let blocks = sqlserver_top_level_blocks(sql);
+ let block = match cursor {
+ Some(cursor) => blocks.iter().find(|block| cursor >= block.start && cursor <= block.end),
+ None => blocks.last(),
+ }?;
+ // A branch body alone is invalid T-SQL, so its whole control statement is
+ // the unit; the whole batch keeps the leading statements too.
+ if block.control_statement || cursor.is_none() {
+ return Some(sql.to_string());
+ }
+ Some(sql[block.start..block.end].to_string())
+}
+
+/// True when the batch starts with a whole T-SQL control-flow statement: an
+/// `IF` batch, or a `BEGIN` block. `BEGIN` keywords that start a transaction or
+/// conversation have no matching `END` and stay split per statement.
fn starts_with_sqlserver_control_flow_batch(sql: &str) -> bool {
- let tokens = first_sql_tokens(sql, 128);
- tokens.first().is_some_and(|token| token.eq_ignore_ascii_case("IF"))
- && tokens.iter().any(|token| token.eq_ignore_ascii_case("ELSE"))
- && tokens.iter().any(|token| token.eq_ignore_ascii_case("BEGIN"))
- && tokens.iter().any(|token| token.eq_ignore_ascii_case("END"))
+ let tokens = sqlserver_top_level_tokens(sql);
+ let Some(first) = tokens.first() else {
+ return false;
+ };
+ if first.is_word("IF") {
+ return tokens.iter().any(|token| token.is_word("ELSE"))
+ && tokens.iter().any(|token| token.is_word("BEGIN"))
+ && tokens.iter().any(|token| token.is_word("END"));
+ }
+ first.is_word("BEGIN") && sqlserver_begins_block(&tokens, 0) && tokens.iter().any(|token| token.is_word("END"))
}
pub fn starts_with_sqlserver_module_ddl(sql: &str) -> bool {
@@ -7091,6 +7357,107 @@ END";
assert_eq!(super::find_statement_at_cursor_for_database(sql, add_cursor, DatabaseType::SqlServer), sql);
}
+ // #13051: a top-level BEGIN TRY ... END TRY BEGIN CATCH ... END CATCH
+ // script is one batch, the same as an IF/ELSE control-flow batch.
+ #[test]
+ fn sqlserver_current_statement_keeps_top_level_try_catch_batch() {
+ let sql = "\
+BEGIN TRY
+ BEGIN TRANSACTION;
+ UPDATE dbo.Documents SET Deleted = 0 WHERE Deleted = 1;
+ COMMIT TRANSACTION;
+END TRY
+BEGIN CATCH
+ IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
+ THROW;
+END CATCH";
+ let update_cursor = sql[..sql.find("UPDATE dbo.Documents").unwrap()].encode_utf16().count();
+ let rollback_cursor = sql[..sql.find("ROLLBACK").unwrap()].encode_utf16().count();
+
+ assert_eq!(super::find_statement_at_cursor_for_database(sql, update_cursor, DatabaseType::SqlServer), sql);
+ assert_eq!(super::find_statement_at_cursor_for_database(sql, rollback_cursor, DatabaseType::SqlServer), sql);
+ }
+
+ #[test]
+ fn sqlserver_current_statement_keeps_top_level_plain_begin_block() {
+ let sql = "BEGIN\n SELECT 1;\n SELECT 2;\nEND";
+ let cursor = sql[..sql.find("SELECT 2").unwrap()].encode_utf16().count();
+
+ assert_eq!(super::find_statement_at_cursor_for_database(sql, cursor, DatabaseType::SqlServer), sql);
+ }
+
+ #[test]
+ fn sqlserver_current_statement_still_splits_begin_transaction_batches() {
+ let sql = "BEGIN TRANSACTION;\nUPDATE dbo.T SET x = 1;\nCOMMIT;";
+ let cursor = sql[..sql.find("UPDATE").unwrap()].encode_utf16().count();
+
+ assert_eq!(
+ super::find_statement_at_cursor_for_database(sql, cursor, DatabaseType::SqlServer),
+ "UPDATE dbo.T SET x = 1"
+ );
+ }
+
+ // #13051: the reported script begins with `SET XACT_ABORT ON;`, so the batch
+ // does not start with the block. The statement at the cursor is still found
+ // by the enclosing top-level BEGIN TRY ... END CATCH block instead of being
+ // `;`-split into a lone `BEGIN TRANSACTION`.
+ #[test]
+ fn sqlserver_current_statement_keeps_try_catch_after_leading_statement() {
+ let sql = "\
+SET XACT_ABORT ON;
+
+BEGIN TRY
+ BEGIN TRANSACTION;
+
+ UPDATE [dbo].[Documents]
+ SET [Deleted] = 0
+ WHERE [Deleted] = 1;
+
+ DECLARE @Updated int = @@ROWCOUNT;
+
+ IF EXISTS (SELECT 1 FROM [dbo].[Documents] WHERE [Deleted] = 1)
+ THROW 50001, N'Rows with Deleted = 1 still exist.', 1;
+
+ COMMIT TRANSACTION;
+
+ SELECT N'OK' AS Result, @Updated AS RowsUpdated;
+END TRY
+BEGIN CATCH
+ IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
+ THROW;
+END CATCH;";
+ let block = sql[sql.find("BEGIN TRY").unwrap()..].trim_end_matches(';');
+ let transaction_cursor = sql[..sql.find("BEGIN TRANSACTION").unwrap()].encode_utf16().count();
+ let update_cursor = sql[..sql.find("UPDATE [dbo].[Documents]").unwrap()].encode_utf16().count();
+ let catch_cursor = sql[..sql.find("BEGIN CATCH").unwrap()].encode_utf16().count();
+ let rollback_cursor = sql[..sql.find("ROLLBACK").unwrap()].encode_utf16().count();
+
+ assert_eq!(
+ super::find_statement_at_cursor_for_database(sql, transaction_cursor, DatabaseType::SqlServer),
+ block
+ );
+ assert_eq!(super::find_statement_at_cursor_for_database(sql, update_cursor, DatabaseType::SqlServer), block);
+ assert_eq!(super::find_statement_at_cursor_for_database(sql, catch_cursor, DatabaseType::SqlServer), block);
+ assert_eq!(super::find_statement_at_cursor_for_database(sql, rollback_cursor, DatabaseType::SqlServer), block);
+ }
+
+ // The block boundary must not be capped by a token budget: a block whose
+ // END is far past the first words still keeps every statement inside it.
+ #[test]
+ fn sqlserver_current_statement_keeps_long_top_level_block() {
+ let body = (0..200).map(|index| format!(" SELECT {index};")).collect::<Vec<_>>().join("\n");
+ let sql = format!("SET XACT_ABORT ON;\nBEGIN\n{body}\nEND");
+ let cursor = sql[..sql.find("SELECT 199").unwrap()].encode_utf16().count();
+ let block = &sql[sql.find("BEGIN").unwrap()..];
+
+ assert_eq!(super::find_statement_at_cursor_for_database(&sql, cursor, DatabaseType::SqlServer), block);
+
+ let plain = format!("BEGIN\n{body}\nEND");
+ let cursor = plain[..plain.find("SELECT 199").unwrap()].encode_utf16().count();
+
+ assert_eq!(super::find_statement_at_cursor_for_database(&plain, cursor, DatabaseType::SqlServer), plain);
+ }
+
#[test]
fn mysql_hash_comments_split_statements_per_issue_428() {
let sql = "SELECT 1; # mysql comment\n\nSELECT 2 # trailing comment";