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(mysql): cancel running SQL imports
t8y26c571a57abc2
diff --git a/crates/dbx-core/src/db/mysql.rs b/crates/dbx-core/src/db/mysql.rsindex d228f6db1f..d3624ac0b1 100644--- a/crates/dbx-core/src/db/mysql.rs+++ b/crates/dbx-core/src/db/mysql.rs@@ -1727,6 +1727,16 @@ pub async fn execute_query_with_max_rows(execute_query_on_conn_with_max_rows(&mut conn, sql, bare, max_rows, dialect).await}+pub async fn kill_query(pool: &MySqlPool, connection_id: u32) -> Result<(), String> {+ let mut conn = pool.get_conn().await.map_err(|e| e.to_string())?;+ conn.query_drop(format!("KILL QUERY {connection_id}")).await.map_err(|e| e.to_string())+}++pub async fn kill_query_with_opts(opts: mysql_async::Opts, connection_id: u32) -> Result<(), String> {+ let mut conn = mysql_async::Conn::new(opts).await.map_err(|e| e.to_string())?;+ conn.query_drop(format!("KILL QUERY {connection_id}")).await.map_err(|e| e.to_string())+}+pub async fn execute_query_on_conn_with_max_rows(conn: &mut mysql_async::Conn,sql: &str,diff --git a/crates/dbx-core/src/query.rs b/crates/dbx-core/src/query.rsindex 9f6407f89b..4ebfae5041 100644--- a/crates/dbx-core/src/query.rs+++ b/crates/dbx-core/src/query.rs@@ -853,10 +853,23 @@ pub async fn do_execute(let bare = *mode == crate::connection::MysqlMode::Bare;let max_rows = options.max_rows;drop(connections);+ let mut conn = db::mysql::get_conn_with_health_check(&p).await?;+ let connection_id = conn.id();+ if let Some(ref execution_id) = options.execution_id {+ let kill_opts = conn.opts().clone();+ state.running_queries.register_interrupt(execution_id, move || {+ let kill_opts = kill_opts.clone();+ tokio::spawn(async move {+ if let Err(error) = db::mysql::kill_query_with_opts(kill_opts, connection_id).await {+ log::warn!("Failed to cancel MySQL query {connection_id}: {error}");+ }+ });+ });+ }wait_for_query_opt(cancel_token,query_timeout,- db::mysql::execute_query_with_max_rows(&p, sql, bare, max_rows, mysql_dialect),+ db::mysql::execute_query_on_conn_with_max_rows(&mut conn, sql, bare, max_rows, mysql_dialect),).await}diff --git a/crates/dbx-core/src/query_cancel.rs b/crates/dbx-core/src/query_cancel.rsindex 8c1b4ae67c..6193a6f422 100644--- a/crates/dbx-core/src/query_cancel.rs+++ b/crates/dbx-core/src/query_cancel.rs@@ -79,6 +79,20 @@ mod tests {assert!(registered.token().is_cancelled());}+ #[test]+ fn cancel_invokes_registered_interrupt() {+ let running = RunningQueries::default();+ let interrupted = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));+ let flag = interrupted.clone();+ let _registered = running.register("exec-1".to_string());+ running.register_interrupt("exec-1", move || {+ flag.store(true, std::sync::atomic::Ordering::SeqCst);+ });++ assert!(running.cancel("exec-1"));+ assert!(interrupted.load(std::sync::atomic::Ordering::SeqCst));+ }+#[test]fn dropping_registration_removes_running_query() {let running = RunningQueries::default();diff --git a/crates/dbx-core/src/sql_file_import.rs b/crates/dbx-core/src/sql_file_import.rsindex d6d77fe034..1857697897 100644--- a/crates/dbx-core/src/sql_file_import.rs+++ b/crates/dbx-core/src/sql_file_import.rs@@ -4,11 +4,12 @@ use tokio_util::sync::CancellationToken;use crate::connection::AppState;use crate::models::connection::DatabaseType;-use crate::query::execute_sql_statement;+use crate::query::{execute_sql_statement_with_options, QueryExecutionOptions};use crate::sql::{optimize_sql_file_import_statements, statement_summary, SqlFileImportStatement, SqlFileImportStatementKind,SqlFileProgress, SqlFileRequest, SqlFileStatus, SqlParsingOptions, SqlStatementSplitter,};+use crate::types::QueryResult;#[derive(Debug, Clone)]struct SqlFileImportTarget {@@ -205,16 +206,7 @@ async fn execute_statement_with_progress(None,));- match execute_sql_statement(- state,- &request.connection_id,- &request.database,- &statement.sql,- None,- Some(token.clone()),- )- .await- {+ match execute_sql_file_statement(state, request, &statement.sql, token, statement_index).await {Ok(result) => {*success_count += statement.source_statement_count;*affected_rows += result.affected_rows;@@ -313,16 +305,7 @@ async fn execute_merged_statement_fallback_with_progress(None,));- match execute_sql_statement(- state,- &request.connection_id,- &request.database,- source_sql,- None,- Some(token.clone()),- )- .await- {+ match execute_sql_file_statement(state, request, source_sql, token, statement_index).await {Ok(result) => {*success_count += 1;*affected_rows += result.affected_rows;@@ -366,6 +349,45 @@ async fn execute_merged_statement_fallback_with_progress(Ok(false)}+async fn execute_sql_file_statement(+ state: &AppState,+ request: &SqlFileRequest,+ sql: &str,+ token: &CancellationToken,+ statement_index: usize,+) -> Result<QueryResult, String> {+ let execution_id = sql_file_statement_execution_id(&request.execution_id, statement_index);+ let registered = state.running_queries.register(execution_id.clone());+ let child_token = registered.token();+ let cancel_task = {+ let parent_token = token.clone();+ let running_queries = state.running_queries.clone();+ let execution_id = execution_id.clone();+ tokio::spawn(async move {+ parent_token.cancelled().await;+ running_queries.cancel(&execution_id);+ })+ };++ let result = execute_sql_statement_with_options(+ state,+ &request.connection_id,+ &request.database,+ sql,+ None,+ Some(child_token),+ QueryExecutionOptions { execution_id: Some(execution_id), ..Default::default() },+ )+ .await;++ cancel_task.abort();+ result+}++fn sql_file_statement_execution_id(parent_execution_id: &str, statement_index: usize) -> String {+ format!("{parent_execution_id}:statement:{statement_index}")+}+#[allow(clippy::too_many_arguments)]fn statement_error_decision(execution_id: &str,diff --git a/crates/dbx-core/tests/live_mysql57.rs b/crates/dbx-core/tests/live_mysql57.rsindex f05b5a3bf2..8977ff871f 100644--- a/crates/dbx-core/tests/live_mysql57.rs+++ b/crates/dbx-core/tests/live_mysql57.rs@@ -33,3 +33,37 @@ async fn live_mysql_compatible_limited_text_protocol_query_succeeds() {assert!(!result.rows.is_empty());assert!(result.rows.len() <= 100);}++#[tokio::test]+#[ignore = "requires a remote MySQL endpoint"]+async fn live_mysql_query_cancel_kills_running_sleep() {+ let url = std::env::var("DBX_LIVE_MYSQL_CANCEL_URL").expect("DBX_LIVE_MYSQL_CANCEL_URL");++ let opts = mysql_async::OptsBuilder::from_opts(mysql_async::Opts::from_url(&url).unwrap())+ .pool_opts(mysql_async::PoolOpts::new().with_constraints(mysql_async::PoolConstraints::new(1, 1).unwrap()));+ let pool = mysql_async::Pool::new(opts);+ let mut conn = dbx_core::db::mysql::get_conn_with_health_check(&pool).await.unwrap();+ let connection_id = mysql_async::Conn::id(&conn);+ let kill_opts = conn.opts().clone();++ let query = tokio::spawn(async move {+ dbx_core::db::mysql::execute_query_on_conn_with_max_rows(+ &mut conn,+ "SELECT SLEEP(30)",+ false,+ Some(10),+ Default::default(),+ )+ .await+ });++ tokio::time::sleep(std::time::Duration::from_millis(500)).await;+ dbx_core::db::mysql::kill_query_with_opts(kill_opts, connection_id).await.unwrap();++ let started = std::time::Instant::now();+ let result = query.await.unwrap();++ assert!(started.elapsed() < std::time::Duration::from_secs(5));+ let result = result.unwrap();+ assert_eq!(result.rows, vec![vec![serde_json::json!("1")]]);+}