Skip to main content

capsule_library/db/
driver.rs

1use std::cell::{Cell, RefCell};
2use std::collections::{BTreeSet, HashMap, HashSet};
3use std::path::Path;
4
5use capsule_core::domain::model_identity::TaskKind;
6use rusqlite::{Connection, params};
7
8use crate::db::album_order::AlbumRecency;
9use crate::db::migrate::{self, MigrationError};
10use crate::db::rows::{AlbumRow, AssetRow, AssetStackRow, CachedRepresentationRow, StackMemberRow};
11
12pub struct DatabaseDriver {
13    pub(in crate::db) conn: Connection,
14    /// Tasks whose `vec0` partition table this driver has already created. The DDL is idempotent,
15    /// so this is purely a hot-path memo — see [`crate::db::VectorTableSpec`] for why the
16    /// tables are created by their writer rather than at open time.
17    pub(in crate::db) vector_tables: RefCell<BTreeSet<TaskKind>>,
18    /// How many [`with_transaction`](Self::with_transaction) scopes are open right now. Each
19    /// scope names its `SAVEPOINT` after its depth, so a nested scope's `ROLLBACK TO` can never
20    /// reach past its own savepoint into the enclosing one's writes.
21    savepoint_depth: Cell<u32>,
22}
23
24/// One open [`DatabaseDriver::with_transaction`] scope.
25///
26/// Rolls its savepoint back on drop unless [`release`](Self::release) succeeded, so an `Err`
27/// from the scope's body, a failed `RELEASE`, or a panic all leave the catalog exactly as the
28/// scope found it. Always restores the driver's depth counter.
29struct SavepointGuard<'d> {
30    driver: &'d DatabaseDriver,
31    name: String,
32    open: bool,
33}
34
35impl<'d> SavepointGuard<'d> {
36    fn begin(driver: &'d DatabaseDriver) -> Result<Self, rusqlite::Error> {
37        let depth = driver.savepoint_depth.get() + 1;
38        let name = format!("capsule_sp_{depth}");
39        // An outermost `SAVEPOINT` (autocommit mode) opens a transaction exactly as `BEGIN`
40        // does, and releasing it commits; inside a transaction it nests. One statement covers
41        // both, so the commit point is always "the outermost scope released".
42        let outermost = driver.conn.is_autocommit();
43        driver.conn.execute_batch(&format!("SAVEPOINT {name}"))?;
44        driver.savepoint_depth.set(depth);
45        tracing::trace!(savepoint = %name, outermost, "catalog: savepoint opened");
46        Ok(Self {
47            driver,
48            name,
49            open: true,
50        })
51    }
52
53    fn release(mut self) -> Result<(), rusqlite::Error> {
54        self.driver
55            .conn
56            .execute_batch(&format!("RELEASE {}", self.name))?;
57        self.open = false;
58        tracing::trace!(savepoint = %self.name, "catalog: savepoint released");
59        Ok(())
60    }
61}
62
63impl Drop for SavepointGuard<'_> {
64    fn drop(&mut self) {
65        if self.open {
66            // `ROLLBACK TO` undoes the scope's writes but leaves the savepoint on the stack;
67            // the `RELEASE` pops it (and, for an outermost scope, ends the now-empty
68            // transaction).
69            let rolled_back = self.driver.conn.execute_batch(&format!(
70                "ROLLBACK TO {name}; RELEASE {name}",
71                name = self.name
72            ));
73            match rolled_back {
74                Ok(()) => tracing::debug!(savepoint = %self.name, "catalog: savepoint rolled back"),
75                Err(e) => tracing::warn!(
76                    savepoint = %self.name,
77                    error = %e,
78                    "catalog: savepoint rollback failed; the enclosing transaction (if any) still owns the writes"
79                ),
80            }
81        }
82        self.driver
83            .savepoint_depth
84            .set(self.driver.savepoint_depth.get().saturating_sub(1));
85    }
86}
87
88impl DatabaseDriver {
89    /// Open (or create) the catalog at `path` and bring it to the crate's `SCHEMA_VERSION`.
90    ///
91    /// The migrator's typed [`MigrationError`] is flattened into `rusqlite::Error` here
92    /// because this signature is consumed by `capsule-core-ffi`; the crate's own library
93    /// opener goes through the crate-private `open_typed` so a catalog newer than this build
94    /// surfaces as a typed refusal rather than a message inside a `SqliteFailure`.
95    pub fn open(path: &Path) -> Result<Self, rusqlite::Error> {
96        Self::open_typed(path).map_err(rusqlite::Error::from)
97    }
98
99    /// As [`open`](Self::open), keeping the migrator's typed error.
100    ///
101    /// [`MigrationError::CatalogTooNew`] is the one variant a caller acts on differently: the
102    /// catalog was left untouched and the recovery is to update the app, so `library::open`
103    /// maps it to [`LibraryError::CatalogTooNew`](crate::library::LibraryError::CatalogTooNew)
104    /// instead of folding it into a generic database error.
105    pub(crate) fn open_typed(path: &Path) -> Result<Self, MigrationError> {
106        crate::db::vector::ensure_vec_extension();
107        let conn = Connection::open(path)?;
108        let driver = Self::new(conn);
109        driver.migrate()?;
110        Ok(driver)
111    }
112
113    pub fn open_in_memory() -> Result<Self, rusqlite::Error> {
114        crate::db::vector::ensure_vec_extension();
115        let conn = Connection::open_in_memory()?;
116        let driver = Self::new(conn);
117        driver.init_schema()?;
118        Ok(driver)
119    }
120
121    fn new(conn: Connection) -> Self {
122        Self {
123            conn,
124            vector_tables: RefCell::new(BTreeSet::new()),
125            savepoint_depth: Cell::new(0),
126        }
127    }
128
129    // ── Transactions ─────────────────────────────────────────────────────────
130
131    /// Run `f` atomically: every catalog write it makes through this driver lands together or
132    /// not at all.
133    ///
134    /// Outside any transaction the scope is its own transaction and commits when `f` returns
135    /// `Ok`. Inside one — a [`begin_batch`](Self::begin_batch) batch, or an enclosing
136    /// `with_transaction` — it nests as a `SAVEPOINT`: `Ok` folds `f`'s writes into the
137    /// enclosing transaction (which commits them later), and `Err` (or a panic) rolls back
138    /// **only** `f`'s writes, leaving everything the enclosing transaction already wrote in
139    /// place. That is what lets a per-asset index write sit inside an import batch without one
140    /// failed asset costing its neighbours their rows.
141    pub fn with_transaction<T, E>(&self, f: impl FnOnce() -> Result<T, E>) -> Result<T, E>
142    where
143        E: From<rusqlite::Error>,
144    {
145        let guard = SavepointGuard::begin(self)?;
146        let value = f()?;
147        guard.release()?;
148        Ok(value)
149    }
150
151    /// Whether a transaction is open on the catalog connection — a
152    /// [`begin_batch`](Self::begin_batch) batch or a [`with_transaction`](Self::with_transaction)
153    /// scope. While it is, nothing written since it opened is durable yet.
154    pub fn in_transaction(&self) -> bool {
155        !self.conn.is_autocommit()
156    }
157
158    /// Open a batch: one outer transaction that every following write (each
159    /// [`with_transaction`](Self::with_transaction) scope nesting inside it as a savepoint)
160    /// joins until [`commit_batch`](Self::commit_batch). Bulk import uses it so a run of assets
161    /// costs one catalog commit instead of several per asset.
162    ///
163    /// Refused if a transaction is already open: batches do not nest, and silently joining
164    /// someone else's transaction would move this batch's commit point out of the caller's
165    /// control.
166    pub fn begin_batch(&self) -> Result<(), rusqlite::Error> {
167        self.conn.execute_batch("BEGIN")?;
168        tracing::debug!("catalog: batch opened");
169        Ok(())
170    }
171
172    /// Commit the batch [`begin_batch`](Self::begin_batch) opened, making every write in it
173    /// durable. On failure the batch's writes are rolled back rather than left pending, so the
174    /// connection is never stranded inside a transaction.
175    pub fn commit_batch(&self) -> Result<(), rusqlite::Error> {
176        if let Err(e) = self.conn.execute_batch("COMMIT") {
177            tracing::warn!(error = %e, "catalog: batch commit failed; rolling the batch back");
178            if !self.conn.is_autocommit() {
179                let _ = self.conn.execute_batch("ROLLBACK");
180            }
181            return Err(e);
182        }
183        tracing::debug!("catalog: batch committed");
184        Ok(())
185    }
186
187    /// Bring the catalog to the crate's `SCHEMA_VERSION`, creating it if the database is empty
188    /// and otherwise migrating it forward (see the crate-private `db::migrate`).
189    ///
190    /// The migrator's typed [`MigrationError`] is flattened into `rusqlite::Error` here because
191    /// this signature is consumed by `capsule-core-ffi` and `library::open`; callers that want
192    /// the typed error (and the list of steps applied) call [`Self::migrate`] instead.
193    pub fn init_schema(&self) -> Result<(), rusqlite::Error> {
194        // The per-task `vec0` tables are deliberately NOT created here: their column width and
195        // metric come from the model that writes them, which this layer knows nothing about.
196        // Each is created on first insert/query from the spec its writer declares, or eagerly via
197        // [`DatabaseDriver::create_vector_tables`].
198        self.migrate()?;
199        Ok(())
200    }
201
202    /// Bring the catalog to the crate's `SCHEMA_VERSION`, reporting exactly what ran.
203    ///
204    /// Refuses (without writing anything) a catalog stamped newer than this build supports —
205    /// see [`MigrationError::CatalogTooNew`].
206    pub fn migrate(&self) -> Result<migrate::Outcome, MigrationError> {
207        migrate::migrate(&self.conn)
208    }
209
210    /// The underlying connection, for schema-level assertions inside `crate::db`'s tests.
211    #[cfg(test)]
212    pub(crate) fn connection(&self) -> &Connection {
213        &self.conn
214    }
215
216    pub fn schema_version(&self) -> Result<u32, rusqlite::Error> {
217        let version: u32 = self
218            .conn
219            .query_row("PRAGMA user_version", [], |row| row.get(0))?;
220        Ok(version)
221    }
222
223    pub fn insert_asset(&self, row: &AssetRow) -> Result<(), rusqlite::Error> {
224        self.conn.execute(
225            "INSERT INTO assets (uuid, asset_type, capture_timestamp, capture_utc, capture_tz_source,
226             import_timestamp, hash_sha256, width, height, duration_ms, stack_id, is_stack_hidden,
227             chromahash, dominant_color, album_id, rating, is_deleted, deleted_at, is_hidden,
228             caption, latitude, longitude)
229             VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20,?21,?22)",
230            params![
231                row.uuid, row.asset_type, row.capture_timestamp, row.capture_utc,
232                row.capture_tz_source, row.import_timestamp, row.hash_sha256,
233                row.width, row.height, row.duration_ms, row.stack_id,
234                row.is_stack_hidden as i64, row.chromahash, row.dominant_color,
235                row.album_id, row.rating, row.is_deleted as i64, row.deleted_at,
236                row.is_hidden as i64, stored_caption(row.caption.as_deref()),
237                row.latitude, row.longitude,
238            ],
239        )?;
240        Ok(())
241    }
242
243    pub fn upsert_asset(&self, row: &AssetRow) -> Result<(), rusqlite::Error> {
244        self.conn.execute(
245            "INSERT OR REPLACE INTO assets (uuid, asset_type, capture_timestamp, capture_utc, capture_tz_source,
246             import_timestamp, hash_sha256, width, height, duration_ms, stack_id, is_stack_hidden,
247             chromahash, dominant_color, album_id, rating, is_deleted, deleted_at, is_hidden,
248             caption, latitude, longitude)
249             VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18,?19,?20,?21,?22)",
250            params![
251                row.uuid, row.asset_type, row.capture_timestamp, row.capture_utc,
252                row.capture_tz_source, row.import_timestamp, row.hash_sha256,
253                row.width, row.height, row.duration_ms, row.stack_id,
254                row.is_stack_hidden as i64, row.chromahash, row.dominant_color,
255                row.album_id, row.rating, row.is_deleted as i64, row.deleted_at,
256                row.is_hidden as i64, stored_caption(row.caption.as_deref()),
257                row.latitude, row.longitude,
258            ],
259        )?;
260        Ok(())
261    }
262
263    pub fn find_by_uuid(&self, uuid: &str) -> Result<Option<AssetRow>, rusqlite::Error> {
264        let mut stmt = self.conn.prepare(
265            "SELECT uuid, asset_type, capture_timestamp, capture_utc, capture_tz_source,
266             import_timestamp, hash_sha256, width, height, duration_ms, stack_id, is_stack_hidden,
267             chromahash, dominant_color, album_id, rating, is_deleted, deleted_at, is_hidden,
268             caption, latitude, longitude
269             FROM assets WHERE uuid = ?1 LIMIT 1",
270        )?;
271        let mut rows = stmt.query_map(params![uuid], map_asset_row)?;
272        match rows.next() {
273            Some(r) => Ok(Some(r?)),
274            None => Ok(None),
275        }
276    }
277
278    pub fn find_by_hash(&self, hash: &str) -> Result<Option<AssetRow>, rusqlite::Error> {
279        let mut stmt = self.conn.prepare(
280            "SELECT uuid, asset_type, capture_timestamp, capture_utc, capture_tz_source,
281             import_timestamp, hash_sha256, width, height, duration_ms, stack_id, is_stack_hidden,
282             chromahash, dominant_color, album_id, rating, is_deleted, deleted_at, is_hidden,
283             caption, latitude, longitude
284             FROM assets WHERE hash_sha256 = ?1 LIMIT 1",
285        )?;
286        let mut rows = stmt.query_map(params![hash], map_asset_row)?;
287        match rows.next() {
288            Some(r) => Ok(Some(r?)),
289            None => Ok(None),
290        }
291    }
292
293    pub fn query_timeline(
294        &self,
295        offset: usize,
296        limit: usize,
297    ) -> Result<Vec<AssetRow>, rusqlite::Error> {
298        let mut stmt = self.conn.prepare(
299            "SELECT uuid, asset_type, capture_timestamp, capture_utc, capture_tz_source,
300             import_timestamp, hash_sha256, width, height, duration_ms, stack_id, is_stack_hidden,
301             chromahash, dominant_color, album_id, rating, is_deleted, deleted_at, is_hidden,
302             caption, latitude, longitude
303             FROM assets
304             WHERE is_deleted = 0 AND is_stack_hidden = 0 AND is_hidden = 0
305             ORDER BY COALESCE(capture_utc, capture_timestamp) DESC
306             LIMIT ?1 OFFSET ?2",
307        )?;
308        let rows = stmt.query_map(params![limit as i64, offset as i64], map_asset_row)?;
309        rows.collect()
310    }
311
312    /// Query the timeline filtered by asset type and/or capture-time window.
313    ///
314    /// `after`/`before` bound `COALESCE(capture_utc, capture_timestamp)`
315    /// (inclusive). Any filter argument left as `None` is not applied.
316    pub fn query_timeline_filtered(
317        &self,
318        asset_type: Option<&str>,
319        after: Option<i64>,
320        before: Option<i64>,
321        offset: usize,
322        limit: usize,
323    ) -> Result<Vec<AssetRow>, rusqlite::Error> {
324        let mut stmt = self.conn.prepare(
325            "SELECT uuid, asset_type, capture_timestamp, capture_utc, capture_tz_source,
326             import_timestamp, hash_sha256, width, height, duration_ms, stack_id, is_stack_hidden,
327             chromahash, dominant_color, album_id, rating, is_deleted, deleted_at, is_hidden,
328             caption, latitude, longitude
329             FROM assets
330             WHERE is_deleted = 0 AND is_stack_hidden = 0 AND is_hidden = 0
331               AND (?1 IS NULL OR asset_type = ?1)
332               AND (?2 IS NULL OR COALESCE(capture_utc, capture_timestamp) >= ?2)
333               AND (?3 IS NULL OR COALESCE(capture_utc, capture_timestamp) <= ?3)
334             ORDER BY COALESCE(capture_utc, capture_timestamp) DESC
335             LIMIT ?4 OFFSET ?5",
336        )?;
337        let rows = stmt.query_map(
338            params![asset_type, after, before, limit as i64, offset as i64],
339            map_asset_row,
340        )?;
341        rows.collect()
342    }
343
344    pub fn insert_stack(&self, row: &AssetStackRow) -> Result<(), rusqlite::Error> {
345        self.conn.execute(
346            "INSERT INTO asset_stacks (id, stack_type, primary_asset_id, cover_asset_id,
347             is_collapsed, is_auto_generated, created_at, modified_at)
348             VALUES (?1,?2,?3,?4,?5,?6,?7,?8)",
349            params![
350                row.id,
351                row.stack_type,
352                row.primary_asset_id,
353                row.cover_asset_id,
354                row.is_collapsed as i64,
355                row.is_auto_generated as i64,
356                row.created_at,
357                row.modified_at,
358            ],
359        )?;
360        Ok(())
361    }
362
363    pub fn insert_stack_member(&self, row: &StackMemberRow) -> Result<(), rusqlite::Error> {
364        self.conn.execute(
365            "INSERT INTO stack_members (id, stack_id, asset_id, sequence_order, member_role, created_at)
366             VALUES (?1,?2,?3,?4,?5,?6)",
367            params![row.id, row.stack_id, row.asset_id, row.sequence_order, row.member_role, row.created_at],
368        )?;
369        Ok(())
370    }
371
372    pub fn update_stack_hidden(&self, uuid: &str, hidden: bool) -> Result<(), rusqlite::Error> {
373        self.conn.execute(
374            "UPDATE assets SET is_stack_hidden = ?1 WHERE uuid = ?2",
375            params![hidden as i64, uuid],
376        )?;
377        Ok(())
378    }
379
380    pub fn update_stack_primary(
381        &self,
382        stack_id: &str,
383        primary_uuid: &str,
384    ) -> Result<(), rusqlite::Error> {
385        self.conn.execute(
386            "UPDATE asset_stacks SET primary_asset_id = ?1, modified_at = ?2 WHERE id = ?3",
387            params![primary_uuid, now_secs(), stack_id],
388        )?;
389        Ok(())
390    }
391
392    pub fn find_stack_by_detection(
393        &self,
394        key: &str,
395        method: &str,
396    ) -> Result<Option<AssetStackRow>, rusqlite::Error> {
397        // Find a stack via a stack_member that has a matching detection key+method
398        // Since detection key/method is stored in the sidecar, not in the DB,
399        // we use a separate lookup table approach. For now, store detection key in
400        // stack_members table isn't in the spec. Instead, we'll need to track this
401        // in-memory during the import batch.
402        //
403        // The spec says: "Check if an asset_stacks row exists for this (detection_key, detection_method) pair
404        // by looking up stack_members for the existing candidates in this batch."
405        // This means the in-memory ImportCandidate tracks the key; DB lookup is by stack_id of existing members.
406        // We expose this as a no-op for now - the executor tracks stack membership in-memory during the batch.
407        let _ = (key, method);
408        Ok(None)
409    }
410
411    pub fn list_stack_members(
412        &self,
413        stack_id: &str,
414    ) -> Result<Vec<StackMemberRow>, rusqlite::Error> {
415        let mut stmt = self.conn.prepare(
416            "SELECT id, stack_id, asset_id, sequence_order, member_role, created_at
417             FROM stack_members WHERE stack_id = ?1 ORDER BY sequence_order ASC",
418        )?;
419        let rows = stmt.query_map(params![stack_id], |row| {
420            Ok(StackMemberRow {
421                id: row.get(0)?,
422                stack_id: row.get(1)?,
423                asset_id: row.get(2)?,
424                sequence_order: row.get(3)?,
425                member_role: row.get(4)?,
426                created_at: row.get(5)?,
427            })
428        })?;
429        rows.collect()
430    }
431
432    pub fn soft_delete(&self, uuid: &str, deleted_at: i64) -> Result<(), rusqlite::Error> {
433        self.conn.execute(
434            "UPDATE assets SET is_deleted = 1, deleted_at = ?1 WHERE uuid = ?2",
435            params![deleted_at, uuid],
436        )?;
437        Ok(())
438    }
439
440    pub fn restore_asset(&self, uuid: &str) -> Result<(), rusqlite::Error> {
441        self.conn.execute(
442            "UPDATE assets SET is_deleted = 0, deleted_at = NULL WHERE uuid = ?1",
443            params![uuid],
444        )?;
445        Ok(())
446    }
447
448    /// All currently soft-deleted assets — the Recently Deleted listing,
449    /// most-recently-deleted first.
450    pub fn query_trash(
451        &self,
452        offset: usize,
453        limit: usize,
454    ) -> Result<Vec<AssetRow>, rusqlite::Error> {
455        let mut stmt = self.conn.prepare(
456            "SELECT uuid, asset_type, capture_timestamp, capture_utc, capture_tz_source,
457             import_timestamp, hash_sha256, width, height, duration_ms, stack_id, is_stack_hidden,
458             chromahash, dominant_color, album_id, rating, is_deleted, deleted_at, is_hidden,
459             caption, latitude, longitude
460             FROM assets WHERE is_deleted = 1
461             ORDER BY deleted_at DESC
462             LIMIT ?1 OFFSET ?2",
463        )?;
464        let rows = stmt.query_map(params![limit as i64, offset as i64], map_asset_row)?;
465        rows.collect()
466    }
467
468    /// All user-hidden, non-deleted assets — the **Hidden** listing, newest first.
469    ///
470    /// Hidden assets are excluded from every default projection (timeline, album), so this
471    /// is the only view that surfaces them; it is reached exclusively through
472    /// [`GateKeeper::query_hidden`](crate::library::GateKeeper::query_hidden), which holds
473    /// it behind the same fresh-local-auth gate as Recently Deleted (SSoT:
474    /// design/organization § Hidden Assets, design/local-gallery SR1).
475    ///
476    /// Soft-deleted assets are excluded even when hidden: a trashed asset belongs to
477    /// Recently Deleted, so the two gated views never show the same row.
478    pub fn query_hidden(
479        &self,
480        offset: usize,
481        limit: usize,
482    ) -> Result<Vec<AssetRow>, rusqlite::Error> {
483        let mut stmt = self.conn.prepare(
484            "SELECT uuid, asset_type, capture_timestamp, capture_utc, capture_tz_source,
485             import_timestamp, hash_sha256, width, height, duration_ms, stack_id, is_stack_hidden,
486             chromahash, dominant_color, album_id, rating, is_deleted, deleted_at, is_hidden,
487             caption, latitude, longitude
488             FROM assets WHERE is_hidden = 1 AND is_deleted = 0
489             ORDER BY COALESCE(capture_utc, capture_timestamp) DESC
490             LIMIT ?1 OFFSET ?2",
491        )?;
492        let rows = stmt.query_map(params![limit as i64, offset as i64], map_asset_row)?;
493        rows.collect()
494    }
495
496    /// Set the index projection of an asset's sidecar `hidden` register. Hiding is
497    /// view-layer only — the asset keeps its album, its stack, and its sync state.
498    pub fn update_asset_hidden(&self, uuid: &str, hidden: bool) -> Result<(), rusqlite::Error> {
499        self.conn.execute(
500            "UPDATE assets SET is_hidden = ?1 WHERE uuid = ?2",
501            params![hidden as i64, uuid],
502        )?;
503        Ok(())
504    }
505
506    /// Set (or, with `None` or an empty string, clear) the index projection of an asset's
507    /// sidecar `caption` register. Returns whether a row was updated: `false` means no asset
508    /// has `uuid`, and nothing was written.
509    pub fn update_asset_caption(
510        &self,
511        uuid: &str,
512        caption: Option<&str>,
513    ) -> Result<bool, rusqlite::Error> {
514        let changed = self.conn.execute(
515            "UPDATE assets SET caption = ?1 WHERE uuid = ?2",
516            params![stored_caption(caption), uuid],
517        )?;
518        Ok(changed > 0)
519    }
520
521    /// Permanently remove an asset's rows — its `assets` row, its indexed tags, its upload
522    /// source guard, its cached representations and its stack memberships — in one transaction, so no index row names
523    /// it afterwards. A stack whose primary or cover it was passes that role to its first
524    /// remaining member (by sequence, then id), and a stack it leaves empty is removed. An
525    /// album cover naming it is cleared. The on-disk files are the caller's concern
526    /// (`Workspace::purge` removes them first).
527    ///
528    /// Runs as one [`with_transaction`](Self::with_transaction) scope, so it also nests inside
529    /// an enclosing batch.
530    pub fn purge_asset(&self, uuid: &str) -> Result<(), rusqlite::Error> {
531        self.with_transaction(|| self.purge_asset_rows(uuid))?;
532        tracing::debug!(asset_id = %uuid, "catalog: asset purged from the index");
533        Ok(())
534    }
535
536    fn purge_asset_rows(&self, uuid: &str) -> Result<(), rusqlite::Error> {
537        let conn = &self.conn;
538        conn.execute("DELETE FROM asset_tags WHERE uuid = ?1", params![uuid])?;
539        // A purged asset's bundle is abandoned: its source guard goes with it.
540        conn.execute(
541            "DELETE FROM upload_guards WHERE asset_id = ?1",
542            params![uuid],
543        )?;
544        conn.execute(
545            "DELETE FROM cached_representations WHERE uuid = ?1",
546            params![uuid],
547        )?;
548        conn.execute(
549            "DELETE FROM stack_members WHERE asset_id = ?1",
550            params![uuid],
551        )?;
552        // The successor is the first remaining member; a stack with none keeps the purged id
553        // only until the `DELETE` below removes it.
554        let successor = "(SELECT m.asset_id FROM stack_members m WHERE m.stack_id = asset_stacks.id
555                          ORDER BY m.sequence_order, m.asset_id LIMIT 1)";
556        conn.execute(
557            &format!(
558                "UPDATE asset_stacks SET primary_asset_id = COALESCE({successor}, primary_asset_id)
559                 WHERE primary_asset_id = ?1"
560            ),
561            params![uuid],
562        )?;
563        conn.execute(
564            &format!(
565                "UPDATE asset_stacks SET cover_asset_id = {successor} WHERE cover_asset_id = ?1"
566            ),
567            params![uuid],
568        )?;
569        conn.execute(
570            "DELETE FROM asset_stacks
571             WHERE primary_asset_id = ?1
572               AND NOT EXISTS (SELECT 1 FROM stack_members m WHERE m.stack_id = asset_stacks.id)",
573            params![uuid],
574        )?;
575        conn.execute(
576            "UPDATE albums SET cover_asset_id = NULL WHERE cover_asset_id = ?1",
577            params![uuid],
578        )?;
579        conn.execute("DELETE FROM assets WHERE uuid = ?1", params![uuid])?;
580        Ok(())
581    }
582
583    // ── Albums ───────────────────────────────────────────────────────────────
584
585    pub fn insert_album(&self, row: &AlbumRow) -> Result<(), rusqlite::Error> {
586        self.conn.execute(
587            "INSERT INTO albums (id, name, created_at, modified_at, cover_asset_id)
588             VALUES (?1,?2,?3,?4,?5)",
589            params![
590                row.id,
591                row.name,
592                row.created_at,
593                row.modified_at,
594                row.cover_asset_id,
595            ],
596        )?;
597        Ok(())
598    }
599
600    pub fn update_album(&self, row: &AlbumRow) -> Result<(), rusqlite::Error> {
601        self.conn.execute(
602            "UPDATE albums SET name = ?2, modified_at = ?3, cover_asset_id = ?4 WHERE id = ?1",
603            params![row.id, row.name, row.modified_at, row.cover_asset_id],
604        )?;
605        Ok(())
606    }
607
608    pub fn delete_album(&self, id: &str) -> Result<(), rusqlite::Error> {
609        // Detach member assets first — deleting an album never deletes assets.
610        self.conn.execute(
611            "UPDATE assets SET album_id = NULL WHERE album_id = ?1",
612            params![id],
613        )?;
614        self.conn
615            .execute("DELETE FROM albums WHERE id = ?1", params![id])?;
616        Ok(())
617    }
618
619    pub fn find_album(&self, id: &str) -> Result<Option<AlbumRow>, rusqlite::Error> {
620        let mut stmt = self.conn.prepare(
621            "SELECT id, name, created_at, modified_at, cover_asset_id
622             FROM albums WHERE id = ?1 LIMIT 1",
623        )?;
624        let mut rows = stmt.query_map(params![id], map_album_row)?;
625        match rows.next() {
626            Some(r) => Ok(Some(r?)),
627            None => Ok(None),
628        }
629    }
630
631    /// Every album row, in the album order ([`AlbumRecency`]): most recent visible asset first,
632    /// an empty album by its id's creation time, ties by ascending id. The row's local
633    /// `created_at` is not consulted: it differs per device and across a rebuild.
634    #[tracing::instrument(level = "debug", skip_all)]
635    pub fn list_albums(&self) -> Result<Vec<AlbumRow>, rusqlite::Error> {
636        let mut stmt = self.conn.prepare(
637            "SELECT id, name, created_at, modified_at, cover_asset_id
638             FROM albums",
639        )?;
640        let mut rows = stmt
641            .query_map([], map_album_row)?
642            .collect::<Result<Vec<_>, _>>()?;
643        self.album_recency()?.sort(&mut rows, |row| row.id.clone());
644        tracing::debug!(albums = rows.len(), "albums listed in recency order");
645        Ok(rows)
646    }
647
648    /// The album order's input, read from the index: the latest effective capture among each
649    /// album's assets that are neither hidden nor trashed. Served by
650    /// `idx_assets_album_recency`; nothing is stored, so every write to an asset's album,
651    /// capture time, hidden or trashed state moves it with no extra bookkeeping.
652    #[tracing::instrument(level = "debug", skip_all)]
653    pub fn album_recency(&self) -> Result<AlbumRecency, rusqlite::Error> {
654        let mut stmt = self.conn.prepare(ALBUM_RECENCY_SQL)?;
655        let latest = stmt
656            .query_map([], |row| {
657                Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
658            })?
659            .collect::<Result<HashMap<_, _>, _>>()?;
660        tracing::trace!(albums = latest.len(), "album recency read from the index");
661        Ok(AlbumRecency::from_latest_captures(latest))
662    }
663
664    /// Set (or clear, with `None`) the album an asset belongs to.
665    pub fn set_asset_album(
666        &self,
667        uuid: &str,
668        album_id: Option<&str>,
669    ) -> Result<(), rusqlite::Error> {
670        self.conn.execute(
671            "UPDATE assets SET album_id = ?1 WHERE uuid = ?2",
672            params![album_id, uuid],
673        )?;
674        Ok(())
675    }
676
677    /// Query the non-deleted, non-hidden assets in an album, newest first.
678    pub fn query_album_assets(
679        &self,
680        album_id: &str,
681        offset: usize,
682        limit: usize,
683    ) -> Result<Vec<AssetRow>, rusqlite::Error> {
684        let mut stmt = self.conn.prepare(
685            "SELECT uuid, asset_type, capture_timestamp, capture_utc, capture_tz_source,
686             import_timestamp, hash_sha256, width, height, duration_ms, stack_id, is_stack_hidden,
687             chromahash, dominant_color, album_id, rating, is_deleted, deleted_at, is_hidden,
688             caption, latitude, longitude
689             FROM assets
690             WHERE is_deleted = 0 AND is_stack_hidden = 0 AND is_hidden = 0
691               AND album_id = ?1
692             ORDER BY COALESCE(capture_utc, capture_timestamp) DESC
693             LIMIT ?2 OFFSET ?3",
694        )?;
695        let rows = stmt.query_map(
696            params![album_id, limit as i64, offset as i64],
697            map_asset_row,
698        )?;
699        rows.collect()
700    }
701
702    // ── Cached representations (adaptive cache eviction, issue #23) ──────────────
703
704    /// Insert or replace a cached representation row.
705    pub fn upsert_representation(
706        &self,
707        row: &CachedRepresentationRow,
708    ) -> Result<(), rusqlite::Error> {
709        self.conn.execute(
710            "INSERT OR REPLACE INTO cached_representations
711             (uuid, tier, format, bytes, path, last_accessed_at, pinned, is_owned_original)
712             VALUES (?1,?2,?3,?4,?5,?6,?7,?8)",
713            params![
714                row.uuid,
715                row.tier,
716                row.format,
717                row.bytes,
718                row.path,
719                row.last_accessed_at,
720                row.pinned as i64,
721                row.is_owned_original as i64,
722            ],
723        )?;
724        Ok(())
725    }
726
727    /// Remove a cached representation row (after its file has been deleted).
728    pub fn remove_representation(&self, uuid: &str, tier: &str) -> Result<(), rusqlite::Error> {
729        self.conn.execute(
730            "DELETE FROM cached_representations WHERE uuid = ?1 AND tier = ?2",
731            params![uuid, tier],
732        )?;
733        Ok(())
734    }
735
736    /// Stamp a representation's last-access time (recency promotion) — viewing an asset keeps its
737    /// representations from eviction. `now` is injected so the policy stays deterministic.
738    pub fn record_access(&self, uuid: &str, tier: &str, now: i64) -> Result<(), rusqlite::Error> {
739        self.conn.execute(
740            "UPDATE cached_representations SET last_accessed_at = ?1 WHERE uuid = ?2 AND tier = ?3",
741            params![now, uuid, tier],
742        )?;
743        Ok(())
744    }
745
746    /// The reclaimable representations to evict so the reclaimable set fits within `budget_bytes`.
747    /// Pinned and device-owned originals are never candidates. Rows are ranked most-valuable-to-
748    /// keep first (most-recently-accessed; thumbnail over preview over original at equal recency),
749    /// then everything past the budget is evicted — i.e. least-recently-accessed first, original →
750    /// preview → thumbnail at equal recency.
751    pub fn eviction_candidates(
752        &self,
753        budget_bytes: i64,
754    ) -> Result<Vec<CachedRepresentationRow>, rusqlite::Error> {
755        let mut stmt = self.conn.prepare(
756            "SELECT uuid, tier, format, bytes, path, last_accessed_at, pinned, is_owned_original
757             FROM cached_representations
758             WHERE pinned = 0 AND is_owned_original = 0
759             ORDER BY last_accessed_at DESC,
760                      CASE tier WHEN 'thumbnail' THEN 2 WHEN 'preview' THEN 1 WHEN 'original' THEN 0 ELSE -1 END DESC",
761        )?;
762        let keep_first = stmt.query_map([], map_cached_representation_row)?;
763
764        let mut kept_bytes: i64 = 0;
765        let mut evict = Vec::new();
766        for row in keep_first {
767            let row = row?;
768            kept_bytes += row.bytes;
769            if kept_bytes > budget_bytes {
770                evict.push(row);
771            }
772        }
773        Ok(evict)
774    }
775
776    /// All cached representations recorded for `uuid` (any tier).
777    pub fn representations_for(
778        &self,
779        uuid: &str,
780    ) -> Result<Vec<CachedRepresentationRow>, rusqlite::Error> {
781        let mut stmt = self.conn.prepare(
782            "SELECT uuid, tier, format, bytes, path, last_accessed_at, pinned, is_owned_original
783             FROM cached_representations WHERE uuid = ?1 ORDER BY tier",
784        )?;
785        let rows = stmt.query_map(params![uuid], map_cached_representation_row)?;
786        rows.collect()
787    }
788
789    // ── User tags (asset_tags index) ────────────────────────────────────────────
790
791    /// Replace the indexed user tags for `uuid` with `tags` (the asset's current OR-set value).
792    ///
793    /// Atomic: the delete and every insert run in one
794    /// [`with_transaction`](Self::with_transaction) scope, so a failure part-way leaves the
795    /// previous tag set intact rather than a truncated one.
796    pub fn replace_asset_tags(&self, uuid: &str, tags: &[String]) -> Result<(), rusqlite::Error> {
797        self.with_transaction(|| {
798            self.conn
799                .execute("DELETE FROM asset_tags WHERE uuid = ?1", params![uuid])?;
800            let mut insert = self
801                .conn
802                .prepare_cached("INSERT OR IGNORE INTO asset_tags (uuid, tag) VALUES (?1, ?2)")?;
803            for tag in tags {
804                insert.execute(params![uuid, tag])?;
805            }
806            Ok::<_, rusqlite::Error>(())
807        })?;
808        tracing::trace!(asset_id = %uuid, tags = tags.len(), "catalog: asset tags replaced");
809        Ok(())
810    }
811
812    /// Every asset id the `assets` table holds — the cheap side of the open-time reconcile's
813    /// set comparison (one key-only scan, no row decoding).
814    pub fn asset_ids(&self) -> Result<HashSet<String>, rusqlite::Error> {
815        let mut stmt = self.conn.prepare("SELECT uuid FROM assets")?;
816        let rows = stmt.query_map([], |r| r.get::<_, String>(0))?;
817        rows.collect()
818    }
819
820    /// The indexed user tags for `uuid`, sorted.
821    pub fn tags_for(&self, uuid: &str) -> Result<Vec<String>, rusqlite::Error> {
822        let mut stmt = self
823            .conn
824            .prepare("SELECT tag FROM asset_tags WHERE uuid = ?1 ORDER BY tag")?;
825        let rows = stmt.query_map(params![uuid], |r| r.get::<_, String>(0))?;
826        rows.collect()
827    }
828}
829
830/// The album order's index read: the latest effective capture per album over its assets that
831/// are neither hidden nor trashed. `INDEXED BY` makes a missing or unusable
832/// `idx_assets_album_recency` an error rather than a silent table scan.
833const ALBUM_RECENCY_SQL: &str = "SELECT album_id, MAX(COALESCE(capture_utc, capture_timestamp))
834     FROM assets INDEXED BY idx_assets_album_recency
835     WHERE album_id IS NOT NULL AND is_deleted = 0 AND is_hidden = 0
836     GROUP BY album_id";
837
838fn now_secs() -> i64 {
839    std::time::SystemTime::now()
840        .duration_since(std::time::UNIX_EPOCH)
841        .expect("system clock is before the UNIX epoch")
842        .as_secs() as i64
843}
844
845fn map_asset_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<AssetRow> {
846    Ok(AssetRow {
847        uuid: row.get(0)?,
848        asset_type: row.get(1)?,
849        capture_timestamp: row.get(2)?,
850        capture_utc: row.get(3)?,
851        capture_tz_source: row.get(4)?,
852        import_timestamp: row.get(5)?,
853        hash_sha256: row.get(6)?,
854        width: row.get(7)?,
855        height: row.get(8)?,
856        duration_ms: row.get(9)?,
857        stack_id: row.get(10)?,
858        is_stack_hidden: row.get::<_, i64>(11)? != 0,
859        chromahash: row.get(12)?,
860        dominant_color: row.get(13)?,
861        album_id: row.get(14)?,
862        rating: row.get(15)?,
863        is_deleted: row.get::<_, i64>(16)? != 0,
864        deleted_at: row.get(17)?,
865        is_hidden: row.get::<_, i64>(18)? != 0,
866        caption: row.get(19)?,
867        latitude: row.get(20)?,
868        longitude: row.get(21)?,
869    })
870}
871
872/// The stored form of a caption: an empty caption is no caption, so it is written as `NULL`
873/// rather than as a second spelling of "none" a reader would have to know about.
874fn stored_caption(caption: Option<&str>) -> Option<&str> {
875    caption.filter(|c| !c.is_empty())
876}
877
878fn map_album_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<AlbumRow> {
879    Ok(AlbumRow {
880        id: row.get(0)?,
881        name: row.get(1)?,
882        created_at: row.get(2)?,
883        modified_at: row.get(3)?,
884        cover_asset_id: row.get(4)?,
885    })
886}
887
888fn map_cached_representation_row(
889    row: &rusqlite::Row<'_>,
890) -> rusqlite::Result<CachedRepresentationRow> {
891    Ok(CachedRepresentationRow {
892        uuid: row.get(0)?,
893        tier: row.get(1)?,
894        format: row.get(2)?,
895        bytes: row.get(3)?,
896        path: row.get(4)?,
897        last_accessed_at: row.get(5)?,
898        pinned: row.get::<_, i64>(6)? != 0,
899        is_owned_original: row.get::<_, i64>(7)? != 0,
900    })
901}
902
903#[cfg(test)]
904mod tests;