From 318f4a2d823ff528b9fb4bd268ad5975e2fd620f Mon Sep 17 00:00:00 2001 From: Ernstjan Freriks Date: Tue, 17 Nov 2026 16:39:50 +0100 Subject: [PATCH] feat(database): export with mysqldump and restore with mysql (#4001) MySQL and MariaDB data sources, schemas and tables get Import/Export > Export with 'mysqldump' and Restore with 'mysql'. ide-db builds the arguments from typed options and runs the tool connected like the data source (TCP, the driver's SSL flags, the SSH tunnel); the password goes in a user-only temporary option file passed as --defaults-extra-file and removed after the run. Restore pipes the dump into mysql's standard input. Restore dialogs (MySQL and PostgreSQL) now check the target first: the Database field lists the source's databases and disables Run for a missing one, and db_dump_info (formerly db_dump_kind) reports whether an SQL dump creates its database itself. pg_restore gains --create. Part of #3188 Co-authored-by: EjaYF <9842286+EjaYF@users.noreply.github.com> --- crates/ide-db/src/lib.rs | 8 +- crates/ide-db/src/tools/jobs.rs | 219 +++++++++++- crates/ide-db/src/tools/mod.rs | 384 ++++++++++++++++++--- crates/ide-db/tests/mysql.rs | 67 ++++ crates/ide-db/tests/postgres.rs | 1 + src-tauri/src/commands/db.rs | 19 +- src-tauri/tests/commands.snap | 3 +- src/bindings.ts | 56 ++- src/features/database/Database.module.css | 3 +- src/features/database/Dialogs.tsx | 8 + src/features/database/DumpDialogs.tsx | 263 ++++++++++++-- src/features/database/MysqlDumpDialogs.tsx | 357 +++++++++++++++++++ src/features/database/dumpTools.test.ts | 64 ++++ src/features/database/dumpTools.ts | 86 ++++- src/features/database/store.ts | 6 +- src/features/database/toolRuns.ts | 4 +- src/features/database/treeActions.ts | 25 +- src/features/database/treeMenu.ts | 17 +- src/platform/locales/text/en.json | 35 ++ src/platform/locales/text/zh.json | 35 ++ 20 files changed, 1545 insertions(+), 115 deletions(-) create mode 100644 src/features/database/MysqlDumpDialogs.tsx diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs index a438200cd..0905a6430 100644 --- a/crates/ide-db/src/lib.rs +++ b/crates/ide-db/src/lib.rs @@ -812,16 +812,16 @@ impl DbManager { let password = self.password(&source).await; // Holding the tunnel keeps it open while the tool runs, even if the tree disconnects. let (target, _tunnel) = self.endpoint(&source, None, true).await?; - let prepared = tools::prepare(job, &target, password.as_deref()); - tools::run(executable, &prepared.args, &prepared.env, cancel, on_output).await + let prepared = tools::prepare(job, executable, &target, password.as_deref())?; + tools::run(executable, &prepared.args, &prepared.env, prepared.input.as_deref(), cancel, on_output).await } /// The command [`DbManager::run_tool`] would run, for the dialogs' preview: the data source's /// own host and port (not a tunnel's local end), and no password. pub fn tool_preview(&self, id: &str, executable: &std::path::Path, job: &tools::DbToolJob) -> IdeResult { let source = self.source(id)?; - let prepared = tools::prepare(job, &source, None); - Ok(tools::command_line(executable, &prepared.args)) + let prepared = tools::prepare(job, executable, &source, None)?; + Ok(tools::command_line(executable, &prepared.args, job.input())) } /// The PostgreSQL server's `server_version_num` (`150013` for 15.13). diff --git a/crates/ide-db/src/tools/jobs.rs b/crates/ide-db/src/tools/jobs.rs index a661dfce6..7fa7b20a2 100644 --- a/crates/ide-db/src/tools/jobs.rs +++ b/crates/ide-db/src/tools/jobs.rs @@ -2,6 +2,7 @@ //! The connection arguments come from [`super::connection`]; these are the rest. use super::DbTool; +use ide_core::{IdeError, IdeResult}; use serde::{Deserialize, Serialize}; use specta::Type; use std::path::Path; @@ -58,6 +59,8 @@ pub struct DbPgDumpOptions { pub struct DbPgRestoreOptions { pub content: DbDumpContent, pub schemas: Vec, + /// Creates the database the archive names; the target is only connected to. + pub create: bool, pub clean: bool, pub if_exists: bool, pub no_owner: bool, @@ -75,6 +78,40 @@ pub struct DbPsqlOptions { pub stop_on_error: bool, } +/// Switches that `mysqldump` turns on by default (`--opt`) only take a flag when turned off. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct DbMysqldumpOptions { + /// Empty: every database. + pub databases: Vec, + /// Only with exactly one database. + pub tables: Vec, + pub add_drop_table: bool, + pub disable_keys: bool, + pub add_locks: bool, + pub add_drop_trigger: bool, + pub no_data: bool, + pub complete_insert: bool, + pub create_options: bool, + pub routines: bool, + pub events: bool, + /// A consistent InnoDB snapshot without locks; needs no RELOAD privilege. + pub single_transaction: bool, + /// Wins over `single_transaction`. + pub lock_all_tables: bool, + /// `None`: the client has no `--masking-policies`. + pub masking_policies: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct DbMysqlOptions { + /// Empty: the databases the dump names. + pub database: String, + /// Runs the remaining statements after an error. + pub force: bool, +} + /// A run of a client tool: which one, the file it writes or reads, and its options. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(tag = "tool", rename_all = "camelCase")] @@ -92,6 +129,15 @@ pub enum DbToolJob { file: String, options: DbPsqlOptions, }, + Mysqldump { + file: String, + options: DbMysqldumpOptions, + }, + /// `file` goes to the standard input. + Mysql { + file: String, + options: DbMysqlOptions, + }, } impl DbToolJob { @@ -100,15 +146,38 @@ impl DbToolJob { DbToolJob::PgDump { .. } => DbTool::PgDump, DbToolJob::PgRestore { .. } => DbTool::PgRestore, DbToolJob::Psql { .. } => DbTool::Psql, + DbToolJob::Mysqldump { .. } => DbTool::Mysqldump, + DbToolJob::Mysql { .. } => DbTool::Mysql, } } + /// The file piped to the tool's standard input. + pub fn input(&self) -> Option<&str> { + match self { + DbToolJob::Mysql { file, .. } if !file.is_empty() => Some(file), + _ => None, + } + } + + /// Refuses names that the tool would read as options: `mysqldump` takes databases and tables + /// as plain arguments. + pub fn check(&self) -> IdeResult<()> { + if let DbToolJob::Mysqldump { options, .. } = self + && let Some(name) = options.databases.iter().chain(&options.tables).find(|n| n.trim().starts_with('-')) + { + return Err(IdeError::invalid(format!("mysqldump cannot dump a database or table named {name}"))); + } + Ok(()) + } + /// The arguments after the connection ones. pub fn args(&self) -> Vec { match self { DbToolJob::PgDump { file, options } => pg_dump(options, file), DbToolJob::PgRestore { file, options } => pg_restore(options, file), DbToolJob::Psql { file, options } => psql(options, file), + DbToolJob::Mysqldump { file, options } => mysqldump(options, file), + DbToolJob::Mysql { options, .. } => mysql(options), } } } @@ -162,6 +231,7 @@ fn pg_dump(o: &DbPgDumpOptions, file: &str) -> Vec { fn pg_restore(o: &DbPgRestoreOptions, file: &str) -> Vec { let mut args: Vec = content(o.content).into_iter().collect(); args.extend(each(&o.schemas, "schema")); + args.extend(flag(o.create, "--create")); args.extend(flag(o.clean, "--clean")); args.extend(flag(o.clean && o.if_exists, "--if-exists")); args.extend(flag(o.no_owner, "--no-owner")); @@ -187,8 +257,53 @@ fn psql(o: &DbPsqlOptions, file: &str) -> Vec { args } -/// The command as a shell would need it typed: the dialogs' preview. -pub fn command_line(program: &Path, args: &[String]) -> String { +fn names(list: &[String]) -> impl Iterator { + list.iter().map(|n| n.trim()).filter(|n| !n.is_empty()).map(str::to_owned) +} + +fn mysqldump(o: &DbMysqldumpOptions, file: &str) -> Vec { + let skip = |on: bool, option: &str| (!on).then(|| format!("--skip-{option}")); + let mut args = vec![format!("--result-file={file}")]; + args.extend(skip(o.add_drop_table, "add-drop-table")); + args.extend(skip(o.disable_keys, "disable-keys")); + args.extend(skip(o.add_locks, "add-locks")); + args.extend(skip(o.create_options, "create-options")); + args.extend(flag(o.add_drop_trigger, "--add-drop-trigger")); + args.extend(flag(o.no_data, "--no-data")); + args.extend(flag(o.complete_insert, "--complete-insert")); + args.extend(flag(o.routines, "--routines")); + args.extend(flag(o.events, "--events")); + args.extend(flag(o.lock_all_tables, "--lock-all-tables")); + args.extend(flag(!o.lock_all_tables && o.single_transaction, "--single-transaction")); + // On by default where it exists; reading the policies needs privileges most users lack. + args.extend(flag(o.masking_policies == Some(false), "--skip-masking-policies")); + // Tablespace statements need the PROCESS privilege and rarely matter in a dump. + args.push("--no-tablespaces".into()); + args.push("--verbose".into()); + let databases: Vec = names(&o.databases).collect(); + match databases.as_slice() { + [] => args.push("--all-databases".into()), + [one] => { + args.push(one.clone()); + args.extend(names(&o.tables)); + } + _ => { + args.push("--databases".into()); + args.extend(databases); + } + } + args +} + +fn mysql(o: &DbMysqlOptions) -> Vec { + let database = o.database.trim(); + let mut args: Vec = (!database.is_empty()).then(|| format!("--database={database}")).into_iter().collect(); + args.extend(flag(o.force, "--force")); + args +} + +/// The command as a shell would need it typed: the dialogs' preview. `input` is piped in. +pub fn command_line(program: &Path, args: &[String], input: Option<&str>) -> String { let quote = |s: &str| { if !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "@%+=:,./-_".contains(c)) { s.to_owned() @@ -196,11 +311,15 @@ pub fn command_line(program: &Path, args: &[String]) -> String { format!("'{}'", s.replace('\'', "'\\''")) } }; - std::iter::once(program.to_string_lossy().into_owned()) + let line = std::iter::once(program.to_string_lossy().into_owned()) .chain(args.iter().cloned()) .map(|a| quote(&a)) .collect::>() - .join(" ") + .join(" "); + match input { + Some(file) => format!("{line} < {}", quote(file)), + None => line, + } } #[cfg(test)] @@ -228,6 +347,7 @@ mod tests { DbPgRestoreOptions { content: DbDumpContent::All, schemas: vec![], + create: false, clean: false, if_exists: false, no_owner: false, @@ -308,6 +428,13 @@ mod tests { ); } + #[test] + fn creates_the_database_of_the_archive_when_asked() { + let options = DbPgRestoreOptions { create: true, ..restore() }; + let a = args(DbToolJob::PgRestore { file: "/tmp/shop.dump".into(), options }); + assert_eq!(a, ["--create", "--exit-on-error", "--verbose", "/tmp/shop.dump"]); + } + #[test] fn leaves_out_an_archive_not_chosen_yet() { let a = args(DbToolJob::PgRestore { file: String::new(), options: restore() }); @@ -328,8 +455,92 @@ mod tests { let line = command_line( Path::new("/usr/bin/pg_dump"), &["--port=5432".into(), "--file=/tmp/my dump.sql".into(), "--table=it's".into()], + None, ); assert_eq!(line, r#"/usr/bin/pg_dump --port=5432 '--file=/tmp/my dump.sql' '--table=it'\''s'"#); + let line = command_line(Path::new("mysql"), &["--force".into()], Some("/tmp/my dump.sql")); + assert_eq!(line, "mysql --force < '/tmp/my dump.sql'"); + } + + fn mysqldump_options() -> DbMysqldumpOptions { + DbMysqldumpOptions { + databases: vec!["shop".into()], + tables: vec![], + add_drop_table: true, + disable_keys: true, + add_locks: true, + add_drop_trigger: false, + no_data: false, + complete_insert: false, + create_options: true, + routines: false, + events: false, + single_transaction: true, + lock_all_tables: false, + masking_policies: None, + } + } + + #[test] + fn mysqldump_flags_only_what_differs_from_its_defaults() { + let job = DbToolJob::Mysqldump { file: "/tmp/shop.sql".into(), options: mysqldump_options() }; + assert_eq!( + args(job), + ["--result-file=/tmp/shop.sql", "--single-transaction", "--no-tablespaces", "--verbose", "shop"] + ); + let options = DbMysqldumpOptions { + add_drop_table: false, + create_options: false, + routines: true, + lock_all_tables: true, + masking_policies: Some(false), + ..mysqldump_options() + }; + let a = args(DbToolJob::Mysqldump { file: "/tmp/x.sql".into(), options }); + for expected in ["--skip-add-drop-table", "--skip-create-options", "--routines", "--lock-all-tables"] { + assert!(a.contains(&expected.to_owned()), "{expected} missing from {a:?}"); + } + assert!(a.contains(&"--skip-masking-policies".to_owned()), "{a:?}"); + assert!(!a.contains(&"--single-transaction".to_owned()), "{a:?}"); + } + + #[test] + fn mysqldump_names_tables_only_of_a_single_database() { + let tables = vec!["orders".to_owned(), "items".to_owned()]; + let one = DbMysqldumpOptions { tables: tables.clone(), ..mysqldump_options() }; + assert!(args(DbToolJob::Mysqldump { file: "f".into(), options: one }).ends_with(&[ + "shop".into(), + "orders".into(), + "items".into() + ])); + let two = DbMysqldumpOptions { databases: vec!["a".into(), "b".into()], tables, ..mysqldump_options() }; + assert!(args(DbToolJob::Mysqldump { file: "f".into(), options: two }).ends_with(&[ + "--databases".into(), + "a".into(), + "b".into() + ])); + let all = DbMysqldumpOptions { databases: vec![], ..mysqldump_options() }; + assert_eq!(args(DbToolJob::Mysqldump { file: "f".into(), options: all }).last().unwrap(), "--all-databases"); + } + + #[test] + fn mysqldump_refuses_names_it_would_read_as_options() { + let options = DbMysqldumpOptions { tables: vec!["--result-file=/etc/x".into()], ..mysqldump_options() }; + assert!(DbToolJob::Mysqldump { file: "f".into(), options }.check().is_err()); + assert!(DbToolJob::Mysqldump { file: "f".into(), options: mysqldump_options() }.check().is_ok()); + } + + #[test] + fn mysql_reads_the_dump_from_its_standard_input() { + let job = DbToolJob::Mysql { + file: "/tmp/shop.sql".into(), + options: DbMysqlOptions { database: " shop ".into(), force: true }, + }; + assert_eq!(args(job.clone()), ["--database=shop", "--force"]); + assert_eq!(job.input(), Some("/tmp/shop.sql")); + let none = + DbToolJob::Mysql { file: String::new(), options: DbMysqlOptions { database: String::new(), force: false } }; + assert!(args(none.clone()).is_empty() && none.input().is_none()); } #[test] diff --git a/crates/ide-db/src/tools/mod.rs b/crates/ide-db/src/tools/mod.rs index 22c2ae420..5b32923a9 100644 --- a/crates/ide-db/src/tools/mod.rs +++ b/crates/ide-db/src/tools/mod.rs @@ -1,5 +1,6 @@ -//! Client tools of a database (`pg_dump`, `pg_restore`, `psql`): finding installed copies, the -//! arguments and environment that connect them like the data source, and running them. +//! Client tools of a database (`pg_dump`, `pg_restore`, `psql`, `mysqldump`, `mysql`): finding +//! installed copies, the arguments and environment that connect them like the data source, and +//! running them. mod jobs; pub use jobs::*; @@ -20,6 +21,8 @@ pub enum DbTool { PgDump, PgRestore, Psql, + Mysqldump, + Mysql, } impl DbTool { @@ -27,20 +30,25 @@ impl DbTool { self.programs()[0] } - /// Executable names. + /// Executable names, MariaDB's own after MySQL's. pub fn programs(self) -> &'static [&'static str] { match self { DbTool::PgDump => &["pg_dump"], DbTool::PgRestore => &["pg_restore"], DbTool::Psql => &["psql"], + DbTool::Mysqldump => &["mysqldump", "mariadb-dump"], + DbTool::Mysql => &["mysql", "mariadb"], } } pub fn driver(self) -> DbDriver { - DbDriver::Postgres + match self { + DbTool::PgDump | DbTool::PgRestore | DbTool::Psql => DbDriver::Postgres, + DbTool::Mysqldump | DbTool::Mysql => DbDriver::Mysql, + } } - /// Whether `path` names this tool (`pg_dump`, `pg_dump.exe`, `pg_dump-17`…). + /// Whether `path` names this tool (`pg_dump`, `pg_dump.exe`, `pg_dump-17`, `mariadb-dump`…). /// The data source's password is handed only to such a program. pub fn is_program(self, path: &Path) -> bool { let Some(stem) = path.file_stem().and_then(OsStr::to_str) else { return false }; @@ -53,6 +61,12 @@ impl DbTool { } } +/// Whether `executable` is MariaDB's client (`mariadb`, `mariadb-dump`), whose SSL options differ +/// from MySQL's. +fn is_mariadb(executable: &Path) -> bool { + executable.file_stem().and_then(OsStr::to_str).is_some_and(|s| s.starts_with("mariadb")) +} + /// An installed copy of a tool. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase", rename = "DbToolInstall")] @@ -70,28 +84,41 @@ pub struct ToolLine { pub text: String, } -/// Directories holding the tools that are often missing from `PATH`, by platform. -fn known_dirs() -> Vec { +/// Directories holding the tools of `driver` that are often missing from `PATH`, by platform. +fn known_dirs(driver: DbDriver) -> Vec { + let mysql = driver == DbDriver::Mysql; let mut dirs = Vec::new(); if cfg!(target_os = "macos") { for prefix in ["/opt/homebrew", "/usr/local"] { dirs.push(PathBuf::from(format!("{prefix}/bin"))); let opt = PathBuf::from(format!("{prefix}/opt")); - for keg in ["libpq", "postgresql"] { + let kegs: &[&str] = if mysql { &["mysql-client", "mysql", "mariadb"] } else { &["libpq", "postgresql"] }; + for keg in kegs { dirs.extend(children(&opt, keg).into_iter().map(|d| d.join("bin"))); } } - dirs.extend( - children(Path::new("/Applications/Postgres.app/Contents/Versions"), "").into_iter().map(|d| d.join("bin")), - ); + if mysql { + dirs.push(PathBuf::from("/usr/local/mysql/bin")); + } else { + dirs.extend( + children(Path::new("/Applications/Postgres.app/Contents/Versions"), "") + .into_iter() + .map(|d| d.join("bin")), + ); + } } else if cfg!(windows) { for var in ["ProgramFiles", "ProgramFiles(x86)"] { if let Some(base) = std::env::var_os(var) { - let root = PathBuf::from(base).join("PostgreSQL"); - dirs.extend(children(&root, "").into_iter().map(|d| d.join("bin"))); + let base = PathBuf::from(base); + // MySQL installs to `MySQL\MySQL Server 8.4`, MariaDB to `MariaDB 11.4`. + let roots: &[(&str, &str)] = + if mysql { &[("MySQL", "MySQL"), ("", "MariaDB")] } else { &[("PostgreSQL", "")] }; + for (dir, prefix) in roots { + dirs.extend(children(&base.join(dir), prefix).into_iter().map(|d| d.join("bin"))); + } } } - } else { + } else if !mysql { dirs.extend(children(Path::new("/usr/lib/postgresql"), "").into_iter().map(|d| d.join("bin"))); dirs.extend(children(Path::new("/usr"), "pgsql-").into_iter().map(|d| d.join("bin"))); } @@ -121,7 +148,7 @@ fn version_key(text: &str) -> Vec { pub fn find_installs(tool: DbTool) -> Vec { let path = ide_core::process::host_var_os("PATH").unwrap_or_default(); let mut dirs: Vec = std::env::split_paths(&path).collect(); - dirs.extend(known_dirs()); + dirs.extend(known_dirs(tool.driver())); let mut seen = Vec::new(); let mut out = Vec::new(); for dir in dirs { @@ -150,6 +177,29 @@ pub fn version_of(path: &Path) -> IdeResult { } } +/// The long options `path --help` lists (`masking-policies` for `--masking-policies`), so a +/// dialog offers only options this copy knows. Blocking. +pub fn options_of(path: &Path) -> IdeResult> { + let (_, text) = capture(path, "--help")?; + Ok(help_options(&text)) +} + +fn help_options(help: &str) -> Vec { + let mut out: Vec = help + .lines() + .filter(|l| l.starts_with(' ') && l.trim_start().starts_with('-')) + .filter_map(|l| { + let at = l.find("--")?; + let name: String = + l[at + 2..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').collect(); + (!name.is_empty()).then_some(name) + }) + .collect(); + out.sort(); + out.dedup(); + out +} + /// Runs `path arg` for at most five seconds; whether it succeeded, and its standard output. fn capture(path: &Path, arg: &str) -> IdeResult<(bool, String)> { if !path.is_file() { @@ -189,23 +239,41 @@ pub enum DbDumpKind { PostgresArchive, /// Plain SQL from `pg_dump`: `psql`. PostgresSql, - /// `mysqldump` / `mariadb-dump`: not for the PostgreSQL tools. + /// `mysqldump` / `mariadb-dump`: `mysql`. MysqlSql, Unknown, } -/// Blocking: reads at most the first 4 KiB. -pub fn dump_kind(path: &Path) -> IdeResult { +/// What a restore needs to know about a dump before it runs. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase", rename = "DbDumpInfo")] +pub struct DumpInfo { + pub kind: DbDumpKind, + /// An SQL dump that runs `CREATE DATABASE` itself: `mysqldump --databases` / `--all-databases`, + /// or `pg_dump --create`. Archives say `false`; `pg_restore --create` decides for them. + pub creates_database: bool, +} + +/// Blocking: reads at most the first 64 KiB, where both tools write their `CREATE DATABASE`. +pub fn dump_info(path: &Path) -> IdeResult { use std::io::Read; if path.is_dir() { - return Ok(if path.join("toc.dat").is_file() { DbDumpKind::PostgresArchive } else { DbDumpKind::Unknown }); + let kind = if path.join("toc.dat").is_file() { DbDumpKind::PostgresArchive } else { DbDumpKind::Unknown }; + return Ok(DumpInfo { kind, creates_database: false }); } - let mut head = Vec::with_capacity(4096); + let mut head = Vec::with_capacity(64 * 1024); std::fs::File::open(path) .map_err(|e| IdeError::not_found(format!("cannot read {}: {e}", path.display())))? - .take(4096) + .take(64 * 1024) .read_to_end(&mut head)?; - Ok(kind_of(&head)) + Ok(info_of(&head)) +} + +fn info_of(head: &[u8]) -> DumpInfo { + let kind = kind_of(head); + let sql = matches!(kind, DbDumpKind::PostgresSql | DbDumpKind::MysqlSql); + let creates_database = sql && String::from_utf8_lossy(head).lines().any(|l| l.starts_with("CREATE DATABASE ")); + DumpInfo { kind, creates_database } } fn kind_of(head: &[u8]) -> DbDumpKind { @@ -224,9 +292,12 @@ fn kind_of(head: &[u8]) -> DbDumpKind { } } -/// Arguments and environment that connect `tool` to `source` (already resolved, through its -/// tunnel when it has one). The password is left to [`prepare`]. -pub fn connection(tool: DbTool, source: &DataSource) -> (Vec, Vec<(String, String)>) { +/// Arguments and environment that connect `tool` at `executable` to `source` (already resolved, +/// through its tunnel when it has one). The password is left to [`prepare`]. +pub fn connection(tool: DbTool, executable: &Path, source: &DataSource) -> (Vec, Vec<(String, String)>) { + if tool.driver() == DbDriver::Mysql { + return (mysql_connection(tool, executable, source), Vec::new()); + } let mut args = Vec::new(); let host = source.host.trim(); if !host.is_empty() { @@ -271,6 +342,50 @@ pub fn connection(tool: DbTool, source: &DataSource) -> (Vec, Vec<(Strin (args, env) } +/// The database is the job's: a dump may name several. +fn mysql_connection(tool: DbTool, executable: &Path, source: &DataSource) -> Vec { + let mut args = Vec::new(); + let host = source.host.trim(); + if !host.is_empty() { + args.push(format!("--host={host}")); + } + args.push(format!("--port={}", source.port.or(source.driver.default_port()).unwrap_or(3306))); + if !source.user.trim().is_empty() { + args.push(format!("--user={}", source.user.trim())); + } + // `localhost` would otherwise mean the Unix socket, not the port or the tunnel. + args.push("--protocol=TCP".into()); + if is_mariadb(executable) { + let flags: &[&str] = match source.ssl { + DbSslMode::Disable => &["--skip-ssl"], + DbSslMode::Prefer => &["--skip-ssl-verify-server-cert"], + DbSslMode::Require => &["--ssl", "--skip-ssl-verify-server-cert"], + DbSslMode::VerifyCa | DbSslMode::VerifyFull => &["--ssl", "--ssl-verify-server-cert"], + }; + args.extend(flags.iter().map(|f| f.to_string())); + } else { + let mode = match source.ssl { + DbSslMode::Disable => "DISABLED", + DbSslMode::Prefer => "PREFERRED", + DbSslMode::Require => "REQUIRED", + DbSslMode::VerifyCa => "VERIFY_CA", + DbSslMode::VerifyFull => "VERIFY_IDENTITY", + }; + args.push(format!("--ssl-mode={mode}")); + } + for (flag, file) in + [("--ssl-ca", &source.ssl_ca_file), ("--ssl-cert", &source.ssl_cert_file), ("--ssl-key", &source.ssl_key_file)] + { + if !file.trim().is_empty() { + args.push(format!("{flag}={}", ide_ssh::expand(file.trim()).to_string_lossy())); + } + } + if tool == DbTool::Mysql && source.read_only { + args.push("--init-command=SET SESSION TRANSACTION READ ONLY".into()); + } + args +} + /// `--dbname` reads a connection string or URI as connection parameters: such a database name /// goes in quoted as the string's `dbname`, so it cannot pick another host or credentials. fn dbname_arg(name: &str) -> String { @@ -281,36 +396,88 @@ fn dbname_arg(name: &str) -> String { } } -/// How a tool is started: connection arguments, then the job's, and the environment. +/// A MySQL client option file holding the password, readable by the user only; deleted on drop. +struct SecretFile(PathBuf); + +impl SecretFile { + fn mysql_password(password: &str) -> IdeResult { + use std::io::Write; + let path = std::env::temp_dir().join(format!("openidea-mysql-{}.cnf", uuid::Uuid::new_v4())); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + let mut file = options.open(&path)?; + let secret = SecretFile(path); + let escaped = password.replace('\\', "\\\\").replace('"', "\\\""); + writeln!(file, "[client]\npassword=\"{escaped}\"")?; + Ok(secret) + } + + /// `mysqldump` / `mysql` accept it only as their first argument. + fn arg(&self) -> String { + format!("--defaults-extra-file={}", self.0.display()) + } +} + +impl Drop for SecretFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +/// How a tool is started: connection arguments, then the job's, the environment, and the file +/// piped to its standard input. Keep it until the tool exits: it owns the password file. pub struct Prepared { pub args: Vec, pub env: Vec<(String, String)>, + pub input: Option, + _secret: Option, } -/// The command for `job` against `source`. The password goes in `PGPASSWORD`, never in the -/// arguments, which other users of the machine can read in the process list. -pub fn prepare(job: &DbToolJob, source: &DataSource, password: Option<&str>) -> Prepared { - let (mut args, mut env) = connection(job.tool(), source); +/// The command for `job` at `executable` against `source`. The password goes in `PGPASSWORD` or +/// a MySQL option file, never in the arguments, which other users of the machine can read in the +/// process list. +pub fn prepare(job: &DbToolJob, executable: &Path, source: &DataSource, password: Option<&str>) -> IdeResult { + job.check()?; + let tool = job.tool(); + let (mut args, mut env) = connection(tool, executable, source); args.extend(job.args()); - if let Some(p) = password.filter(|p| !p.is_empty()) { - env.push(("PGPASSWORD".into(), p.to_owned())); + let mut secret = None; + match password.filter(|p| !p.is_empty()) { + Some(p) if tool.driver() == DbDriver::Mysql => { + let file = SecretFile::mysql_password(p)?; + args.insert(0, file.arg()); + secret = Some(file); + } + Some(p) => env.push(("PGPASSWORD".into(), p.to_owned())), + None => {} } - Prepared { args, env } + Ok(Prepared { args, env, input: job.input().map(PathBuf::from), _secret: secret }) } -/// Runs `program` until it exits, passing its output in batches. Returns the exit code -/// (`None`: ended by a signal). Cancelling kills it and everything it started. +/// Runs `program` until it exits, passing its output in batches; `input` is piped to its standard +/// input. Returns the exit code (`None`: ended by a signal). Cancelling kills it and everything it +/// started. pub async fn run( program: &Path, args: &[String], env: &[(String, String)], + input: Option<&Path>, cancel: &CancellationToken, mut on_output: impl FnMut(Vec), ) -> IdeResult> { + let stdin = match input { + Some(path) => Stdio::from( + std::fs::File::open(path) + .map_err(|e| IdeError::not_found(format!("cannot read {}: {e}", path.display())))?, + ), + None => Stdio::null(), + }; let mut cmd = tokio::process::Command::new(program); cmd.args(args) .envs(env.iter().map(|(k, v)| (k, v))) - .stdin(Stdio::null()) + .stdin(stdin) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .kill_on_drop(true); @@ -408,7 +575,7 @@ mod tests { #[test] fn connects_like_the_data_source_without_prompting() { - let (args, env) = connection(DbTool::PgDump, &pg()); + let (args, env) = connection(DbTool::PgDump, Path::new("pg_dump"), &pg()); assert_eq!(args, ["--host=db.example.test", "--port=6543", "--username=app", "--dbname=shop", "--no-password"]); assert!(env.contains(&("PGSSLMODE".into(), "prefer".into()))); assert!(!env.iter().any(|(k, _)| k == "PGPASSWORD" || k == "PGOPTIONS")); @@ -421,7 +588,8 @@ mod tests { (r"it's=\x", r"--dbname=dbname='it\'s=\\x'"), ("postgresql://evil.example/p", "--dbname=dbname='postgresql://evil.example/p'"), ] { - let (args, _) = connection(DbTool::PgDump, &DataSource { database: name.into(), ..pg() }); + let (args, _) = + connection(DbTool::PgDump, Path::new("pg_dump"), &DataSource { database: name.into(), ..pg() }); assert!(args.contains(&arg.to_owned()), "{args:?}"); } } @@ -429,14 +597,14 @@ mod tests { #[test] fn default_port_and_optional_fields() { let source = DataSource { port: None, user: String::new(), database: String::new(), ..pg() }; - let (args, _) = connection(DbTool::Psql, &source); + let (args, _) = connection(DbTool::Psql, Path::new("psql"), &source); assert_eq!(args, ["--host=db.example.test", "--port=5432", "--no-password"]); } #[test] fn read_only_sources_refuse_writes() { let source = DataSource { read_only: true, ssl: DbSslMode::VerifyFull, ..pg() }; - let (_, env) = connection(DbTool::PgRestore, &source); + let (_, env) = connection(DbTool::PgRestore, Path::new("pg_restore"), &source); assert!(env.contains(&("PGOPTIONS".into(), "-c default_transaction_read_only=on".into()))); assert!(env.contains(&("PGSSLMODE".into(), "verify-full".into()))); } @@ -451,6 +619,77 @@ mod tests { } } + #[test] + fn mysql_tools_accept_mariadb_names_only_for_themselves() { + assert!(DbTool::Mysqldump.is_program(Path::new("/usr/bin/mariadb-dump"))); + assert!(DbTool::Mysql.is_program(Path::new("/opt/homebrew/opt/mysql-client/bin/mysql"))); + assert!(!DbTool::Mysql.is_program(Path::new("/usr/bin/mysqldump"))); + assert!(!DbTool::Mysql.is_program(Path::new("/usr/bin/mariadb-dump"))); + assert!(!DbTool::Mysqldump.is_program(Path::new("/usr/bin/mysqlpump"))); + } + + #[test] + fn mysql_connects_over_tcp_with_the_ssl_flags_of_its_client() { + let source = DataSource { + driver: DbDriver::Mysql, + host: "localhost".into(), + port: None, + user: "app".into(), + read_only: true, + ..DataSource::default() + }; + let (args, env) = connection(DbTool::Mysql, Path::new("/usr/bin/mysql"), &source); + assert_eq!( + args, + [ + "--host=localhost", + "--port=3306", + "--user=app", + "--protocol=TCP", + "--ssl-mode=PREFERRED", + "--init-command=SET SESSION TRANSACTION READ ONLY" + ] + ); + assert!(env.is_empty()); + let (args, _) = connection(DbTool::Mysqldump, Path::new("/usr/bin/mariadb-dump"), &source); + assert!(args.contains(&"--skip-ssl-verify-server-cert".to_owned())); + assert!(!args.iter().any(|a| a.starts_with("--ssl-mode") || a.starts_with("--init-command"))); + } + + #[test] + fn the_password_file_is_private_and_removed() { + let file = SecretFile::mysql_password(r#"p"a\ss"#).unwrap(); + let path = file.arg().trim_start_matches("--defaults-extra-file=").to_owned(); + let text = std::fs::read_to_string(&path).unwrap(); + assert_eq!(text, "[client]\npassword=\"p\\\"a\\\\ss\"\n"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + } + drop(file); + assert!(!Path::new(&path).exists()); + } + + #[test] + fn reads_long_options_from_help() { + let help = "Usage: mysqldump [OPTIONS]\n -A, --all-databases Dump all.\n --masking-policies Dump masking\n policies (--not-an-option).\n -y, --no-tablespaces \n -f, --file=FILENAME output file\n"; + assert_eq!(help_options(help), ["all-databases", "file", "masking-policies", "no-tablespaces"]); + } + + #[cfg(unix)] + #[tokio::test] + async fn pipes_the_input_file() { + let file = std::env::temp_dir().join(format!("openidea-input-{}", uuid::Uuid::new_v4())); + std::fs::write(&file, "from the file\n").unwrap(); + let mut lines = Vec::new(); + run(Path::new("/bin/cat"), &[], &[], Some(&file), &CancellationToken::new(), |b| lines.extend(b)) + .await + .unwrap(); + std::fs::remove_file(&file).unwrap(); + assert_eq!(lines, [ToolLine { stderr: false, text: "from the file".into() }]); + } + #[test] fn tells_dumps_apart_by_their_header() { assert_eq!(kind_of(b"PGDMP\x01\x0f"), DbDumpKind::PostgresArchive); @@ -461,6 +700,17 @@ mod tests { assert_eq!(kind_of(b"CREATE TABLE t (id int);\n"), DbDumpKind::Unknown); } + #[test] + fn sees_a_dump_that_creates_its_own_database() { + let one = b"-- MySQL dump 10.13\n--\n-- Host: localhost Database: shop\nCREATE TABLE `items` (id int);\n"; + assert!(!info_of(one).creates_database); + let several = b"-- MySQL dump 10.13\n--\n-- Current Database: `shop`\n--\n\nCREATE DATABASE /*!32312 IF NOT EXISTS*/ `shop`;\nUSE `shop`;\n"; + assert!(info_of(several).creates_database); + let pg = b"--\n-- PostgreSQL database dump\n--\nSET client_encoding = 'UTF8';\nCREATE DATABASE shop WITH TEMPLATE = template0;\n\\connect shop\n"; + assert_eq!(info_of(pg), DumpInfo { kind: DbDumpKind::PostgresSql, creates_database: true }); + assert!(!info_of(b"CREATE DATABASE x;\n").creates_database, "only for a dump the tools wrote"); + } + #[test] fn newer_versions_sort_first() { assert!(version_key("pg_dump (PostgreSQL) 17.2") > version_key("pg_dump (PostgreSQL) 9.6.24")); @@ -474,6 +724,7 @@ mod tests { Path::new("/bin/sh"), &["-c".into(), "echo out; echo err >&2; exit 3".into()], &[], + None, &CancellationToken::new(), |batch| lines.extend(batch), ) @@ -493,19 +744,25 @@ mod tests { tokio::time::sleep(Duration::from_millis(100)).await; stop.cancel(); }); - let result = run(Path::new("/bin/sh"), &["-c".into(), "sleep 30".into()], &[], &cancel, |_| {}).await; + let result = run(Path::new("/bin/sh"), &["-c".into(), "sleep 30".into()], &[], None, &cancel, |_| {}).await; assert!(result.is_err()); } - /// A stand-in for `tool` that prints each argument on a line, then whether `PGPASSWORD` - /// holds the expected password. + /// A stand-in for `tool` that prints each argument on a line, then whether it got a password + /// from `PGPASSWORD` or a MySQL option file. #[cfg(unix)] fn echo_tool(dir: &Path, tool: DbTool) -> PathBuf { use std::os::unix::fs::PermissionsExt; let path = dir.join(tool.program()); std::fs::write( &path, - "#!/bin/sh\nfor a in \"$@\"; do echo \"arg:$a\"; done\necho \"env:${PGPASSWORD:+set}\"\n", + concat!( + "#!/bin/sh\n", + "for a in \"$@\"; do echo \"arg:$a\"; case \"$a\" in --defaults-extra-file=*)\n", + " grep -q '^password=' \"${a#*=}\" && echo env:set;; esac; done\n", + "[ -n \"$PGPASSWORD\" ] && echo env:set\n", + "exit 0\n", + ), ) .unwrap(); std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); @@ -541,17 +798,48 @@ mod tests { file: file.clone(), options: DbPsqlOptions { single_transaction: true, stop_on_error: true }, }, + DbToolJob::Mysqldump { + file: file.clone(), + options: DbMysqldumpOptions { + databases: vec!["shop".into()], + tables: vec![], + add_drop_table: true, + disable_keys: true, + add_locks: true, + add_drop_trigger: false, + no_data: false, + complete_insert: false, + create_options: true, + routines: false, + events: false, + single_transaction: true, + lock_all_tables: false, + masking_policies: None, + }, + }, + DbToolJob::Mysql { file: String::new(), options: DbMysqlOptions { database: "shop".into(), force: false } }, ]; for job in jobs { + let mysql = job.tool().driver() == DbDriver::Mysql; + let source = if mysql { DataSource { driver: DbDriver::Mysql, ..pg() } } else { pg() }; let program = echo_tool(&dir, job.tool()); - let prepared = prepare(&job, &pg(), Some(SECRET)); + let prepared = prepare(&job, &program, &source, Some(SECRET)).unwrap(); assert!(!prepared.args.iter().any(|a| a.contains(SECRET)), "{:?}", prepared.args); + assert!(!mysql || prepared.env.is_empty(), "{:?}", prepared.env); let mut lines = Vec::new(); - run(&program, &prepared.args, &prepared.env, &CancellationToken::new(), |b| lines.extend(b)).await.unwrap(); + run(&program, &prepared.args, &prepared.env, None, &CancellationToken::new(), |b| lines.extend(b)) + .await + .unwrap(); let text: Vec<&str> = lines.iter().map(|l| l.text.as_str()).collect(); - assert!(text.contains(&"arg:--dbname=shop"), "{text:?}"); + let database = if mysql { "shop" } else { "--dbname=shop" }; + assert!(text.iter().any(|l| l.strip_prefix("arg:").is_some_and(|a| a.ends_with(database))), "{text:?}"); assert!(!text.iter().any(|l| l.contains(SECRET)), "{text:?}"); - assert!(text.contains(&"env:set"), "the tool gets the password from PGPASSWORD: {text:?}"); + assert!(text.contains(&"env:set"), "the tool gets the password: {text:?}"); + if mysql { + let file = prepared.args[0].trim_start_matches("--defaults-extra-file=").to_owned(); + drop(prepared); + assert!(!Path::new(&file).exists(), "the password file outlives the run"); + } } std::fs::remove_dir_all(&dir).unwrap(); } diff --git a/crates/ide-db/tests/mysql.rs b/crates/ide-db/tests/mysql.rs index c36382ead..616724d85 100644 --- a/crates/ide-db/tests/mysql.rs +++ b/crates/ide-db/tests/mysql.rs @@ -231,3 +231,70 @@ async fn servers_that_advertise_deprecate_eof_but_send_legacy_eof_packets() -> I assert_eq!(r.rows, vec![vec![Some("a".into())], vec![Some("b".into())]]); Ok(()) } + +/// `mysqldump` into a file and `mysql` reading it back, with the data source's password. +#[tokio::test] +async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> { + use ide_db::tools::{DbMysqlOptions, DbMysqldumpOptions, DbTool, DbToolJob, find_installs}; + let tmp = tempfile::tempdir().unwrap(); + let Some(db) = manager(&tmp, "").await else { return Ok(()) }; + let (Some(dump), Some(client)) = + (find_installs(DbTool::Mysqldump).into_iter().next(), find_installs(DbTool::Mysql).into_iter().next()) + else { + return Ok(()); + }; + let c = CancellationToken::new(); + for stmt in [ + "DROP DATABASE IF EXISTS oi_dump_src", + "DROP DATABASE IF EXISTS oi_dump_dst", + "CREATE DATABASE oi_dump_src", + "CREATE DATABASE oi_dump_dst", + "CREATE TABLE oi_dump_src.items (id INT PRIMARY KEY, tag VARCHAR(20))", + "INSERT INTO oi_dump_src.items VALUES (1, 'dumped')", + ] { + db.execute("m", stmt, 1, &c).await?; + } + let file = tmp.path().join("src.sql").to_string_lossy().into_owned(); + let run = |executable: String, job: DbToolJob| { + let db = &db; + async move { + let mut lines = Vec::new(); + let code = + db.run_tool("m", executable.as_ref(), &job, &CancellationToken::new(), |b| lines.extend(b)).await?; + assert_eq!(code, Some(0), "{} failed: {lines:?}", job.tool().program()); + IdeResult::Ok(()) + } + }; + let masking = ide_db::tools::options_of(dump.path.as_ref())?.iter().any(|o| o == "masking-policies"); + let options = DbMysqldumpOptions { + databases: vec!["oi_dump_src".into()], + tables: vec![], + add_drop_table: true, + disable_keys: true, + add_locks: true, + add_drop_trigger: false, + no_data: false, + complete_insert: false, + create_options: true, + routines: false, + events: false, + single_transaction: true, + lock_all_tables: false, + masking_policies: masking.then_some(false), + }; + run(dump.path.clone(), DbToolJob::Mysqldump { file: file.clone(), options: options.clone() }).await?; + assert!(!ide_db::tools::dump_info(file.as_ref())?.creates_database, "one database: restored into a chosen one"); + let both = tmp.path().join("both.sql").to_string_lossy().into_owned(); + let two = DbMysqldumpOptions { databases: vec!["oi_dump_src".into(), "oi_dump_dst".into()], ..options }; + run(dump.path, DbToolJob::Mysqldump { file: both.clone(), options: two }).await?; + assert!(ide_db::tools::dump_info(both.as_ref())?.creates_database, "several databases: created by the dump"); + let restore = DbMysqlOptions { database: "oi_dump_dst".into(), force: false }; + run(client.path, DbToolJob::Mysql { file, options: restore }).await?; + + let r = db.execute("m", "SELECT tag FROM oi_dump_dst.items", 1, &c).await?; + assert_eq!(r.rows[0][0].as_deref(), Some("dumped")); + for stmt in ["DROP DATABASE oi_dump_src", "DROP DATABASE oi_dump_dst"] { + db.execute("m", stmt, 1, &c).await?; + } + Ok(()) +} diff --git a/crates/ide-db/tests/postgres.rs b/crates/ide-db/tests/postgres.rs index 10d915e85..7bc1eaa0f 100644 --- a/crates/ide-db/tests/postgres.rs +++ b/crates/ide-db/tests/postgres.rs @@ -282,6 +282,7 @@ async fn dumps_and_restores_with_the_client_tools() -> IdeResult<()> { let restore = DbPgRestoreOptions { content: DbDumpContent::All, schemas: vec![], + create: false, clean: false, if_exists: false, no_owner: false, diff --git a/src-tauri/src/commands/db.rs b/src-tauri/src/commands/db.rs index c614012cc..685be158b 100644 --- a/src-tauri/src/commands/db.rs +++ b/src-tauri/src/commands/db.rs @@ -3,7 +3,7 @@ use crate::state::AppState; use ide_command::desktop_command; use ide_core::{IdeResult, RequestId}; -use ide_db::tools::{DbDumpKind, DbTool, DbToolJob, ToolInstall, ToolLine}; +use ide_db::tools::{DbTool, DbToolJob, DumpInfo, ToolInstall, ToolLine}; use tauri::ipc::Channel; use tauri::{State, Window}; @@ -37,12 +37,20 @@ pub async fn db_tool_version(path: std::path::PathBuf) -> IdeResult { ide_host::ops::doc::blocking(move || ide_db::tools::version_of(&path)).await } -/// What made the dump at `path` (from its first bytes), so a restore picks the right tool. +/// The long options the executable at `path` lists in its `--help` (`masking-policies`…). #[desktop_command(trust = trusted)] #[tauri::command] #[specta::specta] -pub async fn db_dump_kind(path: std::path::PathBuf) -> IdeResult { - ide_host::ops::doc::blocking(move || ide_db::tools::dump_kind(&path)).await +pub async fn db_tool_options(path: std::path::PathBuf) -> IdeResult> { + ide_host::ops::doc::blocking(move || ide_db::tools::options_of(&path)).await +} + +/// What made the dump at `path` and whether it creates its own database (from its first bytes). +#[desktop_command(trust = trusted)] +#[tauri::command] +#[specta::specta] +pub async fn db_dump_info(path: std::path::PathBuf) -> IdeResult { + ide_host::ops::doc::blocking(move || ide_db::tools::dump_info(&path)).await } /// The command line `db_run_tool` would run, without the password. @@ -88,11 +96,12 @@ pub async fn db_server_version(window: Window, state: State<'_, AppState>, id: S } ide_command::desktop_domain!( - db_dump_kind, + db_dump_info, db_export_file, db_run_tool, db_server_version, db_tool_installs, + db_tool_options, db_tool_preview, db_tool_version, ); diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 42f9b03fa..1e515adb3 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -97,7 +97,7 @@ db_database_catalog trusted project_host bin db_databases trusted project_host bindings async db_ddl trusted project_host bindings async db_disconnect trusted project_host bindings async -db_dump_kind trusted desktop bindings async +db_dump_info trusted desktop bindings async db_execute trusted project_host bindings async db_explain trusted project_host bindings async db_export_file always desktop bindings async @@ -124,6 +124,7 @@ db_tables trusted project_host bin db_test trusted project_host bindings async db_test_tunnel trusted project_host bindings async db_tool_installs trusted desktop bindings async +db_tool_options trusted desktop bindings async db_tool_preview trusted desktop bindings sync db_tool_version trusted desktop bindings async db_trust_ssh_host trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index f0c6f44ca..3bb2b7cac 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -276,8 +276,8 @@ export const commands = { dbDatabases: (id: string) => typedError(__TAURI_INVOKE("db_databases", { id })), dbDdl: (id: string, schema: string, table: string) => typedError(__TAURI_INVOKE("db_ddl", { id, schema, table })), dbDisconnect: (id: string) => typedError(__TAURI_INVOKE("db_disconnect", { id })), - /** What made the dump at `path` (from its first bytes), so a restore picks the right tool. */ - dbDumpKind: (path: string) => typedError(__TAURI_INVOKE("db_dump_kind", { path })), + /** What made the dump at `path` and whether it creates its own database (from its first bytes). */ + dbDumpInfo: (path: string) => typedError(__TAURI_INVOKE("db_dump_info", { path })), dbExecute: (request: RequestId, id: string, statements: SqlStatement[], skip: number, maxRows: number, schema: string | null) => typedError(__TAURI_INVOKE("db_execute", { request, id, statements, skip, maxRows, schema })), dbExplain: (request: RequestId, id: string, statement: string, schema: string | null) => typedError(__TAURI_INVOKE("db_explain", { request, id, statement, schema })), /** @@ -318,6 +318,8 @@ export const commands = { dbTestTunnel: (source: DataSource_Deserialize, sshSecret: string | null) => typedError(__TAURI_INVOKE("db_test_tunnel", { source, sshSecret })), /** Installed copies of `tool`, newest first. */ dbToolInstalls: (tool: DbTool) => typedError(__TAURI_INVOKE("db_tool_installs", { tool })), + /** The long options the executable at `path` lists in its `--help` (`masking-policies`…). */ + dbToolOptions: (path: string) => typedError(__TAURI_INVOKE("db_tool_options", { path })), /** The command line `db_run_tool` would run, without the password. */ dbToolPreview: (id: string, executable: string, job: DbToolJob) => typedError(__TAURI_INVOKE("db_tool_preview", { id, executable, job })), /** The version line of the executable at `path`. */ @@ -4187,13 +4189,23 @@ export type DbDumpFormat = /** A directory of files; the only format `pg_dump` writes in parallel. */ "directory" | "tar"; +/** What a restore needs to know about a dump before it runs. */ +export type DbDumpInfo = { + kind: DbDumpKind, + /** + * An SQL dump that runs `CREATE DATABASE` itself: `mysqldump --databases` / `--all-databases`, + * or `pg_dump --create`. Archives say `false`; `pg_restore --create` decides for them. + */ + createsDatabase: boolean, +}; + /** What made a dump, read from its first bytes (a directory: its `toc.dat`). */ export type DbDumpKind = /** `pg_dump` custom or tar archive, or a directory archive: `pg_restore`. */ "postgresArchive" | /** Plain SQL from `pg_dump`: `psql`. */ "postgresSql" | -/** `mysqldump` / `mariadb-dump`: not for the PostgreSQL tools. */ +/** `mysqldump` / `mariadb-dump`: `mysql`. */ "mysqlSql" | "unknown"; export type DbDumpStatements = "copy" | "inserts" | "columnInserts"; @@ -4237,6 +4249,36 @@ export type DbIntrospection = { objectFilter?: string, }; +export type DbMysqlOptions = { + /** Empty: the databases the dump names. */ + database: string, + /** Runs the remaining statements after an error. */ + force: boolean, +}; + +/** Switches that `mysqldump` turns on by default (`--opt`) only take a flag when turned off. */ +export type DbMysqldumpOptions = { + /** Empty: every database. */ + databases: string[], + /** Only with exactly one database. */ + tables: string[], + addDropTable: boolean, + disableKeys: boolean, + addLocks: boolean, + addDropTrigger: boolean, + noData: boolean, + completeInsert: boolean, + createOptions: boolean, + routines: boolean, + events: boolean, + /** A consistent InnoDB snapshot without locks; needs no RELOAD privilege. */ + singleTransaction: boolean, + /** Wins over `single_transaction`. */ + lockAllTables: boolean, + /** `None`: the client has no `--masking-policies`. */ + maskingPolicies: boolean | null, +}; + /** Schema objects other than tables and columns (Go to DDL, Drop). */ export type DbObjectKind = "function" | "procedure" | "package" | "trigger" | "sequence"; @@ -4283,6 +4325,8 @@ export type DbPgDumpOptions = { export type DbPgRestoreOptions = { content: DbDumpContent, schemas: string[], + /** Creates the database the archive names; the target is only connected to. */ + create: boolean, clean: boolean, ifExists: boolean, noOwner: boolean, @@ -4479,7 +4523,7 @@ export type DbTablePage = { offset: number | null, }; -export type DbTool = "pgDump" | "pgRestore" | "psql"; +export type DbTool = "pgDump" | "pgRestore" | "psql" | "mysqldump" | "mysql"; /** An installed copy of a tool. */ export type DbToolInstall = { @@ -4491,7 +4535,9 @@ export type DbToolInstall = { /** A run of a client tool: which one, the file it writes or reads, and its options. */ export type DbToolJob = { tool: "pgDump"; file: string; options: DbPgDumpOptions } | /** `file`: an archive, or a directory archive. */ -{ tool: "pgRestore"; file: string; options: DbPgRestoreOptions } | { tool: "psql"; file: string; options: DbPsqlOptions }; +{ tool: "pgRestore"; file: string; options: DbPgRestoreOptions } | { tool: "psql"; file: string; options: DbPsqlOptions } | { tool: "mysqldump"; file: string; options: DbMysqldumpOptions } | +/** `file` goes to the standard input. */ +{ tool: "mysql"; file: string; options: DbMysqlOptions }; /** A line the tool wrote. */ export type DbToolLine = { diff --git a/src/features/database/Database.module.css b/src/features/database/Database.module.css index 79a96b4a1..eaa631e05 100644 --- a/src/features/database/Database.module.css +++ b/src/features/database/Database.module.css @@ -1425,7 +1425,8 @@ } .dumpPreview { grid-column: 1 / -1; - max-height: 96px; + flex: none; + height: 96px; overflow: auto; padding: 6px 8px; border: 1px solid var(--border); diff --git a/src/features/database/Dialogs.tsx b/src/features/database/Dialogs.tsx index ecef85b04..e28f82432 100644 --- a/src/features/database/Dialogs.tsx +++ b/src/features/database/Dialogs.tsx @@ -16,6 +16,8 @@ const ImportDialog = lazyComponent(() => import("./DataDialogs").then((m) => m.I const SchemaCompareDialog = lazyComponent(() => import("./SchemaCompareDialog").then((m) => m.SchemaCompareDialog)); const DumpDialog = lazyComponent(() => import("./DumpDialogs").then((m) => m.DumpDialog)); const RestoreDialog = lazyComponent(() => import("./DumpDialogs").then((m) => m.RestoreDialog)); +const MysqlDumpDialog = lazyComponent(() => import("./MysqlDumpDialogs").then((m) => m.MysqlDumpDialog)); +const MysqlRestoreDialog = lazyComponent(() => import("./MysqlDumpDialogs").then((m) => m.MysqlRestoreDialog)); function PasswordDialog({ source, resolve }: { source: DataSource; resolve: (ok: boolean) => void }) { const [password, setPassword] = useState(""); @@ -214,6 +216,12 @@ export function DatabaseDialogs() { serverVersion={dialog.serverVersion} /> ); + if (dialog.kind === "mysqlDump") + return ( + + ); + if (dialog.kind === "mysqlRestore") + return ; if (dialog.kind === "sshSecret") return ( diff --git a/src/features/database/DumpDialogs.tsx b/src/features/database/DumpDialogs.tsx index 2890ea1c6..cc4fff5c3 100644 --- a/src/features/database/DumpDialogs.tsx +++ b/src/features/database/DumpDialogs.tsx @@ -6,7 +6,7 @@ import { commands, type DbDumpContent, type DbDumpFormat, - type DbDumpKind, + type DbDumpInfo, type DbDumpStatements, type DbPsqlOptions, type DbTool, @@ -39,15 +39,30 @@ import { outputPath, pickInstall, restoreOptions, + nameList, + patternName, + restoreTargetProblem, restoreToolFor, + toggleName, + unquoteName, versionFit, withExtension, type DumpForm, type DumpMismatch, type RestoreForm, + type TargetProblem, } from "./dumpTools"; import { splitTarget } from "./model"; -import { closeDialog, refresh, sourceById } from "./store"; +import { + closeDialog, + loadDatabases, + loadSchemas, + loadTables, + refresh, + sourceById, + tablesKey, + useDatabase, +} from "./store"; import { TOOL_PROGRAMS, startToolRun, stopToolRun, useToolRuns } from "./toolRuns"; import { copySelectionOnKeyDown } from "@/ui/selectableText"; import styles from "./Database.module.css"; @@ -176,36 +191,184 @@ export function ExecutableField({ {installs && !value.trim() - ? tx`${program} was not found. Install the PostgreSQL client tools or choose the executable.` + ? tool === "mysqldump" || tool === "mysql" + ? tx`${program} was not found. Install the MySQL or MariaDB client tools or choose the executable.` + : tx`${program} was not found. Install the PostgreSQL client tools or choose the executable.` : (hint?.text ?? current?.error ?? "\u00a0")} ); } -/** What made the dump at `path`, read from its header (`null` while unknown). */ -export function useDumpKind(path: string): DbDumpKind | null { - const [known, setKnown] = useState<{ path: string; kind: DbDumpKind } | null>(null); +/** What made the dump at `path` and whether it creates its database, from its header (`null` while unknown). */ +export function useDumpInfo(path: string): DbDumpInfo | null { + const [known, setKnown] = useState<{ path: string; info: DbDumpInfo } | null>(null); useEffect(() => { const p = path.trim(); if (!p) return; let live = true; const timer = setTimeout(() => { - call(commands.dbDumpKind(p)) - .then((kind) => live && setKnown({ path: p, kind })) - .catch(() => live && setKnown({ path: p, kind: "unknown" })); + call(commands.dbDumpInfo(p)) + .then((info) => live && setKnown({ path: p, info })) + .catch(() => live && setKnown({ path: p, info: { kind: "unknown", createsDatabase: false } })); }, 250); return () => { live = false; clearTimeout(timer); }; }, [path]); - return known?.path === path.trim() ? known.kind : null; + return known?.path === path.trim() ? known.info : null; +} + +/** The databases of the data source of `target` (MySQL: its schemas); `null` while unknown. */ +export function useDatabaseNames(target: string): { names: string[]; current: string } | null { + const { id } = splitTarget(target); + const mysql = sourceById(id)?.driver === "mysql"; + const databases = useDatabase((s) => s.databases[id]); + const schemas = useDatabase((s) => s.schemas[id]); + const loaded = mysql ? schemas : databases; + useEffect(() => { + if (!loaded) void (mysql ? loadSchemas(id) : loadDatabases(id)); + }, [id, mysql, loaded]); + if (mysql) return schemas?.status === "ok" ? { names: schemas.value, current: "" } : null; + return databases?.status === "ok" ? databases.value : null; +} + +/** The schemas on connection target `target` (`null` while unknown). */ +function useSchemaNames(target: string): string[] | null { + const loaded = useDatabase((s) => s.schemas[target]); + useEffect(() => { + if (!loaded) void loadSchemas(target); + }, [target, loaded]); + return loaded?.status === "ok" ? loaded.value : null; +} + +/** The tables of `schemas` on connection target `id` (`null` while one of them is unknown, or without schemas). */ +export function useTableNames( + id: string, + schemas: readonly string[] | null, +): { schema: string; name: string }[] | null { + const all = useDatabase((s) => s.tables); + const keys = (schemas ?? []).join("\u0000"); + useEffect(() => { + for (const schema of schemas ?? []) if (!all[tablesKey(id, schema)]) void loadTables(id, schema); + // `keys` stands for `schemas`. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [id, keys, all]); + if (!schemas?.length) return null; + const out: { schema: string; name: string }[] = []; + for (const schema of schemas) { + const loaded = all[tablesKey(id, schema)]; + if (loaded?.status !== "ok") return null; + for (const t of loaded.value) if (t.kind === "table") out.push({ schema, name: t.name }); + } + return out; +} + +/** A typed name list with a button that ticks names off a list of the server's. */ +export function NamesField({ + label, + value, + onChange, + names, + placeholder, + disabled, + title, +}: { + label: string; + value: string; + onChange: (v: string) => void; + names: string[] | null; + placeholder: string; + disabled?: boolean; + title?: string; +}) { + const chosen = nameList(value); + return ( +
+ onChange(e.target.value)} + /> + + showContextMenu( + e, + (names ?? []).map((n) => ({ + label: n, + verbatim: true, + checked: chosen.includes(n), + run: () => onChange(toggleName(value, n)), + })), + ) + } + /> +
+ ); +} + +/** + * The database a restore runs in: the data source's databases to pick from, or a text field + * while they are unknown. `empty` labels a choice of no database. + */ +export function DatabaseField({ + value, + onChange, + names, + empty, +}: { + value: string; + onChange: (v: string) => void; + names: string[] | null; + empty?: string; +}) { + if (!names) return onChange(e.target.value)} />; + const options = [ + ...(empty !== undefined ? [{ value: "", label: empty }] : []), + ...names.map((n) => ({ value: n, label: n, verbatim: true })), + ]; + if (value && !names.includes(value)) options.push({ value, label: value, verbatim: true }); + return setDatabase(e.target.value)} /> + Output result to: @@ -480,20 +656,14 @@ export function DumpDialog({ set(k)(e.target.value)} - /> + ))} {options.format === "directory" && ( @@ -562,11 +732,15 @@ export function RestoreDialog({ const [psql, setPsql] = useState(DEFAULT_PSQL); const [runKey, setRunKey] = useState(null); const running = useToolRuns((s) => (runKey !== null ? s.runs[runKey]?.status === "running" : false)); - const kind = useDumpKind(file); - const tool = picked ?? restoreToolFor(file, kind); - const mismatch = dumpMismatch(tool, kind); + const info = useDumpInfo(file); + const tool = picked ?? restoreToolFor(file, info?.kind ?? null); + const mismatch = dumpMismatch(tool, info?.kind ?? null); const executable = executables[tool]; const readOnly = !!source?.readOnly; + const databases = useDatabaseNames(target); + const shown = database || (databases?.current ?? ""); + const problem = restoreTargetProblem(shown, databases?.names ?? null, false, false); + const creates = tool === "pgRestore" ? restore.create : !!info?.createsDatabase; const changeFile = setFile; const browse = async (directory: boolean) => { @@ -602,8 +776,11 @@ export function RestoreDialog({ job, commandLine, from: file, - to: database || (source?.name ?? target), - onSuccess: () => void refresh(runTarget), + to: shown || (source?.name ?? target), + onSuccess: () => { + void refresh(runTarget); + if (creates) void refresh(splitTarget(target).id); + }, }), ); }; @@ -616,7 +793,7 @@ export function RestoreDialog({ { label: "Run", role: "default", - disabled: readOnly || !!mismatch || !executable.trim() || !file.trim(), + disabled: readOnly || !!mismatch || !!problem || !executable.trim() || !file.trim(), title: readOnly ? tx`The data source is read-only` : undefined, onClick: () => void run(), }, @@ -655,7 +832,18 @@ export function RestoreDialog({ Database: - setDatabase(e.target.value)} /> + + Path to dump: @@ -724,6 +912,11 @@ export function RestoreDialog({ />
+ (null); + useEffect(() => { + const p = path.trim(); + if (!p) return; + let live = true; + const timer = setTimeout(() => { + call(commands.dbToolOptions(p)) + .then((options) => live && setKnown({ path: p, options })) + .catch(() => live && setKnown({ path: p, options: [] })); + }, 250); + return () => { + live = false; + clearTimeout(timer); + }; + }, [path]); + return known?.path === path.trim() && known.options.includes(option); +} + +type Switch = { + [K in keyof MysqldumpForm]: MysqldumpForm[K] extends boolean ? K : never; +}[keyof MysqldumpForm]; + +const CHECKS: readonly [Switch, string][] = [ + ["addDropTable", "Add DROP TABLE before CREATE TABLE"], + ["completeInsert", "Include column names in each INSERT"], + ["disableKeys", "Add DISABLE KEYS before each INSERT block"], + ["createOptions", "Include all table options in CREATE TABLE"], + ["addLocks", "Add LOCK TABLES around each table"], + ["routines", "Include stored routines"], + ["addDropTrigger", "Add DROP TRIGGER before CREATE TRIGGER"], + ["events", "Include scheduled events"], + ["noData", "Export schema without data"], +]; + +export function MysqlDumpDialog({ target, database, tables }: { target: string; database: string; tables?: string }) { + const source = sourceById(target); + const home = useHome(); + const [executable, setExecutable] = useState(""); + const [form, setForm] = useState({ + ...DEFAULT_MYSQLDUMP, + databases: database, + tables: tables ?? "", + }); + const [edited, setOutput] = useState(null); + const output = edited ?? (home ? joinPath(home, "{data_source}-{database}-{timestamp}.sql") : ""); + const [runKey, setRunKey] = useState(null); + const running = useToolRuns((s) => (runKey !== null ? s.runs[runKey]?.status === "running" : false)); + const knowsMasking = useKnowsOption(executable, "masking-policies"); + const chosenDatabases = nameList(form.databases); + const oneDatabase = chosenDatabases.length === 1; + const databases = useDatabaseNames(target); + const tableNames = + useTableNames(splitTarget(target).id, oneDatabase ? chosenDatabases : null)?.map((t) => t.name) ?? null; + const set = + (k: K) => + (v: MysqldumpForm[K]) => + setForm((f) => ({ ...f, [k]: v })); + const jobFor = (file: string): DbToolJob => ({ + tool: "mysqldump", + file, + options: mysqldumpOptions(form, knowsMasking), + }); + const preview = useToolPreview(target, executable || "mysqldump", jobFor(output)); + + const browse = async () => { + try { + const { save } = await import("@/platform/dialog"); + const path = await save({ defaultPath: output }); + if (path) setOutput(path); + } catch { + // No dialog (tests): keep typing the path. + } + }; + + const run = async () => { + const databases = nameList(form.databases); + const file = outputPath(output, { + dataSource: source?.name ?? "", + database: databases.join("_"), + now: new Date(), + }); + const job = jobFor(file); + localStorage.setItem(pathKey("mysqldump"), executable); + const commandLine = await call(commands.dbToolPreview(target, executable, job)).catch(() => ""); + setRunKey( + startToolRun({ + target, + executable, + job, + commandLine, + output: file, + from: databases.join(", ") || tx("all databases"), + to: file, + }), + ); + }; + + const buttons: DialogButton[] = + runKey !== null + ? runButtons(runKey, running, () => setRunKey(null)) + : [ + { label: "Cancel", role: "cancel" }, + { + label: "Run", + role: "default", + disabled: !executable.trim() || !output.trim(), + onClick: () => void run(), + }, + ]; + + return ( + + {runKey !== null ? ( + + ) : ( +
+ + + Output result to: + +
+ setOutput(e.target.value)} + /> + void browse()} /> +
+ + + Allowed substitution patterns: {"{timestamp}, {data_source}, {database}"} + + + Databases to dump: + + + + Tables to dump: + + + +
+ {CHECKS.map(([k, label]) => ( + + ))} + + + {knowsMasking && ( + + )} +
+ +
+ )} +
+ ); +} + +export function MysqlRestoreDialog({ target, database: initialDatabase }: { target: string; database: string }) { + const source = sourceById(target); + const [executable, setExecutable] = useState(""); + const [database, setDatabase] = useState(initialDatabase); + const [file, setFile] = useState(""); + const [force, setForce] = useState(false); + const [runKey, setRunKey] = useState(null); + const running = useToolRuns((s) => (runKey !== null ? s.runs[runKey]?.status === "running" : false)); + const readOnly = !!source?.readOnly; + const info = useDumpInfo(file); + const mismatch = dumpMismatch("mysql", info?.kind ?? null); + const databases = useDatabaseNames(target); + const creates = !!info?.createsDatabase; + // Until the dump is read, an empty choice is not yet wrong. + const problem = restoreTargetProblem(database, databases?.names ?? null, true, creates || !info); + const job: DbToolJob = { tool: "mysql", file, options: { database, force } }; + const preview = useToolPreview(target, executable || "mysql", job); + + const browse = async () => { + try { + const { open } = await import("@/platform/dialog"); + const path = await open({ + multiple: false, + directory: false, + title: tx("Path to dump"), + }); + if (typeof path === "string") setFile(path); + } catch { + // No dialog (tests): keep typing the path. + } + }; + + const run = async () => { + localStorage.setItem(pathKey("mysql"), executable); + const commandLine = await call(commands.dbToolPreview(target, executable, job)).catch(() => preview); + setRunKey( + startToolRun({ + target, + executable, + job, + commandLine, + from: file, + to: database || (source?.name ?? target), + onSuccess: () => void refresh(target), + }), + ); + }; + + const buttons: DialogButton[] = + runKey !== null + ? runButtons(runKey, running, () => setRunKey(null)) + : [ + { label: "Cancel", role: "cancel" }, + { + label: "Run", + role: "default", + disabled: readOnly || !!mismatch || !!problem || !info || !executable.trim() || !file.trim(), + title: readOnly ? tx`The data source is read-only` : undefined, + onClick: () => void run(), + }, + ]; + + return ( + + {runKey !== null ? ( + + ) : ( +
+ + + Database: + + + + + Path to dump: + +
+ setFile(e.target.value)} + /> + void browse()} /> +
+ + + {mismatch ? mismatchText(mismatch) : mysql runs the SQL dump that mysqldump wrote.} + + + + {readOnly && ( + <> + + + The data source is read-only. + + + )} + +
+ )} +
+ ); +} diff --git a/src/features/database/dumpTools.test.ts b/src/features/database/dumpTools.test.ts index cfdb5577b..58abe8558 100644 --- a/src/features/database/dumpTools.test.ts +++ b/src/features/database/dumpTools.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import type { DataSource, DbTableInfo } from "@/platform/ipc"; import { DEFAULT_DUMP, + DEFAULT_MYSQLDUMP, DEFAULT_RESTORE, baseName, dumpMismatch, @@ -9,7 +10,13 @@ import { dumpScope, formatElapsed, majorOf, + mysqlDumpScope, + mysqldumpOptions, outputPath, + patternName, + unquoteName, + restoreTargetProblem, + toggleName, pickInstall, restoreOptions, restoreToolFor, @@ -31,6 +38,25 @@ describe("forms", () => { expect(options.tables).toEqual(['public."Order Items"', '"a,""b"".c"']); }); + it("send mysqldump tables only with one database, and masking policies only to a client that knows them", () => { + const one = mysqldumpOptions({ ...DEFAULT_MYSQLDUMP, databases: "shop", tables: "orders, items" }, false); + expect(one).toMatchObject({ databases: ["shop"], tables: ["orders", "items"], maskingPolicies: null }); + const two = mysqldumpOptions({ ...DEFAULT_MYSQLDUMP, databases: "a b", tables: "orders" }, true); + expect(two).toMatchObject({ databases: ["a", "b"], tables: [], maskingPolicies: false }); + }); + + it("turn names into pg_dump patterns and back", () => { + for (const name of ["public", "My Schema", 'a"b', "Orders"]) expect(unquoteName(patternName(name))).toBe(name); + expect(patternName("Orders")).toBe('"Orders"'); + expect(unquoteName("Public")).toBe("public"); + }); + + it("toggle a name chosen from a list", () => { + expect(toggleName("", "shop")).toBe("shop"); + expect(toggleName("shop crm", "audit")).toBe("shop, crm, audit"); + expect(toggleName("shop, crm", "shop")).toBe("crm"); + }); + it("send the typed name lists as lists", () => { const options = dumpOptions({ ...DEFAULT_DUMP, @@ -66,6 +92,26 @@ describe("restore", () => { expect(dumpMismatch("psql", "postgresSql")).toBeNull(); expect(dumpMismatch("psql", "unknown")).toBeNull(); expect(dumpMismatch("pgRestore", null)).toBeNull(); + expect(dumpMismatch("mysql", "postgresSql")).toBe("postgresIntoMysql"); + expect(dumpMismatch("mysql", "postgresArchive")).toBe("postgresIntoMysql"); + expect(dumpMismatch("mysql", "mysqlSql")).toBeNull(); + }); +}); + +describe("restore target", () => { + const existing = ["postgres", "shop"]; + + it("needs an existing database", () => { + expect(restoreTargetProblem("shop", existing, false, false)).toBeNull(); + expect(restoreTargetProblem(" shop ", existing, true, false)).toBeNull(); + expect(restoreTargetProblem("shop_new", existing, false, true)).toBe("missing"); + expect(restoreTargetProblem("shop_new", null, false, false)).toBeNull(); + }); + + it("lets MySQL run without a database only for a dump that creates its databases", () => { + expect(restoreTargetProblem("", existing, true, false)).toBe("noDatabase"); + expect(restoreTargetProblem("", existing, true, true)).toBeNull(); + expect(restoreTargetProblem("", existing, false, false)).toBeNull(); }); }); @@ -102,6 +148,24 @@ describe("dumpScope", () => { }); }); + it("applies to MySQL sources, schemas (databases) and tables with mysqlDumpScope", () => { + const mysql = { ...pg, driver: "mysql", database: "shop" } as DataSource; + expect(mysqlDumpScope({ kind: "source", key: "s1", source: mysql }, mysql)).toEqual({ + target: "s1", + database: "shop", + }); + expect(mysqlDumpScope({ kind: "schema", key: "k", id: "s1", schema: "crm" }, mysql)).toEqual({ + target: "s1", + database: "crm", + }); + expect(mysqlDumpScope({ kind: "table", key: "k", id: "s1", schema: "crm", table }, mysql)).toEqual({ + target: "s1", + database: "crm", + tables: "Orders", + }); + expect(mysqlDumpScope({ kind: "source", key: "s1", source: pg }, pg)).toBeNull(); + }); + it("does not apply to other drivers or views", () => { const mysql = { ...pg, driver: "mysql" } as DataSource; expect(dumpScope({ kind: "source", key: "s1", source: mysql }, mysql)).toBeNull(); diff --git a/src/features/database/dumpTools.ts b/src/features/database/dumpTools.ts index f96c91282..e25efbcfa 100644 --- a/src/features/database/dumpTools.ts +++ b/src/features/database/dumpTools.ts @@ -3,6 +3,7 @@ import type { DataSource, DbDumpFormat, DbDumpKind, + DbMysqldumpOptions, DbPgDumpOptions, DbPgRestoreOptions, DbPsqlOptions, @@ -24,6 +25,10 @@ type Typed = Omit & { [P in K]: string }; export type DumpForm = Typed; export type RestoreForm = Typed; +/** `maskingPolicies` is the checkbox; whether the client knows the option is decided at run time. */ +export type MysqldumpForm = Typed, "databases" | "tables"> & { + maskingPolicies: boolean; +}; export const DEFAULT_DUMP: DumpForm = { format: "plain", @@ -43,6 +48,7 @@ export const DEFAULT_DUMP: DumpForm = { export const DEFAULT_RESTORE: RestoreForm = { content: "all", schemas: "", + create: false, clean: false, ifExists: false, noOwner: false, @@ -54,6 +60,27 @@ export const DEFAULT_RESTORE: RestoreForm = { export const DEFAULT_PSQL: DbPsqlOptions = { singleTransaction: true, stopOnError: true }; +/** + * `mysqldump`'s own defaults, except `--single-transaction` instead of DataGrip's + * `--lock-all-tables`, which needs the RELOAD privilege. + */ +export const DEFAULT_MYSQLDUMP: MysqldumpForm = { + databases: "", + tables: "", + addDropTable: true, + disableKeys: true, + addLocks: true, + addDropTrigger: false, + noData: false, + completeInsert: false, + createOptions: true, + routines: false, + events: false, + singleTransaction: true, + lockAllTables: false, + maskingPolicies: false, +}; + /** `a, b c` → `["a", "b", "c"]`; a double-quoted part keeps its spaces and commas: `public."Order Items"`. */ export function nameList(text: string): string[] { return text.match(/(?:"(?:[^"]|"")*"|[^\s,"]|")+/g) ?? []; @@ -67,6 +94,23 @@ export function restoreOptions(f: RestoreForm): DbPgRestoreOptions { return { ...f, schemas: nameList(f.schemas) }; } +/** The typed list with `name` added, or taken out when it is there: `a, b` + `c` → `a, b, c`. */ +export function toggleName(text: string, name: string): string { + const names = nameList(text); + return (names.includes(name) ? names.filter((n) => n !== name) : [...names, name]).join(", "); +} + +/** `knowsMasking`: the chosen `mysqldump` lists `--masking-policies` in its `--help`. */ +export function mysqldumpOptions(f: MysqldumpForm, knowsMasking: boolean): DbMysqldumpOptions { + const databases = nameList(f.databases); + return { + ...f, + databases, + tables: databases.length === 1 ? nameList(f.tables) : [], + maskingPolicies: knowsMasking ? f.maskingPolicies : null, + }; +} + /** * The PostgreSQL tool for a dump: from its header when known, else `psql` for a `.sql` file and * `pg_restore` for anything else (archives, directories). @@ -77,17 +121,37 @@ export function restoreToolFor(path: string, kind: DbDumpKind | null = null): Ex return /\.sql$/i.test(path.trim()) ? "psql" : "pgRestore"; } -export type DumpMismatch = "mysqlIntoPostgres" | "archiveIntoPsql" | "sqlIntoPgRestore"; +export type DumpMismatch = "postgresIntoMysql" | "mysqlIntoPostgres" | "archiveIntoPsql" | "sqlIntoPgRestore"; /** Why `tool` cannot restore a dump of `kind`; `null` when it can, or the kind is unknown. */ export function dumpMismatch(tool: DbTool, kind: DbDumpKind | null): DumpMismatch | null { if (!kind || kind === "unknown") return null; + if (tool === "mysql") return kind === "mysqlSql" ? null : "postgresIntoMysql"; if (kind === "mysqlSql") return "mysqlIntoPostgres"; if (tool === "psql" && kind === "postgresArchive") return "archiveIntoPsql"; if (tool === "pgRestore" && kind === "postgresSql") return "sqlIntoPgRestore"; return null; } +export type TargetProblem = "missing" | "noDatabase"; + +/** + * Why a restore cannot run in or connect to `database`; `null` when it can, or while the + * databases are unknown. An empty name is the data source's own for PostgreSQL; MySQL then runs + * without a database, which only works for a dump that creates its databases. + */ +export function restoreTargetProblem( + database: string, + existing: readonly string[] | null, + mysql: boolean, + createsDatabase: boolean, +): TargetProblem | null { + const name = database.trim(); + if (!name) return mysql && !createsDatabase ? "noDatabase" : null; + if (!existing) return null; + return existing.includes(name) ? null : "missing"; +} + /** `2026-03-07_09-05-02` (local time). */ export function timestamp(d: Date): string { const p = (n: number) => String(n).padStart(2, "0"); @@ -111,10 +175,15 @@ export function withExtension(pattern: string, format: DbDumpFormat): string { } /** A name as a `pg_dump` pattern: quoted unless it is a lower-case identifier. */ -function patternName(name: string): string { +export function patternName(name: string): string { return /^[a-z_][a-z0-9_$]*$/.test(name) ? name : `"${name.replaceAll('"', '""')}"`; } +/** A typed `pg_dump` name back to the name itself: `"My Schema"` → `My Schema`, `Public` → `public`. */ +export function unquoteName(pattern: string): string { + return /^".*"$/.test(pattern) ? pattern.slice(1, -1).replaceAll('""', '"') : pattern.toLowerCase(); +} + export interface DumpScope { target: string; database: string; @@ -134,6 +203,19 @@ export function dumpScope(n: DbNode, source: DataSource | undefined): DumpScope return null; } +/** + * What Export with 'mysqldump' / Restore with 'mysql' act on for tree node `n`: a MySQL schema + * is a database. `null` when they don't apply. + */ +export function mysqlDumpScope(n: DbNode, source: DataSource | undefined): DumpScope | null { + const target = nodeTarget(n); + if (!target || source?.driver !== "mysql") return null; + if (n.kind === "source") return { target, database: source.database ?? "" }; + if (n.kind === "schema") return { target, database: n.schema }; + if (n.kind === "table" && n.table.kind === "table") return { target, database: n.schema, tables: n.table.name }; + return null; +} + /** The major version in a `--version` line (`pg_dump (PostgreSQL) 17.2` → 17). */ export function majorOf(version: string): number | null { const m = /(\d+)(?:\.\d+)?/.exec(version); diff --git a/src/features/database/store.ts b/src/features/database/store.ts index 0f3958883..15fe85da2 100644 --- a/src/features/database/store.ts +++ b/src/features/database/store.ts @@ -150,7 +150,11 @@ export type DialogState = /** Export with 'pg_dump' of a database, schema or table. */ | { kind: "dump"; target: string; database: string; schemas?: string; tables?: string; serverVersion: number | null } /** Restore with 'pg_restore' / 'psql' into a database. */ - | { kind: "restore"; target: string; database: string; serverVersion: number | null }; + | { kind: "restore"; target: string; database: string; serverVersion: number | null } + /** Export with 'mysqldump' of a data source, database or table. */ + | { kind: "mysqlDump"; target: string; database: string; tables?: string } + /** Restore with 'mysql' into a database. */ + | { kind: "mysqlRestore"; target: string; database: string }; /** The schemas and tables of a data source's databases, as far as introspection has read them. */ export interface SourceCatalog { diff --git a/src/features/database/toolRuns.ts b/src/features/database/toolRuns.ts index 258e2bc12..cf1a0dd60 100644 --- a/src/features/database/toolRuns.ts +++ b/src/features/database/toolRuns.ts @@ -1,4 +1,4 @@ -/** Runs of `pg_dump` / `pg_restore` / `psql`: they outlive the dialog that started them. */ +/** Runs of the database client tools (`pg_dump`, `mysql`…): they outlive the dialog that started them. */ import { Channel } from "@tauri-apps/api/core"; import { create } from "zustand"; import { @@ -23,6 +23,8 @@ export const TOOL_PROGRAMS: Record = { pgDump: "pg_dump", pgRestore: "pg_restore", psql: "psql", + mysqldump: "mysqldump", + mysql: "mysql", }; export interface ToolRun { diff --git a/src/features/database/treeActions.ts b/src/features/database/treeActions.ts index 833dfdf8f..5b47d6791 100644 --- a/src/features/database/treeActions.ts +++ b/src/features/database/treeActions.ts @@ -45,7 +45,7 @@ import { removeSource, } from "./store"; import { tableInput } from "./tableInput"; -import { dumpScope } from "./dumpTools"; +import { dumpScope, mysqlDumpScope } from "./dumpTools"; import { tx } from "@/platform/i18n"; import { chooseItem } from "@/workbench/inputDialogs"; import { databaseRequest } from "./requests"; @@ -468,6 +468,29 @@ export function registerDatabaseTreeActions(): () => void { openDialog({ kind: "restore", target: scope.target, database: scope.database, serverVersion }); }, }), + tree({ + id: "db.dumpWithMysqldump", + title: "Export with 'mysqldump'…", + icon: "export", + keywords: ["backup", "dump", "mysql", "mariadb"], + run: async ({ arg }) => { + const n = nodeFrom(arg); + const scope = n && mysqlDumpScope(n, sourceOf(n)); + if (scope && (await connect(scope.target))) openDialog({ kind: "mysqlDump", ...scope }); + }, + }), + tree({ + id: "db.restoreWithMysql", + title: "Restore with 'mysql'…", + icon: "download", + keywords: ["backup", "restore", "load dump", "mysql", "mariadb"], + run: async ({ arg }) => { + const n = nodeFrom(arg); + const scope = n && mysqlDumpScope(n, sourceOf(n)); + if (scope && (await connect(scope.target))) + openDialog({ kind: "mysqlRestore", target: scope.target, database: scope.database }); + }, + }), tree({ id: "db.copyReference", title: "Copy Reference", diff --git a/src/features/database/treeMenu.ts b/src/features/database/treeMenu.ts index 0456660cd..06bd37834 100644 --- a/src/features/database/treeMenu.ts +++ b/src/features/database/treeMenu.ts @@ -8,7 +8,7 @@ import { SCRIPT_LABELS, canDrop, canModifyTable, canRename, type ScriptKind } fr import { connectedTargets, openDialog, openSourceDialog, sourceById, useDatabase } from "./store"; import { readClipboardPlainText } from "@/platform/clipboard"; import { useRemote } from "@/platform/remote"; -import { dumpScope } from "./dumpTools"; +import { dumpScope, mysqlDumpScope } from "./dumpTools"; const act = ( action: string, @@ -83,14 +83,17 @@ function sqlScripts(n: DbNode, table: boolean): MenuItem { return { label: "SQL Scripts", submenu: [act("db.ddlToClipboard", n), act("db.ddlToConsole", n), sep, ...scripts] }; } -/** Export with 'pg_dump' / Restore of a PostgreSQL node; the tools run on this machine, so not in remote windows. */ +/** Export / Restore with the client tools of a PostgreSQL or MySQL node; they run on this machine, so not in remote windows. */ function dumpItems(n: DbNode, restore: boolean): MenuItem[] { const source = sourceById(nodeTarget(n)); - if (useRemote.getState().session || !dumpScope(n, source)) return []; - return [ - act("db.dumpWithPgDump", n), - ...(restore ? [act("db.restoreWithPgRestore", n, { disabled: !!source?.readOnly })] : []), - ]; + if (useRemote.getState().session) return []; + const [dump, load] = dumpScope(n, source) + ? ["db.dumpWithPgDump", "db.restoreWithPgRestore"] + : mysqlDumpScope(n, source) + ? ["db.dumpWithMysqldump", "db.restoreWithMysql"] + : []; + if (!dump || !load) return []; + return [act(dump, n), ...(restore ? [act(load, n, { disabled: !!source?.readOnly })] : [])]; } function importExport(items: MenuItem[]): MenuItem[] { diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 0b1d1f681..e8d8ebd87 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2310,6 +2310,41 @@ "{program} failed: {label}": "{program} failed: {label}", "{program} finished: {label}": "{program} finished: {label}", "{program} was not found. Install the PostgreSQL client tools or choose the executable.": "{program} was not found. Install the PostgreSQL client tools or choose the executable.", + "Choose from the server…": "Choose from the server…", + "Database {database} does not exist.": "Database {database} does not exist.", + "This dump does not create its database. Choose the database to restore into.": "This dump does not create its database. Choose the database to restore into.", + "The dump creates the databases it names.": "The dump creates the databases it names.", + "pg_restore connects to {database} and creates the database the archive names.": "pg_restore connects to {database} and creates the database the archive names.", + "The dump creates its own database. psql connects to {database} first.": "The dump creates its own database. psql connects to {database} first.", + "Create the database from the archive (--create)": "Create the database from the archive (--create)", + "{program} printed no output.": "{program} printed no output.", + "Export with 'mysqldump'…": "Export with 'mysqldump'…", + "Restore with 'mysql'…": "Restore with 'mysql'…", + "Export with 'mysqldump' ({target})": "Export with 'mysqldump' ({target})", + "Restore with 'mysql' ({target})": "Restore with 'mysql' ({target})", + "{program} was not found. Install the MySQL or MariaDB client tools or choose the executable.": "{program} was not found. Install the MySQL or MariaDB client tools or choose the executable.", + "This is a PostgreSQL dump: restore it into a PostgreSQL data source.": "This is a PostgreSQL dump: restore it into a PostgreSQL data source.", + "Add DROP TABLE before CREATE TABLE": "Add DROP TABLE before CREATE TABLE", + "Include column names in each INSERT": "Include column names in each INSERT", + "Add DISABLE KEYS before each INSERT block": "Add DISABLE KEYS before each INSERT block", + "Include all table options in CREATE TABLE": "Include all table options in CREATE TABLE", + "Add LOCK TABLES around each table": "Add LOCK TABLES around each table", + "Include stored routines": "Include stored routines", + "Add DROP TRIGGER before CREATE TRIGGER": "Add DROP TRIGGER before CREATE TRIGGER", + "Include scheduled events": "Include scheduled events", + "Export schema without data": "Export schema without data", + "Consistent snapshot (--single-transaction)": "Consistent snapshot (--single-transaction)", + "Lock all tables for the whole export (needs RELOAD)": "Lock all tables for the whole export (needs RELOAD)", + "Include masking policies": "Include masking policies", + "Databases to dump:": "Databases to dump:", + "Databases to dump": "Databases to dump", + "Tables to dump:": "Tables to dump:", + "Tables to dump": "Tables to dump", + "all databases": "all databases", + "Tables can be chosen when one database is dumped": "Tables can be chosen when one database is dumped", + "As named in the dump": "As named in the dump", + "Continue after errors (--force)": "Continue after errors (--force)", + "mysql runs the SQL dump that mysqldump wrote.": "mysql runs the SQL dump that mysqldump wrote.", "{version}: older than the server (PostgreSQL {server}), which pg_dump refuses. Choose version {server} or newer.": "{version}: older than the server (PostgreSQL {server}), which pg_dump refuses. Choose version {server} or newer.", "{version}: newer than the server (PostgreSQL {server}). What it writes may not load into PostgreSQL {server}. Install the PostgreSQL {server} client tools to restore into this server.": "{version}: newer than the server (PostgreSQL {server}). What it writes may not load into PostgreSQL {server}. Install the PostgreSQL {server} client tools to restore into this server.", "Copy Output": "Copy Output", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index fc17d0c11..4e387c7d0 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -8696,6 +8696,41 @@ "{program} failed: {label}": "{program} 失败:{label}", "{program} finished: {label}": "{program} 已完成:{label}", "{program} was not found. Install the PostgreSQL client tools or choose the executable.": "未找到 {program}。请安装 PostgreSQL 客户端工具或选择可执行文件。", + "Choose from the server…": "从服务器中选择…", + "Database {database} does not exist.": "数据库 {database} 不存在。", + "This dump does not create its database. Choose the database to restore into.": "此转储不会创建数据库。请选择要恢复到的数据库。", + "The dump creates the databases it names.": "转储会创建其中指定的数据库。", + "pg_restore connects to {database} and creates the database the archive names.": "pg_restore 连接到 {database},并创建归档中指定的数据库。", + "The dump creates its own database. psql connects to {database} first.": "转储会自行创建数据库。psql 会先连接到 {database}。", + "Create the database from the archive (--create)": "根据归档创建数据库(--create)", + "{program} printed no output.": "{program} 没有输出。", + "Export with 'mysqldump'…": "使用 'mysqldump' 导出…", + "Restore with 'mysql'…": "使用 'mysql' 恢复…", + "Export with 'mysqldump' ({target})": "使用 'mysqldump' 导出({target})", + "Restore with 'mysql' ({target})": "使用 'mysql' 恢复({target})", + "{program} was not found. Install the MySQL or MariaDB client tools or choose the executable.": "未找到 {program}。请安装 MySQL 或 MariaDB 客户端工具或选择可执行文件。", + "This is a PostgreSQL dump: restore it into a PostgreSQL data source.": "这是 PostgreSQL 转储:请恢复到 PostgreSQL 数据源。", + "Add DROP TABLE before CREATE TABLE": "在 CREATE TABLE 之前添加 DROP TABLE", + "Include column names in each INSERT": "在每个 INSERT 中包含列名", + "Add DISABLE KEYS before each INSERT block": "在每个 INSERT 块前添加 DISABLE KEYS", + "Include all table options in CREATE TABLE": "在 CREATE TABLE 中包含所有表选项", + "Add LOCK TABLES around each table": "在每个表周围添加 LOCK TABLES", + "Include stored routines": "包含存储过程和函数", + "Add DROP TRIGGER before CREATE TRIGGER": "在 CREATE TRIGGER 之前添加 DROP TRIGGER", + "Include scheduled events": "包含计划事件", + "Export schema without data": "仅导出结构,不含数据", + "Consistent snapshot (--single-transaction)": "一致性快照(--single-transaction)", + "Lock all tables for the whole export (needs RELOAD)": "整个导出期间锁定所有表(需要 RELOAD 权限)", + "Include masking policies": "包含数据脱敏策略", + "Databases to dump:": "要转储的数据库:", + "Databases to dump": "要转储的数据库", + "Tables to dump:": "要转储的表:", + "Tables to dump": "要转储的表", + "all databases": "所有数据库", + "Tables can be chosen when one database is dumped": "仅转储一个数据库时才能选择表", + "As named in the dump": "使用转储中的名称", + "Continue after errors (--force)": "出错后继续(--force)", + "mysql runs the SQL dump that mysqldump wrote.": "mysql 执行 mysqldump 生成的 SQL 转储。", "{version}: older than the server (PostgreSQL {server}), which pg_dump refuses. Choose version {server} or newer.": "{version}:比服务器(PostgreSQL {server})旧,pg_dump 会拒绝运行。请选择 {server} 或更高版本。", "{version}: newer than the server (PostgreSQL {server}). What it writes may not load into PostgreSQL {server}. Install the PostgreSQL {server} client tools to restore into this server.": "{version}:比服务器(PostgreSQL {server})新。它写出的内容可能无法载入 PostgreSQL {server}。如需恢复到此服务器,请安装 PostgreSQL {server} 客户端工具。", "Copy Output": "复制输出",