second-brain-core 0.13.4

Core library for second-brain: SQLite storage with vector and lexical indexes, BGE embeddings, and hybrid retrieval
Documentation
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,
    /// No outbox row lies past the copy's index watermark, so indexes
    /// persisted at that watermark match the copy exactly.
    pub outbox_settled: bool,
}

impl SqliteStore {
    /// Writes a consistent copy of the store to `dest`, which must not
    /// exist, while writers carry on. SQLCipher attaches the output under
    /// the store's own key, so a keyed store's copy is never plaintext.
    /// SQLite does not fsync a `VACUUM INTO` output, so this does.
    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()))
    }

    /// Opens a copy `vacuum_into` wrote under this store's key and checks
    /// every page of it.
    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,
        })
    }
}