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(sqlserver): keep T-SQL control-flow batches whole on generic JDBC
caiyq925-cell6ea903e33904
diff --git a/crates/dbx-core/src/data/sql_file_import.rs b/crates/dbx-core/src/data/sql_file_import.rsindex dfcd12b919..136f430d27 100644--- a/crates/dbx-core/src/data/sql_file_import.rs+++ b/crates/dbx-core/src/data/sql_file_import.rs@@ -2497,7 +2497,15 @@ async fn sql_file_import_target(state: &AppState, connection_id: &str, database:} else {SqlCompatibilityMode::NotApplicable};- Some(SqlFileImportTarget { db_type: config.db_type, driver_profile: config.driver_profile, compatibility_mode })+ Some(SqlFileImportTarget {+ // Split with the connection's statement-splitting dialect, not its+ // routing `db_type`: a JDBC SQL Server connection keeps control-flow+ // batches whole (#13514), a JDBC Oracle connection keeps PL/SQL units+ // whole. The rest of the import still routes on the raw `db_type`.+ db_type: crate::query::statement_split_database_type(&config),+ driver_profile: config.driver_profile,+ compatibility_mode,+ })}#[derive(Debug, Clone, Copy, PartialEq, Eq)]diff --git a/crates/dbx-core/src/query/mod.rs b/crates/dbx-core/src/query/mod.rsindex 0b4978906d..f56aa24de9 100644--- a/crates/dbx-core/src/query/mod.rs+++ b/crates/dbx-core/src/query/mod.rs@@ -886,9 +886,14 @@ async fn connection_statement_split_database_type(state: &AppState, connection_i/// A generic JDBC connection to Oracle runs PL/SQL through the JDBC plugin, so its/// script is split with the Oracle rules. The plain `Jdbc` profile would cut every/// routine body at its first inner semicolon and replace the object with the fragment.-fn statement_split_database_type(config: &ConnectionConfig) -> DatabaseType {+/// A JDBC connection to SQL Server runs T-SQL through the JDBC plugin, so its script+/// keeps top-level control-flow batches whole (#13514). Both mappings only change+/// statement-splitting semantics; the connection's `db_type` still routes the query.+pub fn statement_split_database_type(config: &ConnectionConfig) -> DatabaseType {if crate::schema::is_oracle_external_driver_config(config) {DatabaseType::Oracle+ } else if crate::schema::is_sqlserver_external_driver_config(config) {+ DatabaseType::SqlServer} else {config.db_type}@@ -6799,6 +6804,10 @@ pub async fn execute_in_manual_transaction_with_options(let db_type = connection_database_type(state, &connection_id).await;let compatibility_mode = connection_sql_compatibility_mode(state, &pool_key, db_type).await;+ // Split with the connection's statement-splitting dialect, not its routing+ // `db_type`: a JDBC SQL Server connection keeps control-flow batches whole+ // (#13514) while still executing through the generic external-driver path.+ let split_db_type = connection_statement_split_database_type(state, &connection_id).await;let statements = if let Some(bound) = options.bound_statements.as_ref() {if db_type != Some(DatabaseType::OceanbaseOracle) {return Err("Bound BLOB saves are only supported for OceanBase Oracle.".into());@@ -6810,12 +6819,12 @@ pub async fn execute_in_manual_transaction_with_options(dbx_types::types::validate_blob_bound_statements(&previews, bound)?;previews} else {- db_type.map_or_else(+ split_db_type.map_or_else(|| split_sql_statements(sql),- |db_type| {+ |split_db_type| {crate::sql::split_sql_statements_for_database_with_compatibility(sql,- db_type,+ split_db_type,compatibility_mode.as_deref(),)},@@ -10889,6 +10898,46 @@ for line in sys.stdin:assert_eq!(statement_split_database_type(&other), DatabaseType::Jdbc);}+ // #13514: a generic JDBC connection to SQL Server splits with the SQL Server+ // rules, so the reported TRY/CATCH script keeps its batch whole while the+ // leading `SET` stays its own statement. Other JDBC configs stay on the+ // plain `Jdbc` profile.+ #[test]+ fn jdbc_sqlserver_execution_plan_keeps_control_flow_batches_whole() {+ let mut sqlserver = test_connection_config(DatabaseType::Jdbc);+ sqlserver.connection_string = Some("jdbc:sqlserver://127.0.0.1:1433;databaseName=demo".to_string());+ assert_eq!(statement_split_database_type(&sqlserver), DatabaseType::SqlServer);++ let sql = "SET XACT_ABORT ON;\n\+ BEGIN TRY\n\+ BEGIN TRANSACTION;\n\+ UPDATE dbo.Documents SET Deleted = 0 WHERE Deleted = 1;\n\+ COMMIT TRANSACTION;\n\+ END TRY\n\+ BEGIN CATCH\n\+ IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;\n\+ THROW;\n\+ END CATCH;";+ let block = &sql[sql.find("BEGIN TRY").unwrap()..];++ let plan = query_execution_plan(sql, Some(statement_split_database_type(&sqlserver)), false);+ assert_eq!(plan.statements, vec!["SET XACT_ABORT ON".to_string(), block.to_string()]);++ let mut other = test_connection_config(DatabaseType::Jdbc);+ other.connection_string = Some("jdbc:h2:mem:test".to_string());+ let plan = query_execution_plan("SELECT 1; SELECT 2;", Some(statement_split_database_type(&other)), false);+ assert_eq!(plan.statements, vec!["SELECT 1", "SELECT 2"]);++ let mut postgres = test_connection_config(DatabaseType::Jdbc);+ postgres.connection_string = Some("jdbc:postgresql://127.0.0.1:5432/demo".to_string());+ assert_eq!(statement_split_database_type(&postgres), DatabaseType::Jdbc);++ let mut jtds = test_connection_config(DatabaseType::Jdbc);+ jtds.connection_string = Some("jdbc:jtds:sqlserver://127.0.0.1:1433/demo".to_string());+ jtds.jdbc_driver_class = Some("net.sourceforge.jtds.jdbc.Driver".to_string());+ assert_eq!(statement_split_database_type(&jtds), DatabaseType::SqlServer);+ }+#[test]fn ordinary_agent_execution_plan_still_splits_semicolon_statements() {let plan = query_execution_plan("SELECT 1; SELECT 2;", Some(DatabaseType::Dameng), false);diff --git a/crates/dbx-core/src/schema/mod.rs b/crates/dbx-core/src/schema/mod.rsindex 3f1d87b62b..4e727b0513 100644--- a/crates/dbx-core/src/schema/mod.rs+++ b/crates/dbx-core/src/schema/mod.rs@@ -3292,19 +3292,20 @@ mod tests {filter_table_infos, filter_visible_schema_names, finalize_object_source, gaussdb_m_indexes_sql,gaussdb_m_view_object_source_sql, gbase8a_object_statistics_sql, is_agent_postgres_metadata_fallback_config,is_mysql_external_driver_config, is_oracle_external_driver_config, is_retryable_metadata_error,- metadata_error_action, metadata_name_or_comment_matches, mysql_auto_increment_from_query_result,- mysql_auto_increment_metadata_sql, mysql_database_list_timeout, mysql_external_driver_ddl_from_query_result,- mysql_external_driver_ddl_sql, mysql_object_source_ddl_column_index, mysql_object_source_sql,- mysql_table_list_source_for_config, mysql_table_metadata_catalog, normalize_information_schema_table_type,- oracle_columns_from_query_result, oracle_columns_sql, oracle_columns_sql_for_resolved_owner,- oracle_completion_synonyms_sql, oracle_current_schema_from_query_result,- oracle_object_statistics_dba_segments_sql, oracle_object_statistics_from_query_result,- oracle_object_statistics_rows_only_sql, oracle_object_statistics_sql,- oracle_object_statistics_user_segments_sql, oracle_synonym_target_from_query_result, oracle_synonym_target_sql,- oracle_table_comment_sql, oracle_table_comments_sql, presto_like_columns_from_query_result,- presto_like_information_schema_columns_sql, presto_like_information_schema_tables_sql,- presto_like_tables_from_query_result, reference_key_columns_from_indexes, reference_keys_from_indexes,- replace_metadata_runtime, should_append_oracle_style_comment_ddl, should_query_oracle_columns_via_sql_first,+ is_sqlserver_external_driver_config, metadata_error_action, metadata_name_or_comment_matches,+ mysql_auto_increment_from_query_result, mysql_auto_increment_metadata_sql, mysql_database_list_timeout,+ mysql_external_driver_ddl_from_query_result, mysql_external_driver_ddl_sql,+ mysql_object_source_ddl_column_index, mysql_object_source_sql, mysql_table_list_source_for_config,+ mysql_table_metadata_catalog, normalize_information_schema_table_type, oracle_columns_from_query_result,+ oracle_columns_sql, oracle_columns_sql_for_resolved_owner, oracle_completion_synonyms_sql,+ oracle_current_schema_from_query_result, oracle_object_statistics_dba_segments_sql,+ oracle_object_statistics_from_query_result, oracle_object_statistics_rows_only_sql,+ oracle_object_statistics_sql, oracle_object_statistics_user_segments_sql,+ oracle_synonym_target_from_query_result, oracle_synonym_target_sql, oracle_table_comment_sql,+ oracle_table_comments_sql, presto_like_columns_from_query_result, presto_like_information_schema_columns_sql,+ presto_like_information_schema_tables_sql, presto_like_tables_from_query_result,+ reference_key_columns_from_indexes, reference_keys_from_indexes, replace_metadata_runtime,+ should_append_oracle_style_comment_ddl, should_query_oracle_columns_via_sql_first,single_table_comment_from_query_result, table_comments_from_query_result, table_name_filter_matches,tdengine_table_comment_like_pattern, tdengine_table_comment_sql, tdengine_table_comments_sql,uses_mongodb_agent_collection_listing, visible_schema_filter, ExternalDriverStatisticsDialect,@@ -3879,6 +3880,35 @@ doneassert!(!is_oracle_external_driver_config(&config));}+ #[test]+ fn sqlserver_external_driver_detection_only_accepts_standard_jdbc_signals() {+ let mut config = test_connection_config(DatabaseType::Jdbc);+ config.connection_string = Some(" jdbc:sqlserver://127.0.0.1:1433;databaseName=demo ".to_string());+ assert!(is_sqlserver_external_driver_config(&config));++ config.connection_string = Some("jdbc:jtds:sqlserver://127.0.0.1:1433/demo".to_string());+ assert!(is_sqlserver_external_driver_config(&config));++ config.connection_string = Some("jdbc:jtds:sqlserver://127.0.0.1:1433/demo".to_string());+ config.jdbc_driver_class = Some("com.mysql.cj.jdbc.Driver".to_string());+ assert!(!is_sqlserver_external_driver_config(&config));++ config.connection_string = None;+ config.jdbc_driver_class = Some(" com.microsoft.sqlserver.jdbc.SQLServerDriver ".to_string());+ assert!(is_sqlserver_external_driver_config(&config));++ config.jdbc_driver_class = Some("net.sourceforge.jtds.jdbc.Driver".to_string());+ assert!(is_sqlserver_external_driver_config(&config));++ config.connection_string = Some("jdbc:postgresql://127.0.0.1:5432/demo".to_string());+ config.jdbc_driver_class = Some("com.microsoft.sqlserver.jdbc.SQLServerDriver".to_string());+ assert!(!is_sqlserver_external_driver_config(&config));++ config.db_type = DatabaseType::SqlServer;+ config.connection_string = None;+ assert!(!is_sqlserver_external_driver_config(&config));+ }+#[test]fn oracle_completion_synonyms_sql_matches_native_agent_semantics() {let sql = oracle_completion_synonyms_sql(@@ -10783,6 +10813,37 @@ pub(crate) fn is_oracle_external_driver_config(config: &ConnectionConfig) -> boo}}+/// SQL Server over a generic JDBC connection runs T-SQL through the JDBC+/// plugin, so its scripts split with the SQL Server statement rules (#13514).+/// The plain `Jdbc` profile would cut a `BEGIN TRY ... END CATCH` batch at+/// every inner semicolon. The `jdbc:jtds:sqlserver:` prefix and the jTDS driver+/// cover the legacy open-source TDS driver alongside the Microsoft one.+pub(crate) fn is_sqlserver_external_driver_config(config: &ConnectionConfig) -> bool {+ if config.db_type != DatabaseType::Jdbc {+ return false;+ }++ let connection_string = config.connection_string.as_deref().map(str::trim).filter(|value| !value.is_empty());+ let driver_class = config.jdbc_driver_class.as_deref().map(str::trim).filter(|value| !value.is_empty());+ let sqlserver_url = connection_string.map(|value| {+ value.to_ascii_lowercase().starts_with("jdbc:sqlserver:")+ || value.to_ascii_lowercase().starts_with("jdbc:jtds:sqlserver:")+ });+ let sqlserver_driver = driver_class.map(|value| {+ matches!(+ value.to_ascii_lowercase().as_str(),+ "com.microsoft.sqlserver.jdbc.sqlserverdriver" | "net.sourceforge.jtds.jdbc.driver"+ )+ });++ match (sqlserver_url, sqlserver_driver) {+ (Some(url_matches), Some(driver_matches)) => url_matches && driver_matches,+ (Some(url_matches), None) => url_matches,+ (None, Some(driver_matches)) => driver_matches,+ (None, None) => false,+ }+}+fn external_driver_uses_mysql_ddl(config: &ConnectionConfig) -> bool {is_mysql_external_driver_config(config) || gaussdb_uses_m_jdbc_driver(config)}diff --git a/crates/dbx-mcp/src/backend.rs b/crates/dbx-mcp/src/backend.rsindex bc500f89ab..5e44923533 100644--- a/crates/dbx-mcp/src/backend.rs+++ b/crates/dbx-mcp/src/backend.rs@@ -1403,7 +1403,15 @@ impl DbxBackend for LocalBackend {) -> dbx_core::sql::SqlExecutionPlan {let is_sqlserver_agent =dbx_core::query::connection_pool_is_sqlserver_agent(self.state.as_ref(), &connection.id, database).await;- dbx_core::query::query_execution_plan(sql, Some(connection.db_type), is_sqlserver_agent)+ // Split with the connection's statement-splitting dialect, not its+ // routing `db_type`: a JDBC SQL Server connection keeps control-flow+ // batches whole (#13514), a JDBC Oracle connection keeps PL/SQL units+ // whole, matching the core's own execution plan.+ dbx_core::query::query_execution_plan(+ sql,+ Some(dbx_core::query::statement_split_database_type(connection)),+ is_sqlserver_agent,+ )}async fn add_connection_for_mcp(&self, config: ConnectionConfig) -> Result<ConnectionConfig, String> {diff --git a/crates/dbx-sql-core/src/sql.rs b/crates/dbx-sql-core/src/sql.rsindex 316d9fe40d..9d1b72c278 100644--- a/crates/dbx-sql-core/src/sql.rs+++ b/crates/dbx-sql-core/src/sql.rs@@ -211,6 +211,13 @@ struct SqlDialectProfile {supports_firebird_routine_blocks: bool,supports_go_batch_separator: bool,keeps_sqlserver_module_batch_at_cursor: bool,+ /// Whether a top-level T-SQL control-flow batch (`IF`/`WHILE` with a block+ /// body or `ELSE`, or a top-level `BEGIN ... END` block) stays whole in the+ /// `;`-statement splitter. The SQL Server profile needs it because T-SQL+ /// does not end a block at a semicolon; the generic JDBC profile must not+ /// lose it, or the backend re-splits the TRY/CATCH batches the editor+ /// already kept together (#13514).+ keeps_sqlserver_control_flow_batches: bool,preserves_tdsql_leading_directives: bool,requires_whitespace_after_line_comment_dashes: bool,supports_psql_control_commands: bool,@@ -236,6 +243,7 @@ impl Default for SqlDialectProfile {supports_firebird_routine_blocks: false,supports_go_batch_separator: false,keeps_sqlserver_module_batch_at_cursor: false,+ keeps_sqlserver_control_flow_batches: false,preserves_tdsql_leading_directives: false,requires_whitespace_after_line_comment_dashes: false,supports_psql_control_commands: false,@@ -397,6 +405,7 @@ impl SqlDialectProfile {Self {supports_go_batch_separator: true,keeps_sqlserver_module_batch_at_cursor: true,+ keeps_sqlserver_control_flow_batches: true,supports_nested_block_comments: true,..Self::default()}@@ -978,6 +987,60 @@ impl SqlStatementSplitter {if firebird_routine_block_is_complete(&self.buffer) {self.push_current_statement(&mut statements);}+ } else if keeps_sqlserver_control_flow_batch(self.options, &self.buffer) {+ // T-SQL does not end a control-flow batch at a semicolon+ // (#9336, #13051, #13514): the inner `;` stays in the+ // batch and the statement ends after the block's final+ // `END [TRY]`.+ self.buffer.push(ch);+ if sqlserver_control_flow_batch_is_complete(&self.buffer) {+ // A final `END` without its own `;` shares the+ // fragment with the next statement; the boundary+ // sits right after that `END` instead (TS parity).+ // An `END` directly followed by this `;` keeps the+ // historical shape: the batch ends here with its+ // terminating semicolon.+ let body_end = self.buffer.len() - ch.len_utf8();+ let body = self.buffer[..body_end].to_string();+ let mut boundaries = Vec::new();+ let mut cursor = 0usize;+ while let Some(relative) = sqlserver_control_flow_batch_boundary(&body[cursor..]) {+ if cursor + relative >= body.len() {+ break;+ }+ cursor += relative;+ boundaries.push(cursor);+ }+ if boundaries.is_empty() {+ self.push_current_statement(&mut statements);+ } else {+ let mut piece_from = 0usize;+ for boundary_end in &boundaries {+ self.buffer.clear();+ self.buffer.push_str(&body[piece_from..*boundary_end]);+ self.push_current_statement(&mut statements);+ piece_from = *boundary_end;+ }+ let trailing = &body[piece_from..];+ if !trailing.trim().is_empty() {+ self.buffer.clear();+ self.buffer.push_str(trailing);+ if keeps_sqlserver_control_flow_batch(self.options, trailing) {+ // A new batch in the remainder keeps the+ // terminating `;` when complete and this+ // `;` when it is still mid-typing.+ self.buffer.push(ch);+ if sqlserver_control_flow_batch_is_complete(trailing) {+ self.push_current_statement(&mut statements);+ }+ } else {+ self.push_current_statement(&mut statements);+ }+ } else {+ self.buffer.clear();+ }+ }+ }} else {self.push_current_statement(&mut statements);}@@ -1667,6 +1730,66 @@ fn split_sql_statement_ranges_with_options(sql: &str, options: SqlParsingOptionscontinue;}push_statement_range(&mut ranges, sql, start, i + ch.len_utf8(), options);+ } else if keeps_sqlserver_control_flow_batch(options, &sql[start..i]) {+ // T-SQL does not end a control-flow batch at a semicolon+ // (#9336, #13051): the inner `;` stays in the batch and+ // the statement ends at the block's final `END [TRY]`.+ if !sqlserver_control_flow_batch_is_complete(&sql[start..i + ch.len_utf8()]) {+ i += ch.len_utf8();+ continue;+ }+ // A final `END` without its own `;` shares the fragment+ // with the next statement; the boundary sits right after+ // that `END` instead (TS parity with+ // `sqlStatementRanges.ts`). An `END` directly followed+ // by this `;` keeps the historical range shape.+ let body = &sql[start..i];+ let mut boundaries = Vec::new();+ let mut cursor = 0usize;+ while let Some(relative) = sqlserver_control_flow_batch_boundary(&body[cursor..]) {+ if cursor + relative >= body.len() {+ break;+ }+ cursor += relative;+ boundaries.push(cursor);+ }+ if boundaries.is_empty() {+ push_statement_range(&mut ranges, sql, start, i + ch.len_utf8(), options);+ } else {+ let mut piece_from = 0usize;+ for boundary_end in &boundaries {+ push_statement_range(+ &mut ranges,+ sql,+ start + piece_from,+ start + boundary_end,+ options,+ );+ piece_from = *boundary_end;+ }+ let trailing = &body[piece_from..];+ if !trailing.trim().is_empty() {+ if keeps_sqlserver_control_flow_batch(options, trailing) {+ if sqlserver_control_flow_batch_is_complete(trailing) {+ push_statement_range(+ &mut ranges,+ sql,+ start + piece_from,+ i + ch.len_utf8(),+ options,+ );+ } else {+ // The remainder opens a new batch that is+ // still mid-typing: this `;` stays inside it.+ start += piece_from;+ i += ch.len_utf8();+ continue;+ }+ } else {+ push_statement_range(&mut ranges, sql, start + piece_from, i, options);+ }+ }+ }} else {push_statement_range(&mut ranges, sql, start, i, options);}@@ -3409,6 +3532,174 @@ fn keeps_oracle_style_block_together(options: SqlParsingOptions, statement_head:options.profile.supports_oracle_style_routine_bodies && starts_with_oracle_style_routine_body(statement_head)}+/// Whether the statement opened so far is a T-SQL control-flow batch that the+/// `;`-statement splitter must keep whole: an `IF`/`WHILE` batch (its block+/// body keeps the splitter going; a branchless one is a single statement+/// anyway), or a top-level `BEGIN` that opens a real block (`BEGIN TRY ... END+/// TRY BEGIN CATCH ... END CATCH` counts as one). `BEGIN TRAN[SACTION]` and+/// friends have no matching `END` and stay split per statement. Only meaningful+/// when the profile keeps such batches (`keeps_sqlserver_control_flow_batches`).+fn keeps_sqlserver_control_flow_batch(options: SqlParsingOptions, statement_head: &str) -> bool {+ if !options.profile.keeps_sqlserver_control_flow_batches {+ return false;+ }+ let tokens = sqlserver_top_level_tokens(statement_head);+ let Some(first) = tokens.first() else {+ return false;+ };+ if first.is_word("IF") || first.is_word("WHILE") {+ return true;+ }+ first.is_word("BEGIN") && sqlserver_begins_block(&tokens, 0)+}++/// Top-level `BEGIN`/`CASE` blocks the T-SQL statement has left open at its+/// end. `END TRY` immediately followed by `BEGIN CATCH` continues the TRY+/// block, so the pair keeps the depth open instead of ending the batch+/// (#13051). Tokens inside strings, bracketed identifiers, comments and+/// parentheses are ignored, so a nested statement's own blocks do not matter.+fn sqlserver_control_flow_open_blocks(sql: &str) -> usize {+ let tokens = sqlserver_top_level_tokens(sql);+ let mut depth = 0usize;+ let mut carried_try = false;+ for (index, token) in tokens.iter().enumerate() {+ if token.is_word("BEGIN") {+ if !sqlserver_begins_block(&tokens, index) {+ continue;+ }+ if carried_try {+ // `BEGIN CATCH` continues the carried TRY block: the depth the+ // `END TRY` left open is consumed here, not extended.+ carried_try = false;+ } else {+ depth += 1;+ }+ continue;+ }+ if token.is_word("CASE") {+ depth += 1;+ 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;+ }+ 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.+ carried_try = true;+ continue;+ }+ depth = depth.saturating_sub(1);+ carried_try = false;+ }+ depth+}++/// Whether the buffered control-flow batch is complete: every top-level+/// `BEGIN`/`CASE` it opened has been closed, so this `;` is a real statement+/// boundary. A batch still open — including one that is mid-typing — keeps the+/// `;` and stays whole.+fn sqlserver_control_flow_batch_is_complete(sql: &str) -> bool {+ sqlserver_control_flow_open_blocks(sql) == 0+}++/// Byte offset just after the `END`/`END TRY`/`END CATCH` that closes the block+/// a `;`-fragment carried into it, when that closure is final (not followed by+/// `ELSE`). T-SQL semicolons are optional, so a batch whose final `END` has no+/// trailing `;` shares its fragment with the next statement; the statement+/// boundary then sits right after the closing token instead of at the next+/// `;`. Mirrors `scanSqlServerControlFlow`'s `closedAt`/`wordAfterClose` in+/// `sqlStatementRanges.ts`: a block opened and closed inside one `;`-free run+/// has no boundary (the whole run stays one statement), and a closure followed+/// by `ELSE` only continues the same `IF`, so a later closure in the same+/// fragment replaces it.+fn sqlserver_control_flow_batch_boundary(sql: &str) -> Option<usize> {+ let tokens = sqlserver_top_level_tokens(sql);+ let mut index = 0usize;+ let mut fragment_start_depth = 0usize;+ while index < tokens.len() {+ // Scan one `;`-delimited fragment with the depth the previous fragment+ // left open; only a closure of that carried depth is a boundary.+ let mut depth = fragment_start_depth;+ let mut carried_try = false;+ let mut boundary: Option<(usize, &str)> = None;+ while index < tokens.len() {+ let token = &tokens[index];+ if token.is_word(";") {+ index += 1;+ break;+ }+ if token.is_word("BEGIN") {+ if sqlserver_begins_block(&tokens, index) {+ if carried_try {+ // `BEGIN CATCH` continues the carried TRY block.+ carried_try = false;+ } else {+ depth += 1;+ }+ }+ index += 1;+ continue;+ }+ if token.is_word("CASE") {+ depth += 1;+ index += 1;+ continue;+ }+ if !token.is_word("END") {+ index += 1;+ 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")) {+ index += 1;+ continue;+ }+ 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 BEGIN CATCH` keeps the pair in one batch.+ carried_try = true;+ index += 1;+ continue;+ }+ depth = depth.saturating_sub(1);+ carried_try = false;+ if fragment_start_depth > 0 && depth == 0 {+ // `END TRY`/`END CATCH` are two-token closers: the boundary sits+ // after the pair, and the word after the pair decides finality.+ let paired = next.is_some_and(|next| next.is_word("TRY") || next.is_word("CATCH"));+ let (end_offset, word_after) = if paired {+ (tokens[index + 1].end, tokens.get(index + 2).map_or("", |token| token.text))+ } else {+ (token.end, next.map_or("", |token| token.text))+ };+ if boundary.as_ref().is_none_or(|(_, word)| word.eq_ignore_ascii_case("ELSE")) {+ boundary = Some((end_offset, word_after));+ }+ }+ index += 1;+ }+ if let Some((offset, word_after)) = boundary {+ if !word_after.eq_ignore_ascii_case("ELSE") {+ return Some(offset);+ }+ }+ fragment_start_depth = depth;+ }+ None+}+fn starts_with_oracle_style_routine_body(sql: &str) -> bool {OraclePlSqlBlock::parse(sql).starts_oracle_style_routine_body()}@@ -7592,6 +7883,186 @@ END CATCH;";);}+ // #13514: a JDBC SQL Server connection splits with the SQL Server profile+ // (the mapped `statement_split_database_type`), so the reported script keeps+ // its TRY/CATCH batch whole while the leading `SET` stays its own statement.+ #[test]+ fn sqlserver_statement_splitter_keeps_try_catch_batch_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()..];++ assert_eq!(+ split_sql_statements_for_database(sql, DatabaseType::SqlServer),+ vec!["SET XACT_ABORT ON".to_string(), block.to_string()]+ );+ }++ // The same script through the generic JDBC profile (no SQL Server signals)+ // keeps its historical split shape: the Oracle-style routine-body handling+ // glues the block opener to the first inner statement, and the rest splits+ // per statement. The `statement_split_database_type` mapping is what opts a+ // connection into the SQL Server rules instead.+ #[test]+ fn jdbc_statement_splitter_still_splits_try_catch_batches() {+ let sql = "BEGIN TRY\n BEGIN TRANSACTION;\n UPDATE dbo.T SET x = 1;\nEND TRY\nBEGIN CATCH\n THROW;\nEND CATCH;";++ assert_eq!(+ split_sql_statements_for_database(sql, DatabaseType::Jdbc),+ vec![+ "BEGIN TRY\n BEGIN TRANSACTION",+ "UPDATE dbo.T SET x = 1",+ "END TRY\nBEGIN CATCH\n THROW",+ "END CATCH",+ ]+ );+ }++ #[test]+ fn sqlserver_statement_splitter_keeps_if_block_batch_whole() {+ let sql = "IF NOT EXISTS (SELECT 1 FROM sys.databases WHERE name = N'demo')\nBEGIN\n CREATE DATABASE demo;\nEND;\nSELECT 1;";++ assert_eq!(+ split_sql_statements_for_database(sql, DatabaseType::SqlServer),+ vec![+ "IF NOT EXISTS (SELECT 1 FROM sys.databases WHERE name = N'demo')\nBEGIN\n CREATE DATABASE demo;\nEND;",+ "SELECT 1",+ ]+ );+ }++ #[test]+ fn sqlserver_statement_splitter_still_splits_begin_transaction_batches() {+ let sql = "BEGIN TRANSACTION;\nUPDATE dbo.T SET x = 1;\nCOMMIT TRANSACTION;";++ assert_eq!(+ split_sql_statements_for_database(sql, DatabaseType::SqlServer),+ vec!["BEGIN TRANSACTION", "UPDATE dbo.T SET x = 1", "COMMIT TRANSACTION"]+ );+ }++ // The four specs below mirror `sqlStatementRanges.spec.ts` so the backend+ // splitter and the editor range scanner agree on where a control-flow+ // batch ends when its final `END` has no semicolon of its own.+ #[test]+ fn sqlserver_statement_splitter_ends_single_line_if_batch_before_next_statement() {+ let sql = "IF @x = 1 BEGIN SELECT 1; END\nSELECT 999;";++ assert_eq!(+ split_sql_statements_for_database(sql, DatabaseType::SqlServer),+ vec!["IF @x = 1 BEGIN SELECT 1; END", "SELECT 999"]+ );+ }++ #[test]+ fn sqlserver_statement_splitter_ends_try_batch_without_catch_at_end_try() {+ let sql = "BEGIN TRY\n SELECT 1;\nEND TRY\nSELECT 999;";++ assert_eq!(+ split_sql_statements_for_database(sql, DatabaseType::SqlServer),+ vec!["BEGIN TRY\n SELECT 1;\nEND TRY", "SELECT 999"]+ );+ }++ #[test]+ fn sqlserver_statement_splitter_ends_if_else_batch_before_next_statement() {+ let batch = "\+IF NOT EXISTS (SELECT 1 FROM dbo.T WHERE n = N'x')+BEGIN+ SELECT 1;+END+ELSE+BEGIN+ SELECT 2;+END";++ assert_eq!(+ split_sql_statements_for_database(&format!("{batch}\nSELECT 999;"), DatabaseType::SqlServer),+ vec![batch.to_string(), "SELECT 999".to_string()]+ );+ }++ #[test]+ fn sqlserver_statement_splitter_ends_if_else_batch_at_else_branch_end_without_semicolon() {+ let batch = "\+IF @x = 1+BEGIN+ SELECT 1;+END+ELSE+BEGIN+ SELECT 2+END";++ assert_eq!(+ split_sql_statements_for_database(&format!("{batch}\nSELECT 999;"), DatabaseType::SqlServer),+ vec![batch.to_string(), "SELECT 999".to_string()]+ );+ }++ #[test]+ fn sqlserver_statement_splitter_keeps_case_end_inside_if_batch() {+ // `CASE ... END` must not close the surrounding `BEGIN` block, so the+ // batch still ends at its own `END`, before the next statement.+ let sql = "IF @x = 1 BEGIN SELECT CASE WHEN 1 = 1 THEN 'a' ELSE 'b' END AS v; END\nSELECT 999;";++ assert_eq!(+ split_sql_statements_for_database(sql, DatabaseType::SqlServer),+ vec!["IF @x = 1 BEGIN SELECT CASE WHEN 1 = 1 THEN 'a' ELSE 'b' END AS v; END", "SELECT 999",]+ );+ }++ #[test]+ fn sqlserver_statement_splitter_ignores_end_conversation_in_batches() {+ let sql = "IF @x = 1 BEGIN SELECT 1; END\nEND CONVERSATION @handle;\nSELECT 999;";++ assert_eq!(+ split_sql_statements_for_database(sql, DatabaseType::SqlServer),+ vec!["IF @x = 1 BEGIN SELECT 1; END", "END CONVERSATION @handle", "SELECT 999",]+ );+ }++ #[test]+ fn sqlserver_statement_splitter_keeps_nested_try_catch_batch_whole() {+ let batch = "\+WHILE @i < 10+BEGIN+ BEGIN TRY+ SELECT 1;+ END TRY+ BEGIN CATCH+ SET @i = @i + 1;+ END CATCH+END";+ let sql = format!("{batch}\nSELECT 999;");++ assert_eq!(+ split_sql_statements_for_database(&sql, DatabaseType::SqlServer),+ vec![batch.to_string(), "SELECT 999".to_string()]+ );+ }+#[test]fn mysql_delimiter_command_keeps_procedure_body_together_per_issue_1978() {let sql = "\