second_brain_core/sqlite_store/
backup.rs1use std::fs;
2use std::path::Path;
3
4use anyhow::{Context, Result, ensure};
5use rusqlite::{OptionalExtension, params};
6
7use super::SqliteStore;
8use super::encrypt_migration::{open_checked, path_text};
9use crate::maintenance::{LiveCounts, live_counts_on};
10
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct BackupCopy {
13 pub counts: LiveCounts,
14 pub outbox_settled: bool,
17}
18
19impl SqliteStore {
20 pub fn vacuum_into(&self, dest: &Path) -> Result<()> {
25 ensure!(
26 fs::symlink_metadata(dest).is_err(),
27 "{} already exists",
28 dest.display()
29 );
30 self.reader()
31 .execute("VACUUM INTO ?1", params![path_text(dest)?])
32 .with_context(|| format!("copying the store into {}", dest.display()))?;
33 fs::File::open(dest)
34 .and_then(|f| f.sync_all())
35 .with_context(|| format!("syncing {}", dest.display()))
36 }
37
38 pub fn check_backup_copy(&self, copy: &Path) -> Result<BackupCopy> {
41 let key = self.store_key();
42 let conn = open_checked(copy, key.as_deref(), "the backup copy")?;
43 let counts = live_counts_on(&conn)?;
44 let watermark: i64 = conn
45 .query_row(
46 "SELECT value FROM index_meta WHERE key = 'watermark'",
47 [],
48 |r| r.get::<_, String>(0),
49 )
50 .optional()?
51 .and_then(|v| v.parse().ok())
52 .unwrap_or(0);
53 let pending: bool = conn.query_row(
54 "SELECT EXISTS (SELECT 1 FROM index_outbox WHERE seq > ?1)",
55 params![watermark],
56 |r| r.get(0),
57 )?;
58 Ok(BackupCopy {
59 counts,
60 outbox_settled: !pending,
61 })
62 }
63}