Files
tessera/crates/tessera-providers/src/mysql_restore.rs
Adnan Zahir 6320b6f244 feat: add managed database capture and operator restore
PostgreSQL and MySQL backups run through paired outposts, with operator sign-in, off-site copies, and legacy import. Retention stays on each orbit, so the unused retention console is removed.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 23:26:49 +07:00

95 lines
3.3 KiB
Rust

use crate::MysqlSource;
use anyhow::{ensure, Result};
use serde::Deserialize;
use std::{
fs::File,
io::{BufRead, BufReader, Seek, SeekFrom, Write},
process::Stdio,
};
use tessera_core::restore::{DatabaseIdentity, Engine};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MysqlRestore {
pub connection: MysqlSource,
#[serde(default)]
pub recreate_database: bool,
#[serde(default)]
pub use_target_definer: bool,
}
impl MysqlRestore {
pub async fn prepare(&self, mut dump: File, expected: &DatabaseIdentity) -> Result<File> {
ensure!(
expected.valid(Engine::Mysql) && expected.database == self.connection.database(),
"MySQL target identity does not match the local profile"
);
ensure!(
!matches!(
expected.database.to_ascii_lowercase().as_str(),
"mysql" | "information_schema" | "performance_schema" | "sys"
),
"system database restore is forbidden"
);
dump.seek(SeekFrom::Start(0))?;
let mut script = tempfile::tempfile()?;
let database = mysql_hex(&expected.database);
let instance = mysql_hex(&expected.instance);
// PREPARE fails before any DDL if this connection resolves to the wrong target.
writeln!(script, "SET @tessera_guard = IF(BINARY LOWER(@@server_uuid) = {instance} AND BINARY DATABASE() = {database}, 'DO 0', 'TESSERA_RESTORE_TARGET_MISMATCH');")?;
writeln!(script, "PREPARE tessera_guard FROM @tessera_guard;\nEXECUTE tessera_guard;\nDEALLOCATE PREPARE tessera_guard;")?;
if self.recreate_database {
let name = format!("`{}`", expected.database.replace('`', "``"));
writeln!(
script,
"DROP DATABASE {name};\nCREATE DATABASE {name} CHARACTER SET utf8mb4;\nUSE {name};"
)?;
}
let use_target_definer = self.use_target_definer;
tokio::task::spawn_blocking(move || {
if use_target_definer {
let definer = regex::bytes::Regex::new(
r"^(CREATE |/\*![0-9]{5} )DEFINER=`(?:[^`]|``)*`@`(?:[^`]|``)*`",
)?;
let mut reader = BufReader::new(dump);
let mut line = Vec::new();
while reader.read_until(b'\n', &mut line)? > 0 {
script.write_all(&definer.replace(&line, &b"${1}DEFINER=CURRENT_USER"[..]))?;
line.clear();
}
} else {
std::io::copy(&mut dump, &mut script)?;
}
script.seek(SeekFrom::Start(0))?;
Ok(script)
})
.await?
}
pub async fn apply(&self, script: File) -> Result<()> {
self.connection
.run(
"mysql",
&[
"--binary-mode",
"--skip-reconnect",
"--skip-force",
"--default-character-set=utf8mb4",
],
Stdio::from(script),
Stdio::null(),
)
.await?;
Ok(())
}
}
fn mysql_hex(value: &str) -> String {
use std::fmt::Write;
let mut literal = String::from("0x");
for byte in value.bytes() {
write!(literal, "{byte:02x}").expect("writing to String cannot fail");
}
literal
}