From 3267f77d019c2f9a018980797506e03c65ff3d64 Mon Sep 17 00:00:00 2001 From: necessarylion Date: Sat, 7 Nov 2026 22:55:50 +0700 Subject: [PATCH 1/4] Show backup progress and let the user cancel a backup A backup only showed a loading state. Now it shows the file size so far, the time, and the table the dump tool works on. A Cancel button (or Esc) stops the tool and deletes the half written file. An older backup at the same path stays as it was. --- CLAUDE.md | 4 +- src-tauri/Cargo.toml | 2 +- src-tauri/src/commands.rs | 26 +++- src-tauri/src/constants/mod.rs | 6 + src-tauri/src/lib.rs | 3 + src-tauri/src/model.rs | 14 ++ src-tauri/src/repository/dump.rs | 244 +++++++++++++++++++++++++++++-- src-tauri/src/service.rs | 28 +++- src-tauri/tests/service.rs | 12 +- src/components/BottomBar.vue | 4 +- src/components/QueryView.vue | 4 +- src/components/Workspace.vue | 12 +- src/constants/index.ts | 3 + src/services/DatabaseApi.ts | 20 ++- src/services/Session.ts | 54 ++++++- src/types.ts | 12 ++ tests/Backup.test.ts | 81 +++++++++- 17 files changed, 487 insertions(+), 42 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 8436f46..2f80755 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -95,7 +95,9 @@ Constants are in `constants/mod.rs`. Errors are `AppError` (`error.rs`), which r changing or dropping a column drops its default first. - Backup and the Users view are not there for SQL Server yet. See `TODO.md`. - **Backups** (`dump.rs`) run `mysqldump` / `pg_dump` or copy the SQLite file. Passwords go through - `MYSQL_PWD` / `PGPASSWORD`. + `MYSQL_PWD` / `PGPASSWORD`. The tools run with `--verbose`. `DumpLog` reads their stderr for the current + table and keeps only the real error lines. Progress (file size, time, table) goes to the frontend through a + `Channel` about once per second. `cancel_dump` kills the tool and deletes the `.part` file. - **AI notes** (`service/notes.rs`): each database has a `claude.md` file at `~/.sql-pro/-/claude.md` (`~/.sql-pro-dev/` in a debug build). The hash (FNV-1a, 8 hex) is of driver, server host, port and database (SQLite: the file path), not the user. The user edits it in Ask AI. The AI adds facts to it (`remember`). diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index cf2b4c6..5e48bb3 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -45,7 +45,7 @@ parking_lot = "0.13" # Version 4 finds the same items as version 3, so saved passwords stay. keyring = "4" # Runs the system ssh program for tunnels. -tokio = { version = "1", features = ["process", "net", "time", "io-util"] } +tokio = { version = "1", features = ["process", "net", "time", "io-util", "macros"] } tauri-plugin-updater = "2" # Lists the fonts installed on the machine, for the font settings. WKWebView cannot do it. fontdb = "0.24" diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index ac38611..9035224 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -6,14 +6,15 @@ use std::path::PathBuf; use tauri::State; +use tauri::ipc::Channel; use crate::error::{AppError, AppResult}; use crate::model::{ AccessLevel, AiOptions, Attachment, BrowseRequest, ClaudeReply, ColumnInfo, ColumnSpec, ConnectionConfig, CsvImport, CsvPreview, DataDiff, DataKinds, DbObject, DbProcess, Diagram, - ExportRequest, NewColumn, NewForeignKey, NewIndex, NewUser, Notes, QueryStat, ResultSet, - RowUpdate, RowsExport, RowsSql, SaveResult, SchemaChange, SyncSql, TableKeys, TablePage, - TableRef, UserList, Values, + DumpProgress, ExportRequest, NewColumn, NewForeignKey, NewIndex, NewUser, Notes, QueryStat, + ResultSet, RowUpdate, RowsExport, RowsSql, SaveResult, SchemaChange, SyncSql, TableKeys, + TablePage, TableRef, UserList, Values, }; use crate::open_file::OpenedFiles; use crate::repository::PasswordRepository; @@ -363,8 +364,23 @@ pub async fn truncate_table(service: Service<'_>, id: String, table: TableRef) - } #[tauri::command] -pub async fn dump_database(service: Service<'_>, id: String, path: PathBuf) -> AppResult<()> { - service.dump_database(&id, &path).await +pub async fn dump_database( + service: Service<'_>, + id: String, + path: PathBuf, + progress: Channel, +) -> AppResult<()> { + service + .dump_database(&id, &path, |step| { + // The page may be gone. The backup goes on anyway. + let _ = progress.send(step); + }) + .await +} + +#[tauri::command] +pub fn cancel_dump(service: Service<'_>, id: String) { + service.cancel_dump(&id); } #[tauri::command] diff --git a/src-tauri/src/constants/mod.rs b/src-tauri/src/constants/mod.rs index e04fb97..6d17cd7 100644 --- a/src-tauri/src/constants/mod.rs +++ b/src-tauri/src/constants/mod.rs @@ -79,6 +79,12 @@ pub const CREATE_NO_WINDOW: u32 = 0x0800_0000; /// What we add to the path of a dump while it is being written. pub const PARTIAL_DUMP_SUFFIX: &str = ".part"; +/// The error of a backup that the user cancelled. +pub const BACKUP_CANCELLED: &str = "Backup cancelled"; + +/// How often a running backup tells the frontend how far it is. +pub const DUMP_PROGRESS_EVERY: std::time::Duration = std::time::Duration::from_secs(1); + /// The `MySQL` account host that means "from any host". pub const ANY_HOST: &str = "%"; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 5d7cd6c..4bffc92 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -24,6 +24,8 @@ use tauri::Manager as _; /// /// Panics when the window cannot be created. #[cfg_attr(mobile, tauri::mobile_entry_point)] +// Most of its lines are the list of commands. +#[allow(clippy::too_many_lines)] pub fn run() { #[cfg(all(debug_assertions, target_os = "macos"))] run_under_dev_name(); @@ -93,6 +95,7 @@ pub fn run() { commands::save_object, commands::drop_object, commands::dump_database, + commands::cancel_dump, commands::export_tables, commands::export_rows, commands::rows_insert_sql, diff --git a/src-tauri/src/model.rs b/src-tauri/src/model.rs index f08b0b3..234ef79 100644 --- a/src-tauri/src/model.rs +++ b/src-tauri/src/model.rs @@ -507,6 +507,20 @@ impl ExportFormat { } } +/// How far a running backup is. The backend sends it about once per second. +#[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct DumpProgress { + /// The size of the dump file so far. + pub bytes: u64, + /// The time since the backup started. + pub seconds: u64, + /// The table the dump tool works on now. None before the first table, and for `SQLite`. + pub table: Option, + /// How many tables the dump tool has started, this one included. + pub tables: usize, +} + /// What to export, and where to write it. #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] diff --git a/src-tauri/src/repository/dump.rs b/src-tauri/src/repository/dump.rs index 696f992..6129140 100644 --- a/src-tauri/src/repository/dump.rs +++ b/src-tauri/src/repository/dump.rs @@ -2,20 +2,25 @@ //! //! The tools know every detail of their own database, so the dump can be loaded again. +use std::collections::VecDeque; use std::ffi::OsString; use std::fs::File; use std::path::{Path, PathBuf}; use std::process::Stdio; +use std::time::Instant; +use futures_util::future::{AbortRegistration, Abortable}; +use tokio::io::{AsyncBufReadExt as _, BufReader}; use tokio::process::Command; -#[cfg(unix)] -use crate::constants::{HOMEBREW_OPT_DIR, TOOL_DIRS}; use crate::constants::{ - MSSQL_NO_BACKUP, MYSQL_PASSWORD_ENV, PARTIAL_DUMP_SUFFIX, POSTGRES_PASSWORD_ENV, + BACKUP_CANCELLED, DUMP_PROGRESS_EVERY, MSSQL_NO_BACKUP, MYSQL_PASSWORD_ENV, + PARTIAL_DUMP_SUFFIX, POSTGRES_PASSWORD_ENV, }; +#[cfg(unix)] +use crate::constants::{HOMEBREW_OPT_DIR, TOOL_DIRS}; use crate::error::{AppError, AppResult}; -use crate::model::{ConnectionConfig, Driver}; +use crate::model::{ConnectionConfig, Driver, DumpProgress}; /// Writes SQL dumps with the dump tools that are installed on this computer. pub struct DumpRepository; @@ -25,7 +30,15 @@ impl DumpRepository { /// /// `config` must hold the host and port we really connect to. With an SSH /// tunnel that is the local end of the tunnel. - pub async fn dump(config: &ConnectionConfig, path: &Path) -> AppResult<()> { + /// + /// `progress` gets how far it is, about once per second. An abort of `cancel` kills + /// the tool. The dump then fails with `BACKUP_CANCELLED` and leaves no file. + pub async fn dump( + config: &ConnectionConfig, + path: &Path, + progress: impl FnMut(DumpProgress), + cancel: AbortRegistration, + ) -> AppResult<()> { if config.driver == Driver::Mssql { return Err(MSSQL_NO_BACKUP.into()); } @@ -35,7 +48,7 @@ impl DumpRepository { partial.push(PARTIAL_DUMP_SUFFIX); let partial = PathBuf::from(partial); - let mut result = Self::run(config, &partial).await; + let mut result = Self::run(config, &partial, progress, cancel).await; if result.is_ok() { result = std::fs::rename(&partial, path).map_err(AppError::from); } @@ -47,7 +60,12 @@ impl DumpRepository { } /// Runs the dump tool and waits for it. Its error text becomes our error. - async fn run(config: &ConnectionConfig, output: &Path) -> AppResult<()> { + async fn run( + config: &ConnectionConfig, + output: &Path, + mut progress: impl FnMut(DumpProgress), + cancel: AbortRegistration, + ) -> AppResult<()> { let mut command = match config.driver { Driver::Mysql => Self::mysql(config, output).await?, Driver::Postgres => Self::postgres(config, output)?, @@ -59,19 +77,50 @@ impl DumpRepository { .stdin(Stdio::null()) .stderr(Stdio::piped()) .kill_on_drop(true); - let finished = command.spawn()?.wait_with_output().await?; - if finished.status.success() { + let mut child = command.spawn()?; + let stderr = child + .stderr + .take() + .ok_or("The dump tool has no error output")?; + // Not `lines()`: a line that is not UTF-8 would end the read with an error. + let mut lines = BufReader::new(stderr).split(b'\n'); + let mut log = DumpLog::default(); + let started = Instant::now(); + let mut tick = tokio::time::interval(DUMP_PROGRESS_EVERY); + let mut cancelled = Abortable::new(std::future::pending::<()>(), cancel); + // The tool closes its error output when it ends. + loop { + tokio::select! { + // A cancel wins over everything else. + biased; + _ = &mut cancelled => { + // Wait until it is gone, so the file is closed before it is deleted. + // It may have ended by itself just now. That is fine. + let _ = child.kill().await; + return Err(BACKUP_CANCELLED.into()); + } + line = lines.next_segment() => match line? { + Some(line) => { + if log.read(&String::from_utf8_lossy(&line)) { + progress(log.progress(output, started)); + } + } + None => break, + }, + _ = tick.tick() => progress(log.progress(output, started)), + } + } + let status = child.wait().await?; + if status.success() { return Ok(()); } - let reason = String::from_utf8_lossy(&finished.stderr); - let reason = reason.trim(); + let reason = log.reason(); if reason.is_empty() { return Err(AppError::Message(format!( - "The dump tool failed ({})", - finished.status + "The dump tool failed ({status})" ))); } - Err(AppError::Message(reason.to_owned())) + Err(AppError::Message(reason)) } async fn mysql(config: &ConnectionConfig, output: &Path) -> AppResult { @@ -92,6 +141,8 @@ impl DumpRepository { .arg("--triggers") // Tablespaces need the PROCESS right, which most users do not have. .arg("--no-tablespaces") + // Names each table on stderr. That is how we show the progress. + .arg("--verbose") .arg(Self::option("--result-file=", output)) .stdout(Stdio::null()); if !config.user.is_empty() { @@ -122,6 +173,7 @@ impl DumpRepository { .arg(format!("--port={}", config.port)) // Never wait for a typed password. Nobody can type it. .arg("--no-password") + .arg("--verbose") .arg(Self::option("--file=", output)) .stdout(Stdio::null()); if !config.user.is_empty() { @@ -215,3 +267,167 @@ impl DumpRepository { folders } } + +/// The error output of a dump tool. With `--verbose` it names each table it starts. +/// It also keeps the lines we show when the tool fails. +#[derive(Default)] +struct DumpLog { + /// The lines that are not progress chatter. Mostly the real errors. + errors: Vec, + /// The last lines of all. We show them when no line looks like an error. + tail: VecDeque, + table: Option, + tables: usize, +} + +impl DumpLog { + /// ponytail: a broken server can print many error lines. The first ones tell the cause. + const MAX_ERRORS: usize = 20; + const MAX_TAIL: usize = 5; + + /// Reads one line. Returns true when it names a new table. + fn read(&mut self, line: &str) -> bool { + let line = line.trim_end(); + if line.is_empty() { + return false; + } + if self.tail.len() == Self::MAX_TAIL { + self.tail.pop_front(); + } + self.tail.push_back(line.to_owned()); + if let Some(table) = Self::table_of(line) { + self.table = Some(table); + self.tables += 1; + return true; + } + if !Self::is_chatter(line) && self.errors.len() < Self::MAX_ERRORS { + self.errors.push(line.to_owned()); + } + false + } + + /// The error text when the tool failed. + fn reason(&self) -> String { + if self.errors.is_empty() { + Vec::from(self.tail.clone()).join("\n") + } else { + self.errors.join("\n") + } + } + + fn progress(&self, output: &Path, started: Instant) -> DumpProgress { + DumpProgress { + // The file is not there before the tool opens it. + bytes: std::fs::metadata(output).map_or(0, |file| file.len()), + seconds: started.elapsed().as_secs(), + table: self.table.clone(), + tables: self.tables, + } + } + + /// The table a line names, like `-- Retrieving table structure for table orders...` + /// (mysqldump) or `pg_dump: dumping contents of table "public.orders"`. + fn table_of(line: &str) -> Option { + let name = if let Some(rest) = line.strip_prefix("-- Retrieving table structure for table ") + { + rest.trim_end_matches("...").trim_matches('`') + } else { + line.strip_prefix("pg_dump: ")? + .strip_prefix("dumping contents of table ")? + .trim_matches('"') + }; + (!name.is_empty()).then(|| name.to_owned()) + } + + /// True for a `--verbose` line that only tells what the tool does now. + fn is_chatter(line: &str) -> bool { + if line.starts_with("-- ") { + return true; + } + line.strip_prefix("pg_dump: ").is_some_and(|rest| { + !["error:", "detail:", "hint:", "warning:"] + .iter() + .any(|kind| rest.starts_with(kind)) + }) + } +} + +#[cfg(test)] +mod tests { + use futures_util::future::AbortHandle; + + use super::{DumpLog, DumpRepository}; + use crate::constants::BACKUP_CANCELLED; + use crate::model::{ConnectionConfig, Driver, SslConfig}; + + #[tokio::test] + async fn a_cancel_leaves_the_older_backup_alone() { + let folder = std::env::temp_dir(); + let id = std::process::id(); + let database = folder.join(format!("sqlpro-cancel-{id}.sqlite")); + std::fs::File::create(&database).expect("database"); + let path = folder.join(format!("sqlpro-cancel-{id}.sql")); + std::fs::write(&path, "old").expect("old backup"); + let config = ConnectionConfig { + driver: Driver::Sqlite, + host: String::new(), + port: 0, + user: String::new(), + password: String::new(), + database: database.to_string_lossy().into_owned(), + ssh: None, + ssl: SslConfig::default(), + }; + let (handle, registration) = AbortHandle::new_pair(); + handle.abort(); + let result = DumpRepository::dump(&config, &path, drop, registration).await; + let old = std::fs::read_to_string(&path); + let partial = folder.join(format!("sqlpro-cancel-{id}.sql.part")).exists(); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(&database); + match result { + Err(error) if error.to_string().contains("was not found") => return, + Err(error) => assert_eq!(error.to_string(), BACKUP_CANCELLED), + Ok(()) => panic!("the dump was not cancelled"), + } + assert_eq!(old.expect("old backup"), "old"); + assert!(!partial, "the side file is still there"); + } + + #[test] + fn finds_the_table_of_mysqldump_and_pg_dump() { + let mut log = DumpLog::default(); + assert!(!log.read("-- Connecting to 127.0.0.1...")); + assert!(log.read("-- Retrieving table structure for table orders...")); + assert_eq!(log.table.as_deref(), Some("orders")); + assert!(!log.read("-- Sending SELECT query...")); + assert!(log.read("-- Retrieving table structure for table `order items`...\n")); + assert_eq!(log.table.as_deref(), Some("order items")); + assert!(!log.read("pg_dump: reading schemas")); + assert!(log.read(r#"pg_dump: dumping contents of table "public.users""#)); + assert_eq!(log.table.as_deref(), Some("public.users")); + assert_eq!(log.tables, 3); + // Chatter only: the error falls back to the last lines. + assert!( + log.reason() + .ends_with("pg_dump: dumping contents of table \"public.users\"") + ); + } + + #[test] + fn keeps_only_the_real_errors() { + let mut log = DumpLog::default(); + log.read("pg_dump: last built-in OID is 16383"); + log.read("pg_dump: reading extensions"); + log.read("pg_dump: error: query failed: ERROR: permission denied for table secret"); + log.read("pg_dump: detail: Query was: LOCK TABLE public.secret IN ACCESS SHARE MODE"); + log.read("-- Retrieving rows..."); + log.read("mysqldump: Got error: 1045: Access denied for user 'me'"); + assert_eq!( + log.reason(), + "pg_dump: error: query failed: ERROR: permission denied for table secret\n\ + pg_dump: detail: Query was: LOCK TABLE public.secret IN ACCESS SHARE MODE\n\ + mysqldump: Got error: 1045: Access denied for user 'me'" + ); + } +} diff --git a/src-tauri/src/service.rs b/src-tauri/src/service.rs index bd00971..f4e15dc 100644 --- a/src-tauri/src/service.rs +++ b/src-tauri/src/service.rs @@ -30,7 +30,7 @@ use crate::constants::{ use crate::error::{AppError, AppResult}; use crate::model::{ AccessLevel, AiOptions, Attachment, BrowseRequest, ClaudeReply, ColumnInfo, ColumnSpec, - ConnectionConfig, DbObject, DbUser, Diagram, DiagramTable, Driver, ExportRequest, + ConnectionConfig, DbObject, DbUser, Diagram, DiagramTable, Driver, DumpProgress, ExportRequest, FilterOperator, FilterRule, ForeignKey, IndexInfo, NewColumn, NewForeignKey, NewIndex, NewUser, Notes, ResultSet, RowUpdate, RowsExport, RowsSql, SaveResult, TableKeys, TablePage, TableRef, UserList, Values, @@ -64,6 +64,8 @@ pub struct ConnectionService { connections: Mutex>, /// The connects that still run, by tab id. `cancel_connect` stops one. connecting: Mutex>>, + /// The backups that still run, by tab id. `cancel_dump` stops one. + dumping: Mutex>, claude: ClaudeCli, /// Holds the notes of each database for the AI. See `NOTES_FOLDER`. notes_folder: Option, @@ -75,6 +77,7 @@ impl ConnectionService { factory, connections: Mutex::new(HashMap::new()), connecting: Mutex::new(HashMap::new()), + dumping: Mutex::new(HashMap::new()), claude: ClaudeCli::default(), notes_folder: std::env::home_dir().map(|home| home.join(NOTES_FOLDER)), } @@ -564,8 +567,13 @@ impl ConnectionService { /// Writes a full SQL dump of the current database to the file at `path`. /// /// The dump tool is its own process with its own login. So the tab can be - /// used while it runs, and no lock is held. - pub async fn dump_database(&self, id: &str, path: &Path) -> AppResult<()> { + /// used while it runs, and no lock is held. `progress` gets how far it is. + pub async fn dump_database( + &self, + id: &str, + path: &Path, + progress: impl FnMut(DumpProgress), + ) -> AppResult<()> { // This copy also keeps the tunnel open until the dump is done. let connection = self.connection(id)?; let mut config = connection.config; @@ -574,7 +582,19 @@ impl ConnectionService { LOCALHOST.clone_into(&mut config.host); config.port = tunnel.local_port(); } - DumpRepository::dump(&config, path).await + let (handle, registration) = AbortHandle::new_pair(); + self.dumping.lock().insert(id.to_owned(), handle); + let result = DumpRepository::dump(&config, path, progress, registration).await; + self.dumping.lock().remove(id); + result + } + + /// Stops the backup that runs now for `id`. It then fails with `BACKUP_CANCELLED`. + /// Does nothing when no backup runs. + pub fn cancel_dump(&self, id: &str) { + if let Some(handle) = self.dumping.lock().remove(id) { + handle.abort(); + } } /// Writes tables to a SQL or CSV file. See `ExportRequest`. diff --git a/src-tauri/tests/service.rs b/src-tauri/tests/service.rs index 60d95a7..bdcd159 100644 --- a/src-tauri/tests/service.rs +++ b/src-tauri/tests/service.rs @@ -988,14 +988,18 @@ async fn dump(service: &ConnectionService, driver: Driver) { let path = temp_path("dump", "sql"); if driver == Driver::Mssql { let error = service - .dump_database(ID, &path) + .dump_database(ID, &path, drop) .await .expect_err("no backup"); assert!(error.to_string().contains("not supported"), "{error}"); assert!(!path.exists()); return; } - match service.dump_database(ID, &path).await { + let mut steps = Vec::new(); + match service + .dump_database(ID, &path, |step| steps.push(step)) + .await + { Err(error) if error.to_string().contains("was not found") => { println!("NOTE: the dump check for {driver:?} is skipped: {error}"); return; @@ -1010,12 +1014,14 @@ async fn dump(service: &ConnectionService, driver: Driver) { "no CREATE TABLE in the dump" ); assert!(sql.contains("Brien") && sql.contains("2020-01-31")); + // The progress came at least once: the first tick is at the start. + assert_ne!(steps.len(), 0); // The side file of the dump is gone. assert!(!folder.join(format!("{}.part", path.display())).exists()); // A folder that does not exist: an error, and no file. let missing = folder.join("sqlpro-no-such-folder").join("dump.sql"); - assert!(service.dump_database(ID, &missing).await.is_err()); + assert!(service.dump_database(ID, &missing, drop).await.is_err()); assert!(!missing.exists()); assert!(!folder.join("sqlpro-no-such-folder").exists()); } diff --git a/src/components/BottomBar.vue b/src/components/BottomBar.vue index 6eebc10..4109736 100644 --- a/src/components/BottomBar.vue +++ b/src/components/BottomBar.vue @@ -13,11 +13,11 @@ defineProps<{ session: Session }>() {{ session.error }} - {{ session.busy ? 'Working…' : session.status }} + {{ session.busy ? session.busyText : session.status }}