use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::Duration;
use rusqlite::backup::{Backup, StepResult};
use rusqlite::{Connection, OpenFlags};
use super::connection::sql_error;
use crate::{Error, Result};
#[derive(Debug)]
pub(crate) struct Drafts {
pub(crate) copy: PathBuf,
pub(crate) redo: bool,
pub(crate) command: String,
}
const FLAGS: OpenFlags =
OpenFlags::SQLITE_OPEN_READ_WRITE.union(OpenFlags::SQLITE_OPEN_NO_MUTEX).union(OpenFlags::SQLITE_OPEN_EXRESCODE);
pub(super) fn keep(path: &Path, copy: &Path, busy_timeout: Duration) -> Result<()> {
let what = || format!("copy {} to {} before its drafts", path.display(), copy.display());
remove(copy).map_err(|error| error.within(what()))?;
let into = copy.to_str().ok_or_else(|| Error::invalid(format!("{}: a path that is no UTF-8", copy.display())))?;
let connection = own(path, busy_timeout).map_err(|error| sql_error(what(), error))?;
connection.execute("vacuum into ?1", [into]).map(drop).map_err(|error| sql_error(what(), error))
}
pub(super) fn take_back(path: &Path, copy: &Path, busy_timeout: Duration) -> Result<()> {
let what = || format!("take {} back to {}", path.display(), copy.display());
if !copy.is_file() {
return Err(Error::invalid(format!(
"{}: the copy of the database from before its drafts is gone, so nothing takes them back",
copy.display()
)));
}
let source = Connection::open_with_flags(copy, FLAGS).map_err(|error| sql_error(what(), error))?;
let mut target = own(path, busy_timeout).map_err(|error| sql_error(what(), error))?;
let backup = Backup::new(&source, &mut target).map_err(|error| sql_error(what(), error))?;
match backup.step(-1).map_err(|error| sql_error(what(), error))? {
StepResult::Done => {}
other => return Err(Error::internal(format!("{}: stopped short: {other:?}", what()))),
}
drop(backup);
drop(source);
remove(copy).map_err(|error| error.within(what()))
}
pub(super) fn remove(copy: &Path) -> Result<()> {
match fs::remove_file(copy) {
Ok(()) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(Error::io(copy.display().to_string(), error)),
}
}
fn own(path: &Path, busy_timeout: Duration) -> rusqlite::Result<Connection> {
super::give_mutexes();
let connection = Connection::open_with_flags(path, FLAGS)?;
connection.busy_timeout(busy_timeout)?;
Ok(connection)
}