use std::fs;
use std::path::Path;
use anyhow::{Context, Result, ensure};
use rusqlite::{OptionalExtension, params};
use super::SqliteStore;
use super::encrypt_migration::{open_checked, path_text};
use crate::maintenance::{LiveCounts, live_counts_on};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BackupCopy {
pub counts: LiveCounts,
pub outbox_settled: bool,
}
impl SqliteStore {
pub fn vacuum_into(&self, dest: &Path) -> Result<()> {
ensure!(
fs::symlink_metadata(dest).is_err(),
"{} already exists",
dest.display()
);
self.reader()
.execute("VACUUM INTO ?1", params![path_text(dest)?])
.with_context(|| format!("copying the store into {}", dest.display()))?;
fs::File::open(dest)
.and_then(|f| f.sync_all())
.with_context(|| format!("syncing {}", dest.display()))
}
pub fn check_backup_copy(&self, copy: &Path) -> Result<BackupCopy> {
let key = self.store_key();
let conn = open_checked(copy, key.as_deref(), "the backup copy")?;
let counts = live_counts_on(&conn)?;
let watermark: i64 = conn
.query_row(
"SELECT value FROM index_meta WHERE key = 'watermark'",
[],
|r| r.get::<_, String>(0),
)
.optional()?
.and_then(|v| v.parse().ok())
.unwrap_or(0);
let pending: bool = conn.query_row(
"SELECT EXISTS (SELECT 1 FROM index_outbox WHERE seq > ?1)",
params![watermark],
|r| r.get(0),
)?;
Ok(BackupCopy {
counts,
outbox_settled: !pending,
})
}
}