diff --git a/CLAUDE.md b/CLAUDE.md index 23a41f8..696cceb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -102,7 +102,10 @@ 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. + Esc stops a backup only when Escape has no other job there (`Shortcuts.cancelsBackup`). - **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 76cce63..6ed190a 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -47,7 +47,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 9c84c1a..bd59eeb 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, QueryPlan, QueryStat, - ResultSet, RowUpdate, RowsExport, RowsSql, SaveResult, SchemaChange, SyncSql, TableKeys, - TablePage, TableRef, UserList, Values, + DumpProgress, ExportRequest, NewColumn, NewForeignKey, NewIndex, NewUser, Notes, QueryPlan, + QueryStat, ResultSet, RowUpdate, RowsExport, RowsSql, SaveResult, SchemaChange, SyncSql, + TableKeys, TablePage, TableRef, UserList, Values, }; use crate::open_file::OpenedFiles; use crate::repository::PasswordRepository; @@ -369,8 +370,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 1d4ddf8..83dafbd 100644 --- a/src-tauri/src/constants/mod.rs +++ b/src-tauri/src/constants/mod.rs @@ -79,6 +79,15 @@ 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"; + +/// The error when the user starts a second backup in a tab whose first one still runs. +pub const BACKUP_RUNS: &str = "A backup already runs in this tab"; + +/// 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 8ca94e6..187f64e 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 26f9829..085b49d 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..155f89a 100644 --- a/src-tauri/src/repository/dump.rs +++ b/src-tauri/src/repository/dump.rs @@ -2,20 +2,26 @@ //! //! 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::sync::atomic::{AtomicU64, Ordering}; +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,17 +31,23 @@ 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()); } // The tool writes to a side file first. So a dump that fails leaves no // half file, and does not harm an older backup that is already at `path`. - let mut partial = OsString::from(path); - partial.push(PARTIAL_DUMP_SUFFIX); - let partial = PathBuf::from(partial); + let partial = Self::partial_path(path); - 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); } @@ -46,8 +58,26 @@ impl DumpRepository { result } + /// The side file of a dump to `path`, like `shop.sql.4242-7.part`. The name is new for + /// each dump. So two tabs that back up to the same file never write into one side file. + fn partial_path(path: &Path) -> PathBuf { + static NEXT: AtomicU64 = AtomicU64::new(0); + let mut partial = OsString::from(path); + partial.push(format!( + ".{}-{}{PARTIAL_DUMP_SUFFIX}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + PathBuf::from(partial) + } + /// 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 +89,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 +153,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 +185,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 +279,207 @@ 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 std::ffi::OsStr; + use std::path::Path; + + 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")); + let _ = std::fs::remove_file(&database); + // Enough rows that the dump still runs when the cancel comes. + let filled = std::process::Command::new("sqlite3") + .arg(&database) + .arg( + "CREATE TABLE t(x TEXT); WITH RECURSIVE c(n) AS (SELECT 1 UNION ALL \ + SELECT n + 1 FROM c WHERE n < 300000) INSERT INTO t SELECT hex(randomblob(64)) FROM c;", + ) + .status(); + if !filled.is_ok_and(|status| status.success()) { + println!("NOTE: the cancel check is skipped: sqlite3 was not found"); + return; + } + 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(); + let mut steps = 0; + // The first progress comes right after the tool started. Cancel there. + let cancel = |_| { + steps += 1; + handle.abort(); + }; + let result = DumpRepository::dump(&config, &path, cancel, registration).await; + let old = std::fs::read_to_string(&path); + let partial = std::fs::read_dir(&folder) + .expect("temp folder") + .flatten() + .any(|entry| { + let name = entry.file_name(); + let name = name.to_string_lossy(); + name.starts_with(&format!("sqlpro-cancel-{id}.sql.")) && name.ends_with(".part") + }); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(&database); + assert_eq!( + result.expect_err("the dump was not cancelled").to_string(), + BACKUP_CANCELLED + ); + assert_eq!(steps, 1); + assert_eq!(old.expect("old backup"), "old"); + assert!(!partial, "the side file is still there"); + } + + #[test] + fn each_dump_has_its_own_side_file() { + let path = Path::new("/backups/shop.sql"); + let first = DumpRepository::partial_path(path); + let second = DumpRepository::partial_path(path); + assert_ne!(first, second); + for partial in [first, second] { + assert_eq!(partial.extension(), Some(OsStr::new("part"))); + let name = partial.to_string_lossy().into_owned(); + assert!(name.starts_with("/backups/shop.sql."), "{name}"); + } + } + + #[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 18c9306..f00bb34 100644 --- a/src-tauri/src/service.rs +++ b/src-tauri/src/service.rs @@ -22,15 +22,16 @@ use futures_util::future::{AbortHandle, Abortable}; use parking_lot::Mutex; use crate::constants::{ - AI_IMAGE_MAX_BYTES, ANY_HOST, CANNOT_MANAGE_USERS, CHARSET_ONLY_MYSQL, CLAUDE_READ_ONLY_NOTE, - CONNECT_CANCELLED, DROP_CURRENT_DATABASE, LIKE_ESCAPE, LOCALHOST, MAX_QUERY_ROWS, - MSSQL_NO_USER_ACCOUNTS, NO_HOME_FOR_NOTES, NO_USER_ACCOUNTS, NOT_A_READ, NOTES_FOLDER, - OPEN_TRANSACTION, PRIMARY_KEY_NOT_DROPPED, QUERY_STATS_FIXED, SQLITE_NO_DATABASES, VIEW, + AI_IMAGE_MAX_BYTES, ANY_HOST, BACKUP_RUNS, CANNOT_MANAGE_USERS, CHARSET_ONLY_MYSQL, + CLAUDE_READ_ONLY_NOTE, CONNECT_CANCELLED, DROP_CURRENT_DATABASE, LIKE_ESCAPE, LOCALHOST, + MAX_QUERY_ROWS, MSSQL_NO_USER_ACCOUNTS, NO_HOME_FOR_NOTES, NO_USER_ACCOUNTS, NOT_A_READ, + NOTES_FOLDER, OPEN_TRANSACTION, PRIMARY_KEY_NOT_DROPPED, QUERY_STATS_FIXED, + SQLITE_NO_DATABASES, VIEW, }; 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 +65,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 +78,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)), } @@ -566,8 +570,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; @@ -576,7 +585,27 @@ impl ConnectionService { LOCALHOST.clone_into(&mut config.host); config.port = tunnel.local_port(); } - DumpRepository::dump(&config, path).await + let (handle, registration) = AbortHandle::new_pair(); + { + let mut dumping = self.dumping.lock(); + // Two backups of one tab would write the same side file. + if dumping.contains_key(id) { + return Err(BACKUP_RUNS.into()); + } + dumping.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) { + // Only `dump_database` removes the entry, when its backup ends. + if let Some(handle) = self.dumping.lock().get(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 dd759eb..832b0c2 100644 --- a/src-tauri/tests/service.rs +++ b/src-tauri/tests/service.rs @@ -990,14 +990,18 @@ async fn dump(service: &ConnectionService, driver: Driver, database: &str) { 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; @@ -1016,12 +1020,27 @@ async fn dump(service: &ConnectionService, driver: Driver, database: &str) { "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()); + let name = path + .file_name() + .expect("name") + .to_string_lossy() + .into_owned(); + let left = std::fs::read_dir(&folder) + .expect("temp folder") + .flatten() + .any(|entry| { + let other = entry.file_name(); + let other = other.to_string_lossy(); + other.starts_with(&format!("{name}.")) && other.ends_with(".part") + }); + assert!(!left, "the side file of the dump is still there"); // 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/App.vue b/src/App.vue index e135f30..8c71ada 100644 --- a/src/App.vue +++ b/src/App.vue @@ -34,6 +34,17 @@ function detail(session: Session): string { * The one place for the save, refresh, export, detail panel, duplicate and zoom keys. Only the active tab saves, refreshes or exports. * The default is always stopped. It would save or reload the whole page of the app. */ +/** + * True when the key stops work of the tab. A query or page load always stops. + * A backup stops only when Escape has no other job, like closing a dialog. + */ +function cancelsWork(event: KeyboardEvent, session: Session | undefined): boolean { + if (!session || !shortcuts.cancels(event)) { + return false + } + return session.cancellable || (session.dumping && shortcuts.cancelsBackup(event)) +} + function onKey(event: KeyboardEvent): void { // The zoom is for the whole app, also with no open connection. const zoom = shortcuts.zoom(event) @@ -46,9 +57,9 @@ function onKey(event: KeyboardEvent): void { return } // Escape or Cmd+. stops a running query. Otherwise Escape keeps its normal job. - if (shortcuts.cancels(event) && manager.active?.cancellable) { + if (cancelsWork(event, manager.active)) { event.preventDefault() - void manager.active.cancel() + void manager.active?.cancel() return } const action = shortcuts.action(event) diff --git a/src/components/BottomBar.vue b/src/components/BottomBar.vue index 6eebc10..7e4cc42 100644 --- a/src/components/BottomBar.vue +++ b/src/components/BottomBar.vue @@ -13,15 +13,15 @@ defineProps<{ session: Session }>() {{ session.error }} - {{ session.busy ? 'Working…' : session.status }} + {{ session.busy ? session.busyText : session.status }} diff --git a/src/components/QueryView.vue b/src/components/QueryView.vue index 4735698..e618f4e 100644 --- a/src/components/QueryView.vue +++ b/src/components/QueryView.vue @@ -165,7 +165,11 @@ function useHistory(sql: string): void { showHistory.value = false } -function closeHistory(): void { +function closeHistory(event: Event): void { + if (showHistory.value) { + // This Escape had a job. It does not also stop a backup. + shortcuts.claim(event) + } showHistory.value = false } @@ -361,14 +365,14 @@ watch(sessionPlan, showPlanTab) {{ session.error }}