Skip to main content

smriti/db/
connection.rs

1//! Database connection management
2
3use std::path::{Path, PathBuf};
4
5use rusqlite::{Connection, Result as SqliteResult};
6use thiserror::Error;
7
8#[derive(Error, Debug)]
9pub enum DatabaseError {
10    #[error("Failed to open database: {0}")]
11    OpenError(#[from] rusqlite::Error),
12
13    #[error("Database path does not exist: {0}")]
14    PathNotFound(PathBuf),
15
16    #[error("Failed to create .photovault directory: {0}")]
17    DirectoryCreationError(std::io::Error),
18}
19
20/// Database wrapper with path information
21pub struct Database {
22    pub conn: Connection,
23}
24
25impl Drop for Database {
26    fn drop(&mut self) {
27        // Best-effort PASSIVE checkpoint on drop. The clean-exit path
28        // already calls `flush_and_close` (TRUNCATE), so this only
29        // catches accidental drops (panics, early-return paths) and
30        // never blocks long.
31        let _ = self.conn.execute_batch("PRAGMA wal_checkpoint(PASSIVE);");
32    }
33}
34
35/// Returns the on-drive metadata directory.
36///
37/// The folder name is `.photovault` for backwards compatibility with
38/// libraries indexed before the rename — see `LIBRARY_METADATA_DIR`.
39pub fn library_metadata_dir(drive_root: &Path) -> PathBuf {
40    drive_root.join(super::LIBRARY_METADATA_DIR)
41}
42
43/// Returns the SQLite database file path for a drive root.
44///
45/// Use this when a background task needs to open its own connection
46/// to the same database — e.g. duplicate / burst detection runs in
47/// `spawn_blocking` and shouldn't compete with the shared
48/// `Arc<Mutex<Database>>` for a lock. SQLite WAL handles the
49/// concurrent reader/writer.
50pub fn db_path_for(drive_root: &Path) -> PathBuf {
51    library_metadata_dir(drive_root).join("photovault.db")
52}
53
54/// Open a fresh connection to an existing Smriti database.
55///
56/// Configures the same pragmas as `open_for_drive` so background
57/// detection tasks see the same performance profile. The journal mode
58/// was chosen when the library opened; this connection follows the file
59/// rather than detecting the drive again.
60/// Returns an error if the path doesn't exist or can't be opened.
61pub fn open_secondary(db_path: &Path) -> Result<Connection, DatabaseError> {
62    let conn = Connection::open_with_flags(
63        db_path,
64        rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
65    )?;
66    // Reading the journal mode can meet another connection's commit.
67    conn.busy_timeout(std::time::Duration::from_secs(15))?;
68    let journal: String = conn.query_row("PRAGMA journal_mode", [], |row| row.get(0))?;
69    Database::configure_connection(&conn, !journal.eq_ignore_ascii_case("wal"))?;
70    Ok(conn)
71}
72
73impl Database {
74    /// Open or create database on a drive
75    ///
76    /// # Arguments
77    /// * `drive_root` - Root path of the drive to index (e.g., "/media/photos")
78    ///
79    /// # Returns
80    /// A Database instance with an open connection
81    pub fn open_for_drive<P: AsRef<Path>>(drive_root: P) -> Result<Self, DatabaseError> {
82        let drive_root = drive_root.as_ref().to_path_buf();
83
84        if !drive_root.exists() {
85            return Err(DatabaseError::PathNotFound(drive_root));
86        }
87
88        let metadata_dir = library_metadata_dir(&drive_root);
89        if !metadata_dir.exists() {
90            std::fs::create_dir_all(&metadata_dir)
91                .map_err(DatabaseError::DirectoryCreationError)?;
92        }
93
94        let db_path = metadata_dir.join("photovault.db");
95        let conn = Connection::open(&db_path)?;
96
97        let network = super::network_drive::network_drive(&drive_root).active();
98        Self::configure_connection(&conn, network)?;
99        Self::set_journal_mode(&conn, network)?;
100
101        Ok(Self { conn })
102    }
103
104    /// Configure SQLite connection for optimal performance. `network`
105    /// selects the profile for a library on a network share (see
106    /// `network_drive`).
107    pub(crate) fn configure_connection(conn: &Connection, network: bool) -> SqliteResult<()> {
108        // Wait for a busy lock instead of failing immediately. Without
109        // this, two writers (e.g. face-processor writer thread + scanner
110        // upserts during a re-index) surface SQLITE_BUSY to the user
111        // instead of retrying. Network round-trips hold locks longer.
112        conn.pragma_update(None, "busy_timeout", if network { 15000 } else { 5000 })?;
113
114        // Balance between safety and speed. Without WAL, NORMAL can lose
115        // a commit on power loss, so the network profile syncs fully.
116        conn.pragma_update(None, "synchronous", if network { "FULL" } else { "NORMAL" })?;
117
118        // 64MB cache
119        conn.pragma_update(None, "cache_size", -64000)?;
120
121        // Temp tables in memory
122        conn.pragma_update(None, "temp_store", "MEMORY")?;
123
124        // Memory-map up to 256MB. Never over a network: another client's
125        // writes would not show up in the mapped pages.
126        conn.pragma_update(None, "mmap_size", if network { 0 } else { 268435456 })?;
127
128        // Foreign key enforcement
129        conn.pragma_update(None, "foreign_keys", "ON")?;
130
131        Ok(())
132    }
133
134    /// WAL for concurrent reads on local disks; the rollback journal on
135    /// network shares, where WAL's shared-memory index does not work.
136    /// The mode is stored in the file, so a library moved between a NAS
137    /// and a local disk switches on its next open.
138    fn set_journal_mode(conn: &Connection, network: bool) -> SqliteResult<()> {
139        if !network {
140            return conn.pragma_update(None, "journal_mode", "WAL");
141        }
142        // Leaving WAL reads the WAL index, which on a share may be
143        // unusable. EXCLUSIVE locking keeps that index in private memory
144        // instead; normal locking returns afterwards so background
145        // connections can share the file.
146        conn.pragma_update(None, "locking_mode", "EXCLUSIVE")?;
147        let switched = conn.query_row("PRAGMA journal_mode = DELETE", [], |row| {
148            row.get::<_, String>(0)
149        });
150        conn.pragma_update(None, "locking_mode", "NORMAL")?;
151        // The exclusive lock is released on the next access.
152        conn.query_row("SELECT COUNT(*) FROM sqlite_master", [], |_| Ok(()))?;
153        match switched {
154            Ok(mode) if mode.eq_ignore_ascii_case("delete") => {}
155            // Still usable, just without the safer journal. Retried on the
156            // next open.
157            Ok(mode) => tracing::warn!("network library stays in {mode} journal mode"),
158            Err(e) => tracing::warn!("network library could not leave WAL mode: {e}"),
159        }
160        Ok(())
161    }
162
163    /// Check if this is a fresh database (needs schema creation)
164    pub fn needs_schema(&self) -> SqliteResult<bool> {
165        let count: i32 = self.conn.query_row(
166            "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='photos'",
167            [],
168            |row| row.get(0),
169        )?;
170        Ok(count == 0)
171    }
172
173    /// Aggressively flush WAL to the main DB file and consume the
174    /// connection. Use on drive deselect / app exit so a yanked USB
175    /// drive doesn't leave unwritten data behind. TRUNCATE is the
176    /// strict mode (vs PASSIVE) — it both checkpoints AND empties the
177    /// WAL file.
178    pub fn flush_and_close(self) {
179        if let Err(e) = self.conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);") {
180            tracing::debug!("WAL truncate-checkpoint failed: {}", e);
181        }
182        // Connection drops here, releasing file handles.
183    }
184
185    /// Flush WAL into the main DB file while the connection stays open.
186    /// Called on app exit (the shared connection is behind an Arc, so it
187    /// cannot be consumed like `flush_and_close`) so a drive yanked or a
188    /// catalog copied right after the window closes cannot lose recent
189    /// commits that were still sitting in the WAL. Best-effort: a
190    /// checkpoint blocked by readers is skipped rather than awaited.
191    pub fn checkpoint_truncate(&self) {
192        if let Err(e) = self.conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);") {
193            tracing::debug!("exit WAL checkpoint failed: {}", e);
194        }
195    }
196
197    /// Create a backup of the database file.
198    ///
199    /// Takes a consistent SQLite snapshot, including committed WAL transactions.
200    pub fn backup(drive_root: &Path, max_backups: usize) -> std::io::Result<PathBuf> {
201        if max_backups == 0 {
202            return Err(std::io::Error::new(
203                std::io::ErrorKind::InvalidInput,
204                "max_backups must be positive",
205            ));
206        }
207        let db_path = library_metadata_dir(drive_root).join("photovault.db");
208        if !db_path.exists() {
209            return Err(std::io::Error::new(
210                std::io::ErrorKind::NotFound,
211                "Database file not found",
212            ));
213        }
214
215        let backup_dir = library_metadata_dir(drive_root).join("backups");
216        std::fs::create_dir_all(&backup_dir)?;
217
218        // Name with timestamp
219        let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S_%f");
220        let backup_path = backup_dir.join(format!("photovault_{}.db", timestamp));
221
222        let conn = open_secondary(&db_path).map_err(std::io::Error::other)?;
223        conn.execute("VACUUM INTO ?1", [backup_path.to_string_lossy().as_ref()])
224            .map_err(std::io::Error::other)?;
225
226        // Clean old backups (keep max_backups newest)
227        let mut backups: Vec<_> = std::fs::read_dir(&backup_dir)?
228            .filter_map(|e| e.ok())
229            .filter(|e| {
230                e.path()
231                    .file_name()
232                    .and_then(|n| n.to_str())
233                    .map(|n| n.starts_with("photovault_") && n.ends_with(".db"))
234                    .unwrap_or(false)
235            })
236            .collect();
237
238        backups.sort_by_key(|e| std::cmp::Reverse(e.path()));
239
240        for old in backups.into_iter().skip(max_backups) {
241            let _ = std::fs::remove_file(old.path());
242        }
243
244        tracing::info!("Database backed up to {}", backup_path.display());
245        Ok(backup_path)
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252    use tempfile::tempdir;
253
254    #[test]
255    fn test_open_for_drive() {
256        let temp = tempdir().unwrap();
257        let db = Database::open_for_drive(temp.path()).unwrap();
258
259        let table_count: i64 = db
260            .conn
261            .query_row(
262                "SELECT COUNT(*) FROM sqlite_master WHERE type='table'",
263                [],
264                |row| row.get(0),
265            )
266            .unwrap();
267        assert!(table_count >= 0);
268        assert!(temp.path().join(".photovault").exists());
269    }
270}