surrealpatch/src/cli/export.rs

45 lines
1.5 KiB
Rust
Raw Normal View History

2022-07-19 08:28:24 +00:00
use crate::cli::LOG;
use crate::cnf::SERVER_AGENT;
2022-02-16 23:45:23 +00:00
use crate::err::Error;
2020-06-29 15:36:01 +00:00
use reqwest::blocking::Client;
2022-09-27 15:35:03 +00:00
use reqwest::header::ACCEPT;
use reqwest::header::USER_AGENT;
2020-06-29 15:36:01 +00:00
use std::fs::OpenOptions;
pub fn init(matches: &clap::ArgMatches) -> Result<(), Error> {
// Set the default logging level
crate::cli::log::init(3);
// Try to parse the file argument
2020-06-29 15:36:01 +00:00
let file = matches.value_of("file").unwrap();
// Try to open the specified file
2021-03-29 15:43:37 +00:00
let mut file = OpenOptions::new().write(true).create(true).truncate(true).open(file)?;
2020-06-29 15:36:01 +00:00
// Parse all other cli arguments
let user = matches.value_of("user").unwrap();
let pass = matches.value_of("pass").unwrap();
let conn = matches.value_of("conn").unwrap();
let ns = matches.value_of("ns").unwrap();
let db = matches.value_of("db").unwrap();
// Set the correct export URL
let conn = format!("{conn}/export");
// Export the data from the database
let mut res = Client::new()
.get(conn)
.header(USER_AGENT, SERVER_AGENT)
.header(ACCEPT, "application/octet-stream")
2020-06-29 15:36:01 +00:00
.basic_auth(user, Some(pass))
.header("NS", ns)
.header("DB", db)
.send()?;
// Check import result and report error
if res.status().is_success() {
res.copy_to(&mut file)?;
info!(target: LOG, "The SQL file was exported successfully");
} else if res.status().is_client_error() || res.status().is_server_error() {
error!(target: LOG, "Request failed with status {}. Body: {}", res.status(), res.text()?);
} else {
error!(target: LOG, "Unexpected response status {}", res.status());
}
// Everything OK
2020-06-29 15:36:01 +00:00
Ok(())
}