diff --git a/CLAUDE.md b/CLAUDE.md index 696cceb..388128e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -106,6 +106,13 @@ Constants are in `constants/mod.rs`. Errors are `AppError` (`error.rs`), which r 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`). + - PostgreSQL only (`PgToolDialog.vue`): the user picks plain SQL or custom format (`--format=custom`, a + `.dump` file) and the pg_dump version. `DumpRepository::pg_tools` lists the installed versions + (`--version`). The default is the server version (`SHOW server_version_num`), else the newest. + - `restore_dump` loads a `.dump` file with `pg_restore --no-owner --no-privileges` into the current + database, optionally with `--clean --if-exists`. It uses the same progress, cancel map and `DumpLog`. + pg_restore goes on after errors; the error then counts them. The SQL import sends a file that starts + with `PGDMP` to the restore dialog. - **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/src/commands.rs b/src-tauri/src/commands.rs index bd59eeb..090b04e 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -10,11 +10,11 @@ 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, - DumpProgress, ExportRequest, NewColumn, NewForeignKey, NewIndex, NewUser, Notes, QueryPlan, - QueryStat, ResultSet, RowUpdate, RowsExport, RowsSql, SaveResult, SchemaChange, SyncSql, - TableKeys, TablePage, TableRef, UserList, Values, + AccessLevel, AiOptions, Attachment, BackupOptions, BrowseRequest, ClaudeReply, ColumnInfo, + ColumnSpec, ConnectionConfig, CsvImport, CsvPreview, DataDiff, DataKinds, DbObject, DbProcess, + Diagram, DumpProgress, ExportRequest, NewColumn, NewForeignKey, NewIndex, NewUser, Notes, + PgTools, QueryPlan, QueryStat, RestoreOptions, ResultSet, RowUpdate, RowsExport, RowsSql, + SaveResult, SchemaChange, SyncSql, TableKeys, TablePage, TableRef, UserList, Values, }; use crate::open_file::OpenedFiles; use crate::repository::PasswordRepository; @@ -374,10 +374,11 @@ pub async fn dump_database( service: Service<'_>, id: String, path: PathBuf, + options: BackupOptions, progress: Channel, ) -> AppResult<()> { service - .dump_database(&id, &path, |step| { + .dump_database(&id, &path, &options, |step| { // The page may be gone. The backup goes on anyway. let _ = progress.send(step); }) @@ -389,6 +390,32 @@ pub fn cancel_dump(service: Service<'_>, id: String) { service.cancel_dump(&id); } +#[tauri::command] +pub async fn restore_dump( + service: Service<'_>, + id: String, + path: PathBuf, + options: RestoreOptions, + progress: Channel, +) -> AppResult<()> { + service + .restore_dump(&id, &path, &options, |step| { + // The page may be gone. The restore goes on anyway. + let _ = progress.send(step); + }) + .await +} + +#[tauri::command] +pub async fn pg_tools(service: Service<'_>, id: String, restore: bool) -> AppResult { + service.pg_tools(&id, restore).await +} + +#[tauri::command] +pub fn is_custom_dump(path: PathBuf) -> AppResult { + ConnectionService::is_custom_dump(&path) +} + #[tauri::command] pub async fn export_tables( service: Service<'_>, diff --git a/src-tauri/src/constants/mod.rs b/src-tauri/src/constants/mod.rs index 83dafbd..b5fba1a 100644 --- a/src-tauri/src/constants/mod.rs +++ b/src-tauri/src/constants/mod.rs @@ -71,7 +71,31 @@ pub const TOOL_DIRS: [&str; 8] = [ ]; /// Homebrew keeps each `PostgreSQL` version in a folder like `postgresql@16` in here. -pub const HOMEBREW_OPT_DIR: &str = "/opt/homebrew/opt"; +/// The first is Apple silicon, the second Intel. +pub const HOMEBREW_OPT_DIRS: [&str; 2] = ["/opt/homebrew/opt", "/usr/local/opt"]; + +/// Postgres.app keeps each version in a folder like `17` in here. +pub const POSTGRES_APP_VERSIONS_DIR: &str = "/Applications/Postgres.app/Contents/Versions"; + +/// Debian and Ubuntu keep each `PostgreSQL` version in a folder like `17` in here. +pub const LINUX_POSTGRES_DIR: &str = "/usr/lib/postgresql"; + +/// RHEL and Fedora keep each `PostgreSQL` version in a folder like `/usr/pgsql-17`. +pub const RHEL_POSTGRES_PARENT: &str = "/usr"; + +/// The first bytes of a custom format file of `pg_dump`. Only `pg_restore` reads it. +pub const PG_CUSTOM_MAGIC: &[u8; 5] = b"PGDMP"; + +/// The error when a custom format file of `pg_dump` is opened as a SQL file. +pub const PG_CUSTOM_DUMP: &str = + "This file is a pg_dump custom archive, not SQL. Use Restore from .dump… to load it"; + +/// The same error on a database that is not `PostgreSQL`. It has no restore. +pub const PG_CUSTOM_DUMP_ELSEWHERE: &str = "This file is a PostgreSQL custom backup, not SQL. \ + It can only be restored into a PostgreSQL database"; + +/// The error when a restore runs on a database that is not `PostgreSQL`. +pub const RESTORE_ONLY_POSTGRES: &str = "Restore from .dump works only with PostgreSQL"; /// The Windows flag `CREATE_NO_WINDOW`. A tool started with it opens no console window. pub const CREATE_NO_WINDOW: u32 = 0x0800_0000; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 187f64e..a8bfebf 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -96,6 +96,9 @@ pub fn run() { commands::drop_object, commands::dump_database, commands::cancel_dump, + commands::restore_dump, + commands::pg_tools, + commands::is_custom_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 085b49d..fa4f228 100644 --- a/src-tauri/src/model.rs +++ b/src-tauri/src/model.rs @@ -521,6 +521,46 @@ pub struct DumpProgress { pub tables: usize, } +/// How to back up a `PostgreSQL` database. Other databases ignore it. +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct BackupOptions { + /// True for the custom format of `pg_dump`, which `pg_restore` reads. Else plain SQL. + pub custom: bool, + /// The major version of `pg_dump` to use. None means the default one. + pub version: Option, +} + +/// How to load a `pg_restore` file into the current database. +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct RestoreOptions { + /// The major version of `pg_restore` to use. None means the default one. + pub version: Option, + /// Drop each object before it is made again (`--clean --if-exists`). + pub clean: bool, +} + +/// A `pg_dump` or `pg_restore` that is installed on this computer. +#[derive(Clone, Debug, Serialize, PartialEq, Eq)] +pub struct PgTool { + /// The major version, like 17. + pub version: u32, + pub path: PathBuf, +} + +/// The versions of one `PostgreSQL` tool on this computer, and the one to use by default. +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PgTools { + /// The major version of the server, like 17. + pub server: u32, + /// Newest first. + pub tools: Vec, + /// The tool with the version of the server, else the newest one. None when none was found. + pub default_version: Option, +} + /// 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 155f89a..cfa82c0 100644 --- a/src-tauri/src/repository/dump.rs +++ b/src-tauri/src/repository/dump.rs @@ -1,10 +1,12 @@ //! Backups. We run the dump tool of each database: `mysqldump`, `pg_dump` and `sqlite3`. //! //! The tools know every detail of their own database, so the dump can be loaded again. +//! A custom format file of `PostgreSQL` is loaded again with `pg_restore`. -use std::collections::VecDeque; +use std::collections::{HashSet, VecDeque}; use std::ffi::OsString; use std::fs::File; +use std::io::Read as _; use std::path::{Path, PathBuf}; use std::process::Stdio; use std::sync::atomic::{AtomicU64, Ordering}; @@ -16,12 +18,15 @@ use tokio::process::Command; use crate::constants::{ BACKUP_CANCELLED, DUMP_PROGRESS_EVERY, MSSQL_NO_BACKUP, MYSQL_PASSWORD_ENV, - PARTIAL_DUMP_SUFFIX, POSTGRES_PASSWORD_ENV, + PARTIAL_DUMP_SUFFIX, PG_CUSTOM_MAGIC, POSTGRES_PASSWORD_ENV, RESTORE_ONLY_POSTGRES, }; #[cfg(unix)] -use crate::constants::{HOMEBREW_OPT_DIR, TOOL_DIRS}; +use crate::constants::{ + HOMEBREW_OPT_DIRS, LINUX_POSTGRES_DIR, POSTGRES_APP_VERSIONS_DIR, RHEL_POSTGRES_PARENT, + TOOL_DIRS, +}; use crate::error::{AppError, AppResult}; -use crate::model::{ConnectionConfig, Driver, DumpProgress}; +use crate::model::{BackupOptions, ConnectionConfig, Driver, DumpProgress, PgTool, RestoreOptions}; /// Writes SQL dumps with the dump tools that are installed on this computer. pub struct DumpRepository; @@ -37,6 +42,7 @@ impl DumpRepository { pub async fn dump( config: &ConnectionConfig, path: &Path, + options: &BackupOptions, progress: impl FnMut(DumpProgress), cancel: AbortRegistration, ) -> AppResult<()> { @@ -47,7 +53,10 @@ impl DumpRepository { // half file, and does not harm an older backup that is already at `path`. let partial = Self::partial_path(path); - let mut result = Self::run(config, &partial, progress, cancel).await; + let mut result = match Self::command(config, &partial, options).await { + Ok(command) => Self::run(command, &partial, DumpLog::default(), progress, cancel).await, + Err(error) => Err(error), + }; if result.is_ok() { result = std::fs::rename(&partial, path).map_err(AppError::from); } @@ -71,19 +80,173 @@ impl DumpRepository { PathBuf::from(partial) } - /// Runs the dump tool and waits for it. Its error text becomes our error. - async fn run( + /// Loads a custom format file of `pg_dump` into the current database with `pg_restore`. + /// + /// `pg_restore` goes on after an error. The restore then fails with the error lines + /// and how many there were. Progress and cancel work like in `dump`. A cancel leaves + /// what was loaded so far. + pub async fn restore( + config: &ConnectionConfig, + file: &Path, + options: &RestoreOptions, + progress: impl FnMut(DumpProgress), + cancel: AbortRegistration, + ) -> AppResult<()> { + if config.driver != Driver::Postgres { + return Err(RESTORE_ONLY_POSTGRES.into()); + } + if config.database.is_empty() { + return Err("Choose a database first".into()); + } + let tool = Self::pg_tool("pg_restore", options.version).await?; + let command = Self::restore_command(&tool, config, file, options.clean); + Self::run(command, file, DumpLog::restore(), progress, cancel).await + } + + /// True when the file starts like a custom format file of `pg_dump`. + pub fn is_custom_dump(path: &Path) -> AppResult { + let mut start = [0; PG_CUSTOM_MAGIC.len()]; + // A file shorter than that is no custom dump. + Ok(File::open(path)?.read_exact(&mut start).is_ok() && &start == PG_CUSTOM_MAGIC) + } + + /// All versions of `name` (`pg_dump` or `pg_restore`) on this computer, newest first. + /// One tool per version: the first one found wins. + pub async fn pg_tools(name: &str) -> Vec { + let file = format!("{name}{}", std::env::consts::EXE_SUFFIX); + let mut seen = HashSet::new(); + let mut tools: Vec = Vec::new(); + for folder in Self::folders() { + let path = folder.join(&file); + // PATH, Homebrew and Postgres.app often link to the same file. + let Ok(real) = path.canonicalize() else { + continue; + }; + if !real.is_file() || !seen.insert(real) { + continue; + } + if let Some(version) = Self::major_version(&path).await + && !tools.iter().any(|tool| tool.version == version) + { + tools.push(PgTool { version, path }); + } + } + tools.sort_by_key(|tool| std::cmp::Reverse(tool.version)); + tools + } + + /// The version to use by default: the one of the server, else the newest one. + pub fn default_version(server: u32, tools: &[PgTool]) -> Option { + tools + .iter() + .find(|tool| tool.version == server) + .or(tools.first()) + .map(|tool| tool.version) + } + + /// The tool `name` with this major version. None means the first one found. + async fn pg_tool(name: &str, version: Option) -> AppResult { + let Some(version) = version else { + return Self::find(&[name]).ok_or_else(|| { + AppError::Message(format!( + "{name} was not found. Install the PostgreSQL client tools (macOS: brew install libpq)" + )) + }); + }; + Self::pg_tools(name) + .await + .into_iter() + .find(|tool| tool.version == version) + .map(|tool| tool.path) + .ok_or_else(|| AppError::Message(format!("{name} {version} was not found"))) + } + + /// The major version a tool prints with `--version`. None when it does not run. + async fn major_version(tool: &Path) -> Option { + let mut command = Command::new(tool); + super::hide_console(&mut command); + let output = command + .arg("--version") + .stdin(Stdio::null()) + .output() + .await + .ok()?; + Self::parse_major(&String::from_utf8_lossy(&output.stdout)) + } + + /// The major version in text like `pg_dump (PostgreSQL) 17.2 (Homebrew)`. + fn parse_major(text: &str) -> Option { + let word = text + .split_whitespace() + .find(|word| word.starts_with(|c: char| c.is_ascii_digit()))?; + let digits: String = word.chars().take_while(char::is_ascii_digit).collect(); + digits.parse().ok() + } + + /// The `pg_restore` command. The password goes in the environment, never in an argument. + fn restore_command( + tool: &Path, + config: &ConnectionConfig, + file: &Path, + clean: bool, + ) -> Command { + let mut command = Command::new(tool); + command + .arg(format!("--host={}", config.host)) + .arg(format!("--port={}", config.port)) + .arg("--no-password") + .arg("--verbose") + .arg(Self::dbname(&config.database)) + // The objects belong to the user of this connection, with no grants of + // the old server. Its roles may not exist here. + .arg("--no-owner") + .arg("--no-privileges") + .stdout(Stdio::null()); + if clean { + command.arg("--clean").arg("--if-exists"); + } + if !config.user.is_empty() { + command.arg(format!("--username={}", config.user)); + } + if !config.password.is_empty() { + command.env(POSTGRES_PASSWORD_ENV, &config.password); + } + // "--" ends the options. A file name can then never be read as one. + command.arg("--").arg(file); + command + } + + /// The `--dbname` option of `pg_dump` and `pg_restore`. They read a value with `=` or + /// `postgresql://` as a whole connection string, which could name another host and get + /// our password. So the name always goes in as `dbname='…'`, with `\` and `'` escaped. + fn dbname(database: &str) -> String { + let quoted = database.replace('\\', "\\\\").replace('\'', "\\'"); + format!("--dbname=dbname='{quoted}'") + } + + /// The dump command of the database. + async fn command( config: &ConnectionConfig, output: &Path, + options: &BackupOptions, + ) -> AppResult { + match config.driver { + Driver::Mysql => Self::mysql(config, output).await, + Driver::Postgres => Self::postgres(config, output, options).await, + Driver::Sqlite => Self::sqlite(config, output), + Driver::Mssql => Err(MSSQL_NO_BACKUP.into()), + } + } + + /// Runs the tool and waits for it. Its error text becomes our error. + /// `file` is the file whose size the progress shows. + async fn run( + mut command: Command, + file: &Path, + mut log: DumpLog, 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)?, - Driver::Sqlite => Self::sqlite(config, output)?, - Driver::Mssql => return Err(MSSQL_NO_BACKUP.into()), - }; super::hide_console(&mut command); command .stdin(Stdio::null()) @@ -96,7 +259,6 @@ impl DumpRepository { .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); @@ -114,12 +276,12 @@ impl DumpRepository { line = lines.next_segment() => match line? { Some(line) => { if log.read(&String::from_utf8_lossy(&line)) { - progress(log.progress(output, started)); + progress(log.progress(file, started)); } } None => break, }, - _ = tick.tick() => progress(log.progress(output, started)), + _ = tick.tick() => progress(log.progress(file, started)), } } let status = child.wait().await?; @@ -176,10 +338,16 @@ impl DumpRepository { Ok(command) } - fn postgres(config: &ConnectionConfig, output: &Path) -> AppResult { - let tool = Self::find(&["pg_dump"]) - .ok_or("pg_dump was not found. Install the PostgreSQL client tools (macOS: brew install libpq)")?; + async fn postgres( + config: &ConnectionConfig, + output: &Path, + options: &BackupOptions, + ) -> AppResult { + let tool = Self::pg_tool("pg_dump", options.version).await?; let mut command = Command::new(tool); + if options.custom { + command.arg("--format=custom"); + } command .arg(format!("--host={}", config.host)) .arg(format!("--port={}", config.port)) @@ -192,7 +360,7 @@ impl DumpRepository { command.arg(format!("--username={}", config.user)); } if !config.database.is_empty() { - command.arg(format!("--dbname={}", config.database)); + command.arg(Self::dbname(&config.database)); } if !config.password.is_empty() { command.env(POSTGRES_PASSWORD_ENV, &config.password); @@ -262,22 +430,38 @@ impl DumpRepository { for folder in TOOL_DIRS { folders.push(PathBuf::from(folder)); } - // ponytail: any Homebrew PostgreSQL version, in no fixed order. pg_dump - // refuses a server that is newer than itself; pick the newest if that hurts. - if let Ok(entries) = std::fs::read_dir(HOMEBREW_OPT_DIR) { - for entry in entries.flatten() { - if entry - .file_name() - .to_string_lossy() - .starts_with("postgresql@") - { - folders.push(entry.path().join("bin")); - } + // Each PostgreSQL version that is installed. The user picks one in the app. + for homebrew in HOMEBREW_OPT_DIRS { + for prefix in ["postgresql@", "libpq@"] { + folders.extend(Self::bin_folders(Path::new(homebrew), prefix)); } } + folders.extend(Self::bin_folders(Path::new(POSTGRES_APP_VERSIONS_DIR), "")); + folders.extend(Self::bin_folders(Path::new(LINUX_POSTGRES_DIR), "")); + folders.extend(Self::bin_folders(Path::new(RHEL_POSTGRES_PARENT), "pgsql-")); + } + // The installer of PostgreSQL for Windows. An absolute folder, so it is safe. + #[cfg(windows)] + { + if let Some(programs) = std::env::var_os("ProgramFiles") { + let installs = Path::new(&programs).join("PostgreSQL"); + folders.extend(Self::bin_folders(&installs, "")); + } } folders } + + /// The `bin` folder of each folder in `parent` whose name starts with `prefix`. + fn bin_folders(parent: &Path, prefix: &str) -> Vec { + let Ok(entries) = std::fs::read_dir(parent) else { + return Vec::new(); + }; + entries + .flatten() + .filter(|entry| entry.file_name().to_string_lossy().starts_with(prefix)) + .map(|entry| entry.path().join("bin")) + .collect() + } } /// The error output of a dump tool. With `--verbose` it names each table it starts. @@ -290,9 +474,21 @@ struct DumpLog { tail: VecDeque, table: Option, tables: usize, + /// True for `pg_restore`. Its error lines are followed by the SQL that failed. + restore: bool, + /// The count in `pg_restore: warning: errors ignored on restore: N`. `pg_restore` prints it + /// only when it went on after errors. A fatal error has no such line. + ignored: Option, } impl DumpLog { + fn restore() -> Self { + Self { + restore: true, + ..Self::default() + } + } + /// 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; @@ -312,7 +508,13 @@ impl DumpLog { self.tables += 1; return true; } - if !Self::is_chatter(line) && self.errors.len() < Self::MAX_ERRORS { + if let Some(count) = line.strip_prefix("pg_restore: warning: errors ignored on restore: ") { + self.ignored = count.trim().parse().ok(); + } + // The SQL after a pg_restore error can be long. Only its first line stays. + let shown = + !self.restore || line.starts_with("pg_restore: ") || line.starts_with("Command was: "); + if shown && !Self::is_chatter(line) && self.errors.len() < Self::MAX_ERRORS { self.errors.push(line.to_owned()); } false @@ -320,10 +522,17 @@ impl DumpLog { /// The error text when the tool failed. fn reason(&self) -> String { - if self.errors.is_empty() { + let lines = if self.errors.is_empty() { Vec::from(self.tail.clone()).join("\n") } else { self.errors.join("\n") + }; + match self.ignored { + None | Some(0) => lines, + Some(1) => format!("pg_restore had 1 error. The rest was restored.\n{lines}"), + Some(count) => { + format!("pg_restore had {count} errors. The rest was restored.\n{lines}") + } } } @@ -338,11 +547,15 @@ impl DumpLog { } /// The table a line names, like `-- Retrieving table structure for table orders...` - /// (mysqldump) or `pg_dump: dumping contents of table "public.orders"`. + /// (mysqldump), `pg_dump: dumping contents of table "public.orders"` or + /// `pg_restore: processing data for 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 if let Some(rest) = line.strip_prefix("pg_restore: ") { + rest.strip_prefix("processing data for table ")? + .trim_matches('"') } else { line.strip_prefix("pg_dump: ")? .strip_prefix("dumping contents of table ")? @@ -356,7 +569,10 @@ impl DumpLog { if line.starts_with("-- ") { return true; } - line.strip_prefix("pg_dump: ").is_some_and(|rest| { + let rest = line + .strip_prefix("pg_dump: ") + .or_else(|| line.strip_prefix("pg_restore: ")); + rest.is_some_and(|rest| { !["error:", "detail:", "hint:", "warning:"] .iter() .any(|kind| rest.starts_with(kind)) @@ -373,7 +589,7 @@ mod tests { use super::{DumpLog, DumpRepository}; use crate::constants::BACKUP_CANCELLED; - use crate::model::{ConnectionConfig, Driver, SslConfig}; + use crate::model::{BackupOptions, ConnectionConfig, Driver, PgTool, SslConfig}; #[tokio::test] async fn a_cancel_leaves_the_older_backup_alone() { @@ -412,7 +628,8 @@ mod tests { steps += 1; handle.abort(); }; - let result = DumpRepository::dump(&config, &path, cancel, registration).await; + let options = BackupOptions::default(); + let result = DumpRepository::dump(&config, &path, &options, cancel, registration).await; let old = std::fs::read_to_string(&path); let partial = std::fs::read_dir(&folder) .expect("temp folder") @@ -482,4 +699,159 @@ mod tests { mysqldump: Got error: 1045: Access denied for user 'me'" ); } + + fn postgres(password: &str) -> ConnectionConfig { + ConnectionConfig { + driver: Driver::Postgres, + host: "127.0.0.1".to_owned(), + port: 5433, + user: "me".to_owned(), + password: password.to_owned(), + database: "shop".to_owned(), + ssh: None, + ssl: SslConfig::default(), + } + } + + #[test] + fn reads_the_major_version_of_the_tools() { + let parse = DumpRepository::parse_major; + assert_eq!(parse("pg_dump (PostgreSQL) 17.2\n"), Some(17)); + assert_eq!(parse("pg_restore (PostgreSQL) 15.10 (Homebrew)"), Some(15)); + assert_eq!(parse("pg_dump (PostgreSQL) 18beta1"), Some(18)); + assert_eq!(parse("pg_dump (PostgreSQL) 9.6.24"), Some(9)); + assert_eq!(parse("command not found"), None); + assert_eq!(parse(""), None); + } + + #[test] + fn the_default_version_is_the_one_of_the_server() { + let tool = |version| PgTool { + version, + path: format!("/pg{version}/pg_dump").into(), + }; + let tools = [tool(18), tool(17), tool(15)]; + assert_eq!(DumpRepository::default_version(17, &tools), Some(17)); + // No tool of the server version: the newest one. + assert_eq!(DumpRepository::default_version(16, &tools), Some(18)); + assert_eq!(DumpRepository::default_version(17, &[]), None); + } + + #[test] + fn the_restore_password_is_never_an_argument() { + let file = Path::new("/backups/-shop.dump"); + let tool = Path::new("pg_restore"); + let command = DumpRepository::restore_command(tool, &postgres("s3cret"), file, true); + let args: Vec<_> = command + .as_std() + .get_args() + .map(|arg| arg.to_string_lossy().into_owned()) + .collect(); + assert_eq!( + args, + [ + "--host=127.0.0.1", + "--port=5433", + "--no-password", + "--verbose", + "--dbname=dbname='shop'", + "--no-owner", + "--no-privileges", + "--clean", + "--if-exists", + "--username=me", + "--", + "/backups/-shop.dump", + ] + ); + assert!(args.iter().all(|arg| !arg.contains("s3cret"))); + let password = command + .as_std() + .get_envs() + .find(|(name, _)| *name == "PGPASSWORD") + .and_then(|(_, value)| value); + assert_eq!(password, Some(OsStr::new("s3cret"))); + // Without clean and without a password. + let command = DumpRepository::restore_command(tool, &postgres(""), file, false); + let args: Vec<_> = command.as_std().get_args().collect(); + assert!(!args.contains(&OsStr::new("--clean"))); + assert_eq!(command.as_std().get_envs().count(), 0); + } + + #[test] + fn a_database_name_is_never_a_connection_string() { + let dbname = DumpRepository::dbname; + assert_eq!(dbname("shop"), "--dbname=dbname='shop'"); + assert_eq!( + dbname("x host=evil.example"), + "--dbname=dbname='x host=evil.example'" + ); + assert_eq!( + dbname("postgresql://evil.example/x"), + "--dbname=dbname='postgresql://evil.example/x'" + ); + // A quote or backslash cannot end the value early. + assert_eq!( + dbname(r"it's' host=evil \"), + r"--dbname=dbname='it\'s\' host=evil \\'" + ); + } + + #[test] + fn knows_a_custom_dump_by_its_first_bytes() { + let folder = std::env::temp_dir(); + let id = std::process::id(); + let custom = folder.join(format!("sqlpro-magic-{id}.dump")); + let plain = folder.join(format!("sqlpro-magic-{id}.sql")); + let short = folder.join(format!("sqlpro-magic-{id}.short")); + std::fs::write(&custom, b"PGDMP\x01\x0e\x00").expect("custom"); + std::fs::write(&plain, "-- PostgreSQL database dump\n").expect("plain"); + std::fs::write(&short, "PG").expect("short"); + let found = [&custom, &plain, &short].map(|path| DumpRepository::is_custom_dump(path)); + for path in [&custom, &plain, &short] { + let _ = std::fs::remove_file(path); + } + assert_eq!( + found.map(|found| found.expect("read")), + [true, false, false] + ); + } + + #[test] + fn a_fatal_pg_restore_error_does_not_say_the_rest_was_restored() { + for fatal in [ + "pg_restore: error: connection to server at \"127.0.0.1\", port 5433 failed: \ + FATAL: password authentication failed for user \"me\"", + "pg_restore: error: unsupported version (1.16) in file header", + ] { + let mut log = DumpLog::restore(); + log.read(fatal); + assert_eq!(log.reason(), fatal); + } + } + + #[test] + fn counts_the_errors_of_pg_restore() { + let mut log = DumpLog::restore(); + assert!(!log.read("pg_restore: connecting to database for restore")); + assert!(!log.read(r#"pg_restore: creating TABLE "public.orders""#)); + assert!(log.read(r#"pg_restore: processing data for table "public.orders""#)); + assert_eq!(log.table.as_deref(), Some("public.orders")); + log.read(r#"pg_restore: error: could not execute query: ERROR: relation "orders" already exists"#); + log.read("Command was: CREATE TABLE public.orders ("); + log.read(" id integer NOT NULL"); + log.read(");"); + log.read( + r#"pg_restore: error: could not execute query: ERROR: role "old" does not exist"#, + ); + log.read("pg_restore: warning: errors ignored on restore: 2"); + assert_eq!( + log.reason(), + "pg_restore had 2 errors. The rest was restored.\n\ + pg_restore: error: could not execute query: ERROR: relation \"orders\" already exists\n\ + Command was: CREATE TABLE public.orders (\n\ + pg_restore: error: could not execute query: ERROR: role \"old\" does not exist\n\ + pg_restore: warning: errors ignored on restore: 2" + ); + } } diff --git a/src-tauri/src/service.rs b/src-tauri/src/service.rs index f00bb34..579d155 100644 --- a/src-tauri/src/service.rs +++ b/src-tauri/src/service.rs @@ -18,7 +18,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use futures_util::future::{AbortHandle, Abortable}; +use futures_util::future::{AbortHandle, AbortRegistration, Abortable}; use parking_lot::Mutex; use crate::constants::{ @@ -30,11 +30,11 @@ use crate::constants::{ }; use crate::error::{AppError, AppResult}; use crate::model::{ - AccessLevel, AiOptions, Attachment, BrowseRequest, ClaudeReply, ColumnInfo, ColumnSpec, - 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, + AccessLevel, AiOptions, Attachment, BackupOptions, BrowseRequest, ClaudeReply, ColumnInfo, + ColumnSpec, ConnectionConfig, DbObject, DbUser, Diagram, DiagramTable, Driver, DumpProgress, + ExportRequest, FilterOperator, FilterRule, ForeignKey, IndexInfo, NewColumn, NewForeignKey, + NewIndex, NewUser, Notes, PgTools, RestoreOptions, ResultSet, RowUpdate, RowsExport, RowsSql, + SaveResult, TableKeys, TablePage, TableRef, UserList, Values, }; use crate::repository::{ ClaudeCli, DumpRepository, Repository, RepositoryFactory, SshTunnel, Statement, create_start, @@ -575,28 +575,84 @@ impl ConnectionService { &self, id: &str, path: &Path, + options: &BackupOptions, 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; + let config = Self::tool_config(&connection); + let registration = self.start_tool(id)?; + let result = DumpRepository::dump(&config, path, options, progress, registration).await; + self.dumping.lock().remove(id); + result + } + + /// Loads a `pg_restore` file into the current database. Progress and cancel work like + /// in `dump_database`, and a backup and a restore never run at once in one tab. + pub async fn restore_dump( + &self, + id: &str, + path: &Path, + options: &RestoreOptions, + progress: impl FnMut(DumpProgress), + ) -> AppResult<()> { + let connection = self.connection(id)?; + let config = Self::tool_config(&connection); + let registration = self.start_tool(id)?; + let result = DumpRepository::restore(&config, path, options, progress, registration).await; + self.dumping.lock().remove(id); + result + } + + /// The `pg_dump` (or with `restore`, `pg_restore`) versions on this computer, and the + /// one that fits the server of the tab. + pub async fn pg_tools(&self, id: &str, restore: bool) -> AppResult { + let repository = self.repository(id)?; + let sets = repository.query("SHOW server_version_num").await?; + let number = sets + .first() + .and_then(|set| set.rows.first()) + .and_then(|row| row.first().cloned().flatten()) + .and_then(|text| text.trim().parse::().ok()) + .ok_or("The server did not tell its version")?; + // Like 170002 for 17.2. Before version 10 it was like 90624 for 9.6.24. + let server = number / 10_000; + let tools = DumpRepository::pg_tools(if restore { "pg_restore" } else { "pg_dump" }).await; + let default_version = DumpRepository::default_version(server, &tools); + Ok(PgTools { + server, + tools, + default_version, + }) + } + + /// True when the file is a custom format file of `pg_dump`, for `pg_restore`. + pub fn is_custom_dump(path: &Path) -> AppResult { + DumpRepository::is_custom_dump(path) + } + + /// The login of a tab for a dump tool. With an SSH tunnel it goes through the same + /// tunnel as the tab. The tunnel stays open while `connection` lives. + fn tool_config(connection: &Connection) -> ConnectionConfig { + let mut config = connection.config.clone(); if let Some(tunnel) = &connection.tunnel { - // Go through the same tunnel as the tab. LOCALHOST.clone_into(&mut config.host); config.port = tunnel.local_port(); } + config + } + + /// Notes that a dump tool runs in tab `id`, so `cancel_dump` can stop it. + /// The caller removes the entry when the tool ends. + fn start_tool(&self, id: &str) -> AppResult { 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 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()); } - let result = DumpRepository::dump(&config, path, progress, registration).await; - self.dumping.lock().remove(id); - result + dumping.insert(id.to_owned(), handle); + Ok(registration) } /// Stops the backup that runs now for `id`. It then fails with `BACKUP_CANCELLED`. diff --git a/src-tauri/src/service/import.rs b/src-tauri/src/service/import.rs index de01dd3..8c07391 100644 --- a/src-tauri/src/service/import.rs +++ b/src-tauri/src/service/import.rs @@ -2,10 +2,10 @@ use std::path::Path; -use crate::constants::CSV_PREVIEW_ROWS; +use crate::constants::{CSV_PREVIEW_ROWS, PG_CUSTOM_DUMP, PG_CUSTOM_DUMP_ELSEWHERE}; use crate::error::{AppError, AppResult}; use crate::model::{CsvImport, CsvPreview, Driver, Values}; -use crate::repository::Statement; +use crate::repository::{DumpRepository, Statement}; use super::ConnectionService; @@ -65,6 +65,15 @@ impl ConnectionService { /// Gives the number of statements. pub async fn import_sql(&self, id: &str, path: &Path) -> AppResult { let connection = self.connection(id)?; + // Not text. Only pg_restore can read it. + if DumpRepository::is_custom_dump(path)? { + return Err(if connection.config.driver == Driver::Postgres { + PG_CUSTOM_DUMP + } else { + PG_CUSTOM_DUMP_ELSEWHERE + } + .into()); + } let sql = std::fs::read_to_string(path)?; let statements = SqlSplitter::new(&sql, connection.config.driver == Driver::Mysql).split(); if statements.is_empty() { diff --git a/src-tauri/tests/service.rs b/src-tauri/tests/service.rs index 832b0c2..c498719 100644 --- a/src-tauri/tests/service.rs +++ b/src-tauri/tests/service.rs @@ -9,10 +9,11 @@ use sql_pro_lib::model::DbObject; use sql_pro_lib::model::{ - AccessLevel, BrowseRequest, ColumnSpec, ConnectionConfig, CsvColumn, CsvImport, DataKinds, - DbUser, Diagram, Driver, ExportFormat, ExportRequest, FilterOperator, FilterRule, ForeignKey, - IndexInfo, NewColumn, NewForeignKey, NewIndex, NewUser, PlanMeasure, ReferentialAction, - Relation, RowUpdate, RowsExport, RowsSql, SaveResult, SshConfig, TableRef, Values, + AccessLevel, BackupOptions, BrowseRequest, ColumnSpec, ConnectionConfig, CsvColumn, CsvImport, + DataKinds, DbUser, Diagram, Driver, ExportFormat, ExportRequest, FilterOperator, FilterRule, + ForeignKey, IndexInfo, NewColumn, NewForeignKey, NewIndex, NewUser, PlanMeasure, + ReferentialAction, Relation, RestoreOptions, RowUpdate, RowsExport, RowsSql, SaveResult, + SshConfig, TableRef, Values, }; use std::time::{Duration, Instant}; @@ -990,7 +991,7 @@ 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, drop) + .dump_database(ID, &path, &BackupOptions::default(), drop) .await .expect_err("no backup"); assert!(error.to_string().contains("not supported"), "{error}"); @@ -999,7 +1000,9 @@ async fn dump(service: &ConnectionService, driver: Driver, database: &str) { } let mut steps = Vec::new(); match service - .dump_database(ID, &path, |step| steps.push(step)) + .dump_database(ID, &path, &BackupOptions::default(), |step| { + steps.push(step); + }) .await { Err(error) if error.to_string().contains("was not found") => { @@ -1012,6 +1015,7 @@ async fn dump(service: &ConnectionService, driver: Driver, database: &str) { if driver == Driver::Postgres { assert!(sql.contains("FROM stdin;"), "the dump has COPY rows"); restore(service, &path, database).await; + pg_restore(service, database).await; } std::fs::remove_file(&path).expect("remove dump"); assert!( @@ -1040,7 +1044,12 @@ async fn dump(service: &ConnectionService, driver: Driver, database: &str) { // 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, drop).await.is_err()); + assert!( + service + .dump_database(ID, &missing, &BackupOptions::default(), drop) + .await + .is_err() + ); assert!(!missing.exists()); assert!(!folder.join("sqlpro-no-such-folder").exists()); } @@ -1077,6 +1086,94 @@ async fn restore(service: &ConnectionService, path: &std::path::Path, back: &str .expect("drop restore database"); } +/// Backs up the test database in the custom format, then loads it with `pg_restore` into a +/// new database. Expects the two rows that `exercise` inserts. Goes back to the test database. +async fn pg_restore(service: &ConnectionService, back: &str) { + let dumps = service.pg_tools(ID, false).await.expect("pg_dump versions"); + let restores = service + .pg_tools(ID, true) + .await + .expect("pg_restore versions"); + let (Some(dump_version), Some(restore_version)) = + (dumps.default_version, restores.default_version) + else { + println!("NOTE: the pg_restore check is skipped: pg_dump or pg_restore was not found"); + return; + }; + assert!(dumps.server >= 10, "server {}", dumps.server); + let versions: Vec = dumps.tools.iter().map(|tool| tool.version).collect(); + println!("pg_dump versions: {versions:?}, server {}", dumps.server); + assert!( + versions.windows(2).all(|pair| pair[0] > pair[1]), + "newest first" + ); + let path = temp_path("custom", "dump"); + let options = BackupOptions { + custom: true, + version: Some(dump_version), + }; + service + .dump_database(ID, &path, &options, drop) + .await + .expect("custom dump"); + assert!(ConnectionService::is_custom_dump(&path).expect("read the dump")); + // The SQL import does not run it. It says what to use. + let error = service.import_sql(ID, &path).await.expect_err("not SQL"); + assert!(error.to_string().contains("Restore from .dump"), "{error}"); + + let _ = service.drop_database(ID, RESTORED).await; + let created = service.create_database(ID, RESTORED, "", ""); + created.await.expect("create restore database"); + service + .use_database(ID, RESTORED.to_owned()) + .await + .expect("use restore database"); + let mut options = RestoreOptions { + version: Some(restore_version), + clean: false, + }; + let mut steps = Vec::new(); + service + .restore_dump(ID, &path, &options, |step| steps.push(step)) + .await + .expect("pg_restore"); + assert!( + steps + .iter() + .any(|step| step.table.as_deref() == Some(&format!("public.{TABLE}"))), + "no progress for the table" + ); + let rows = async || { + let table = listed(service, TABLE).await.expect("the restored table"); + page(service, &table).await.rows + }; + let loaded = rows().await; + assert_eq!(loaded.len(), 2); + assert_eq!(loaded[0][1].as_deref(), Some("O'Brien")); + assert_eq!(loaded[1][3].as_deref(), Some("line 1\nline 2")); + // Again: the objects are there already, so pg_restore counts its errors. + let error = service.restore_dump(ID, &path, &options, drop).await; + let error = error.expect_err("objects exist").to_string(); + assert!(error.contains("errors. The rest was restored"), "{error}"); + assert!(error.contains("already exists"), "{error}"); + // With clean, each object is dropped first. No error, and the rows are there once. + options.clean = true; + service + .restore_dump(ID, &path, &options, drop) + .await + .expect("pg_restore with clean"); + assert_eq!(rows().await.len(), 2); + std::fs::remove_file(&path).expect("remove custom dump"); + service + .use_database(ID, back.to_owned()) + .await + .expect("back to the test database"); + service + .drop_database(ID, RESTORED) + .await + .expect("drop restore database"); +} + /// Exports the test table as SQL and as CSV. Expects the two rows that `exercise` inserts. async fn export(service: &ConnectionService, table: &TableRef) { let path = temp_path("export", "sql"); diff --git a/src/components/PgToolDialog.vue b/src/components/PgToolDialog.vue new file mode 100644 index 0000000..4f17e35 --- /dev/null +++ b/src/components/PgToolDialog.vue @@ -0,0 +1,224 @@ + + + + + diff --git a/src/components/Workspace.vue b/src/components/Workspace.vue index 98fa5b5..1235c55 100644 --- a/src/components/Workspace.vue +++ b/src/components/Workspace.vue @@ -58,6 +58,7 @@ import EnvBadge from './EnvBadge.vue' import ExportDialog from './ExportDialog.vue' import ImportDialog from './ImportDialog.vue' import PaneResizer from './PaneResizer.vue' +import PgToolDialog from './PgToolDialog.vue' import QueryView from './QueryView.vue' import StructureView from './StructureView.vue' import TableDialog from './TableDialog.vue' @@ -113,6 +114,7 @@ const tableDialog = useTemplateRef>('tableDialo const databaseDialog = useTemplateRef>('databaseDialog') const exportDialog = useTemplateRef>('exportDialog') const importDialog = useTemplateRef>('importDialog') +const pgDialog = useTemplateRef>('pgDialog') const menuElement = ref(null) const filteredTables = computed(matchingTables) const groups = computed(tableGroups) @@ -462,13 +464,19 @@ async function importCsv(table: TableRef): Promise { async function importSql(): Promise { closeMenu() const session = props.session + const postgres = isPostgres() const path = await open({ title: 'Import SQL file', - filters: [{ name: 'SQL', extensions: ['sql'] }], + filters: [{ name: 'SQL', extensions: postgres ? ['sql', 'dump'] : ['sql'] }], }) if (!path) { return } + // A custom format file of pg_dump is not SQL. pg_restore loads it. + if (postgres && (await isCustomDump(path))) { + await pgDialog.value?.openRestore(path) + return + } const sure = await confirm( `Run all statements in ${path} on database "${databaseLabel()}"? This can change or delete data.`, { title: 'Import SQL file', kind: 'warning' }, @@ -478,6 +486,34 @@ async function importSql(): Promise { } } +/** False when the file cannot be read. The SQL import then shows the error. */ +async function isCustomDump(path: string): Promise { + try { + return await props.session.isCustomDump(path) + } catch { + return false + } +} + +function isPostgres(): boolean { + return props.session.config?.driver === 'postgres' +} + +/** Asks for a .dump file, then opens the restore dialog for it. Does nothing on cancel. */ +async function restoreDump(): Promise { + closeMenu() + const path = await open({ + title: 'Restore from .dump', + filters: [ + { name: 'pg_dump file', extensions: ['dump', 'backup'] }, + { name: 'All files', extensions: ['*'] }, + ], + }) + if (path) { + await pgDialog.value?.openRestore(path) + } +} + /** * A click opens the table here and clears the selection. * Shift-click selects a range. Cmd-click (Ctrl on Windows and Linux) adds or removes one table. @@ -589,11 +625,22 @@ function backupButtonTitle(): string { if (backupBlocked.value) { return 'Choose a database first' } - return props.session.dumping - ? 'A backup already runs in this tab' + if (props.session.dumping) { + return props.session.restoring + ? 'A restore runs in this tab' + : 'A backup already runs in this tab' + } + return isPostgres() + ? 'Back up this database to a SQL or .dump file' : 'Back up this database to a SQL file' } +function importTitle(): string { + return isPostgres() + ? 'Import a SQL or .dump file into this database' + : 'Import a SQL file into this database' +} + /** The database name. SQLite has none, so it is the file name. */ function databaseLabel(): string { const config = props.session.config @@ -603,6 +650,11 @@ function databaseLabel(): string { /** Asks where to save, asks to confirm, then writes the SQL dump. Does nothing on cancel or no. */ async function backup(): Promise { const session = props.session + // PostgreSQL has a choice of format and pg_dump version first. + if (isPostgres()) { + await pgDialog.value?.openBackup() + return + } const path = await save({ title: 'Back up database', defaultPath: session.backupName(new Date()), @@ -706,7 +758,7 @@ async function switchDatabase(select: HTMLSelectElement): Promise { + @@ -1000,6 +1055,7 @@ async function switchDatabase(select: HTMLSelectElement): Promise { + diff --git a/src/constants/index.ts b/src/constants/index.ts index d13f634..39f50e8 100644 --- a/src/constants/index.ts +++ b/src/constants/index.ts @@ -25,6 +25,9 @@ export const QUERY_CANCELLED_STATUS = 'Query cancelled' /** The status of a tab after the user cancelled its backup. */ export const BACKUP_CANCELLED_STATUS = 'Backup cancelled' +/** The status of a tab after the user cancelled its pg_restore. */ +export const RESTORE_CANCELLED_STATUS = 'Restore cancelled. What was loaded so far stays.' + /** The note in the connection form after the user cancelled a connect. */ export const CONNECT_CANCELLED_NOTE = 'Connection cancelled.' diff --git a/src/services/DatabaseApi.ts b/src/services/DatabaseApi.ts index a9db566..9fadde3 100644 --- a/src/services/DatabaseApi.ts +++ b/src/services/DatabaseApi.ts @@ -19,6 +19,9 @@ import type { DbUser, Diagram, DumpProgress, + BackupOptions, + PgTools, + RestoreOptions, ExportRequest, NewColumn, NewForeignKey, @@ -272,15 +275,38 @@ export class DatabaseApi { return invoke('truncate_table', { id, table }) } - /** Writes a SQL dump of the current database to the file at `path`. `onProgress` gets how far it is. */ + /** Writes a dump of the current database to the file at `path`. `onProgress` gets how far it is. */ dumpDatabase( id: string, path: string, + options: BackupOptions, onProgress: (progress: DumpProgress) => void, ): Promise { const progress = new Channel() progress.onmessage = onProgress - return invoke('dump_database', { id, path, progress }) + return invoke('dump_database', { id, path, options, progress }) + } + + /** Loads a .dump file into the current database with pg_restore. Stops like a backup. */ + restoreDump( + id: string, + path: string, + options: RestoreOptions, + onProgress: (progress: DumpProgress) => void, + ): Promise { + const progress = new Channel() + progress.onmessage = onProgress + return invoke('restore_dump', { id, path, options, progress }) + } + + /** The pg_dump (or with `restore`, pg_restore) versions on this computer. */ + pgTools(id: string, restore: boolean): Promise { + return invoke('pg_tools', { id, restore }) + } + + /** True when the file is a custom format file of pg_dump, for pg_restore. */ + isCustomDump(path: string): Promise { + return invoke('is_custom_dump', { path }) } /** Stops the backup that runs now on tab `id`. It then fails with "Backup cancelled". */ diff --git a/src/services/PgToolChoice.ts b/src/services/PgToolChoice.ts new file mode 100644 index 0000000..2885ec3 --- /dev/null +++ b/src/services/PgToolChoice.ts @@ -0,0 +1,44 @@ +import type { PgTool, PgTools } from '../types' + +/** The pick of a pg_dump or pg_restore version in the backup and restore dialog. */ +export class PgToolChoice { + /** 'pg_dump' or 'pg_restore'. */ + readonly name: string + readonly server: number + /** Newest first. */ + readonly tools: PgTool[] + /** The chosen major version. null when no tool was found. */ + version: number | null + + constructor(name: string, list: PgTools) { + this.name = name + this.server = list.server + this.tools = list.tools + this.version = list.defaultVersion + } + + /** The text of one option, like `PostgreSQL 17`. */ + label(tool: PgTool): string { + return `PostgreSQL ${tool.version}` + } + + /** What to tell when no tool was found. '' when there is one. */ + get missing(): string { + if (this.tools.length > 0) { + return '' + } + return `${this.name} was not found. Install the PostgreSQL client tools (macOS: brew install libpq).` + } + + /** A warning when the chosen tool is older than the server. '' when it is fine. */ + get warning(): string { + if (this.version === null || this.version >= this.server) { + return '' + } + const what = + this.name === 'pg_dump' + ? 'pg_dump does not back up a newer server.' + : 'It may not read a file made by a newer pg_dump.' + return `${this.name} ${this.version} is older than the server (PostgreSQL ${this.server}). ${what}` + } +} diff --git a/src/services/Session.ts b/src/services/Session.ts index 8f9f5fc..75856f4 100644 --- a/src/services/Session.ts +++ b/src/services/Session.ts @@ -1,6 +1,7 @@ import { markRaw } from 'vue' import { BACKUP_CANCELLED_STATUS, + RESTORE_CANCELLED_STATUS, DELETE_ROWS_TITLE, OBJECT_KIND_LABELS, PAGE_SIZE, @@ -43,6 +44,9 @@ import type { DbUser, Diagram, DumpProgress, + BackupOptions, + PgTools, + RestoreOptions, CopyFormat, ExportFormat, ExportRequest, @@ -107,6 +111,8 @@ export class Session { dumping = false /** True after the user asked to cancel the backup. */ dumpCancelling = false + /** True when the running dump tool is pg_restore and not a backup. */ + restoring = false /** How far the running backup is, like `Backing up… 48 MB, 0:32`. '' = no backup runs. */ backupProgress = '' error = '' @@ -374,7 +380,10 @@ export class Session { /** The tooltip of the Cancel button. */ get cancelTitle(): string { - return this.cancellable ? 'Stop the running query (Esc)' : 'Stop the backup (Esc)' + if (this.cancellable) { + return 'Stop the running query (Esc)' + } + return this.restoring ? 'Stop the restore (Esc)' : 'Stop the backup (Esc)' } /** @@ -1476,23 +1485,21 @@ export class Session { } /** The file name we offer for a backup made at `now`, like `shop-2026-01-31-0905.sql`. */ - backupName(now: Date): string { + backupName(now: Date, extension = 'sql'): string { const name = this.databaseName() const day = `${now.getFullYear()}-${this.two(now.getMonth() + 1)}-${this.two(now.getDate())}` const time = `${this.two(now.getHours())}${this.two(now.getMinutes())}` - return `${name || 'backup'}-${day}-${time}.sql` + return `${name || 'backup'}-${day}-${time}.${extension}` } - /** Writes a SQL dump of the current database to the file at `path`. */ - async backup(path: string): Promise { - if (this.dumping) { - throw 'A backup already runs in this tab' - } - this.dumping = true - this.dumpCancelling = false - this.backupProgress = 'Backing up…' + /** Writes a dump of the current database to the file at `path`. Plain SQL by default. */ + async backup( + path: string, + options: BackupOptions = { custom: false, version: null }, + ): Promise { + this.startDumpTool(false) try { - await this.api.dumpDatabase(this.id, path, this.showBackupProgress.bind(this)) + await this.api.dumpDatabase(this.id, path, options, this.showBackupProgress.bind(this)) } catch (error) { if (!this.dumpCancelling) { throw error @@ -1500,14 +1507,77 @@ export class Session { this.status = BACKUP_CANCELLED_STATUS return } finally { - this.dumping = false - this.dumpCancelling = false - this.backupProgress = '' + this.stopDumpTool() } // A cancel that came after the end did nothing. The file is saved. this.status = `Backup saved to ${path}` } + /** + * Loads a .dump file into the current database with pg_restore. + * pg_restore goes on after an error, so the tables load again also after an error or a cancel. + */ + async restore(path: string, options: RestoreOptions): Promise { + this.startDumpTool(true) + let failure: unknown = null + let cancelled = false + try { + await this.api.restoreDump(this.id, path, options, this.showBackupProgress.bind(this)) + } catch (error) { + cancelled = this.dumpCancelling + failure = error + } finally { + this.stopDumpTool() + } + if (failure === null || cancelled) { + await this.loadTables() + } else { + // The error of pg_restore matters more than one of the reload. + try { + await this.loadTables() + } catch { + // The user can refresh the list. + } + } + if (cancelled) { + this.status = RESTORE_CANCELLED_STATUS + } else if (failure !== null) { + throw failure + } else { + this.status = `Restored ${path}` + } + } + + /** The pg_dump (or with `restore`, pg_restore) versions on this computer. */ + pgTools(restore: boolean): Promise { + return this.api.pgTools(this.id, restore) + } + + /** True when the file is a custom format file of pg_dump, which only pg_restore reads. */ + isCustomDump(path: string): Promise { + return this.api.isCustomDump(path) + } + + /** Sets the flags of a backup or restore that starts now. Only one runs at a time in a tab. */ + private startDumpTool(restoring: boolean): void { + if (this.dumping) { + throw this.restoring + ? 'A restore already runs in this tab' + : 'A backup already runs in this tab' + } + this.dumping = true + this.restoring = restoring + this.dumpCancelling = false + this.backupProgress = restoring ? 'Restoring…' : 'Backing up…' + } + + private stopDumpTool(): void { + this.dumping = false + this.restoring = false + this.dumpCancelling = false + this.backupProgress = '' + } + /** The busy text of the tab. A backup shows how far it is. */ get busyText(): string { return this.backupProgress || 'Working…' @@ -1520,7 +1590,14 @@ export class Session { return } const minutes = Math.floor(progress.seconds / 60) - let text = `Backing up… ${this.sizeText(progress.bytes)}, ${minutes}:${this.two(progress.seconds % 60)}` + const time = `${minutes}:${this.two(progress.seconds % 60)}` + if (this.restoring) { + // The file does not grow, so there is no size. The tables of the file are not known. + const table = progress.table ? ` · Loading table ${progress.table} (${progress.tables})` : '' + this.backupProgress = `Restoring… ${time}${table}` + return + } + let text = `Backing up… ${this.sizeText(progress.bytes)}, ${time}` if (progress.table) { // The tool may dump more tables than the list has, like the other schemas of PostgreSQL. const total = this.tables.length diff --git a/src/types.ts b/src/types.ts index 8fde12f..3191179 100644 --- a/src/types.ts +++ b/src/types.ts @@ -47,6 +47,38 @@ export interface DumpProgress { tables: number } +/** How to back up a PostgreSQL database. Other databases ignore it. */ +export interface BackupOptions { + /** True for the custom format of pg_dump (a .dump file for pg_restore). Else plain SQL. */ + custom: boolean + /** The major version of pg_dump to use. null = the default one. */ + version: number | null +} + +/** How to load a .dump file with pg_restore. */ +export interface RestoreOptions { + /** The major version of pg_restore to use. null = the default one. */ + version: number | null + /** Drop each object first (`--clean --if-exists`). */ + clean: boolean +} + +/** A pg_dump or pg_restore on this computer. */ +export interface PgTool { + /** The major version, like 17. */ + version: number + path: string +} + +/** The versions of pg_dump or pg_restore on this computer, newest first. */ +export interface PgTools { + /** The major version of the server, like 17. */ + server: number + tools: PgTool[] + /** The version of the server when it is there, else the newest. null when none was found. */ + defaultVersion: number | null +} + /** `schema` is set only for postgres and mssql. */ export interface TableRef { schema: string | null diff --git a/tests/Backup.test.ts b/tests/Backup.test.ts index cc28e79..ea7577b 100644 --- a/tests/Backup.test.ts +++ b/tests/Backup.test.ts @@ -3,7 +3,14 @@ import { expect, test } from 'bun:test' import type { DatabaseApi } from '../src/services/DatabaseApi' import { Session } from '../src/services/Session' import { FakePrompt } from './FakePrompt' -import type { ConnectionConfig, DumpProgress, TableRef } from '../src/types' +import { PgToolChoice } from '../src/services/PgToolChoice' +import type { + BackupOptions, + ConnectionConfig, + DumpProgress, + RestoreOptions, + TableRef, +} from '../src/types' class FakeApi { dumps: { id: string; path: string }[] = [] @@ -13,11 +20,17 @@ class FakeApi { private finish: ((error?: string) => void) | null = null cancels: string[] = [] + options: BackupOptions[] = [] + restores: { path: string; options: RestoreOptions }[] = [] + tableLoads = 0 + async dumpDatabase( id: string, path: string, + options: BackupOptions, onProgress: (progress: DumpProgress) => void, ): Promise { + this.options.push(options) if (path === '/nowhere/x.sql') { throw 'pg_dump was not found' } @@ -28,6 +41,32 @@ class FakeApi { } } + async restoreDump( + id: string, + path: string, + options: RestoreOptions, + onProgress: (progress: DumpProgress) => void, + ): Promise { + this.restores.push({ path, options }) + this.onProgress = onProgress + await new Promise(this.hold.bind(this)) + } + + /** When set, loading the tables fails with this error. */ + tablesError = '' + + async listTables(): Promise { + this.tableLoads += 1 + if (this.tablesError) { + throw this.tablesError + } + return [table('restored')] + } + + async listObjects(): Promise { + return [] + } + private hold(resolve: () => void, reject: (error: string) => void): void { this.finish = function end(error?: string): void { if (error) { @@ -211,3 +250,83 @@ test('a progress message that arrives after the backup ended is ignored', async expect(session.backupProgress).toBe('') expect(session.busyText).toBe('Working…') }) + +test('a custom backup sends its options and gets a .dump name', async function () { + const api = new FakeApi() + const session = new Session(api as unknown as DatabaseApi, new FakePrompt()) + session.config = config('postgres', 'shop') + expect(session.backupName(new Date(2026, 0, 31, 9, 5), 'dump')).toBe('shop-2026-01-31-0905.dump') + await session.run(session.backup('/tmp/shop.dump', { custom: true, version: 17 })) + // The plain SQL backup is the default. + await session.run(session.backup('/tmp/shop.sql')) + expect(api.options).toEqual([ + { custom: true, version: 17 }, + { custom: false, version: null }, + ]) +}) + +test('a restore shows its time and table, then loads the tables again', async function () { + const api = new FakeApi() + const session = new Session(api as unknown as DatabaseApi, new FakePrompt()) + const running = session.run(session.restore('/tmp/shop.dump', { version: 17, clean: true })) + expect(api.restores).toEqual([{ path: '/tmp/shop.dump', options: { version: 17, clean: true } }]) + expect(session.busyText).toBe('Restoring…') + expect(session.cancelTitle).toBe('Stop the restore (Esc)') + api.onProgress?.({ bytes: 4096, seconds: 75, table: 'public.orders', tables: 2 }) + expect(session.busyText).toBe('Restoring… 1:15 · Loading table public.orders (2)') + // A backup cannot start while it runs. + expect(await session.run(session.backup('/tmp/x.sql'))).toBe(false) + expect(session.error).toBe('A restore already runs in this tab') + api.end() + expect(await running).toBe(true) + expect(session.status).toBe('Restored /tmp/shop.dump') + expect(session.tables).toEqual([table('restored')]) + expect(session.dumping).toBe(false) +}) + +test('a failed or cancelled restore still loads the tables again', async function () { + const api = new FakeApi() + const session = new Session(api as unknown as DatabaseApi, new FakePrompt()) + const failing = session.run(session.restore('/tmp/a.dump', { version: null, clean: false })) + api.end('pg_restore had 2 errors. The rest was restored.') + expect(await failing).toBe(false) + expect(session.error).toBe('pg_restore had 2 errors. The rest was restored.') + expect(api.tableLoads).toBe(1) + + const cancelled = session.run(session.restore('/tmp/a.dump', { version: null, clean: false })) + await session.cancel() + expect(await cancelled).toBe(true) + expect(session.error).toBe('') + expect(session.status).toBe('Restore cancelled. What was loaded so far stays.') + expect(api.tableLoads).toBe(2) +}) + +test('the tool choice warns about a tool older than the server', function () { + const tools = [ + { version: 18, path: '/a/pg_dump' }, + { version: 15, path: '/b/pg_dump' }, + ] + const choice = new PgToolChoice('pg_dump', { server: 17, tools, defaultVersion: 18 }) + expect(choice.version).toBe(18) + expect(choice.label(tools[1]!)).toBe('PostgreSQL 15') + expect(choice.warning).toBe('') + expect(choice.missing).toBe('') + choice.version = 15 + expect(choice.warning).toBe( + 'pg_dump 15 is older than the server (PostgreSQL 17). pg_dump does not back up a newer server.', + ) + const none = new PgToolChoice('pg_restore', { server: 17, tools: [], defaultVersion: null }) + expect(none.warning).toBe('') + expect(none.missing).toContain('pg_restore was not found') +}) + +test('a failed restore keeps its error when the reload of the tables fails too', async function () { + const api = new FakeApi() + const session = new Session(api as unknown as DatabaseApi, new FakePrompt()) + api.tablesError = 'connection lost' + const failing = session.run(session.restore('/tmp/a.dump', { version: null, clean: false })) + api.end('pg_restore had 1 error. The rest was restored.') + expect(await failing).toBe(false) + expect(session.error).toBe('pg_restore had 1 error. The rest was restored.') + expect(api.tableLoads).toBe(1) +})