videre-core 0.22.1

Shared SQLite, caching, and search helpers for the videre media library CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! Per-photo marks: rating, pick, colour label, like. One row per photo, keyed
//! by content hash so a mark follows a photo across duplicates and moves.
//!
//! This module is the single implementation of set/get/query, and the only
//! writer of the `marks` table. The `videre mark` command and the gallery API
//! both call it; nothing else writes marks. Its predicates flow through
//! `videre_core::selection` so `search`, `gallery` and MCP get them for free.

use anyhow::Result;
use rusqlite::Connection;
use std::collections::{HashMap, HashSet};

/// A photo's four marks. Absent means unset.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Marks {
    /// Star rating 1..=5, or None when unrated.
    pub rating: Option<i64>,
    /// The culling decision, or None when undecided.
    pub pick: Option<Pick>,
    /// Colour label string, or None.
    pub label: Option<String>,
    /// Whether the photo is liked (a favourite).
    pub liked: bool,
}

/// The culling decision. Keep and Reject are the two set states; "undecided" is
/// `Option::None` at the field, so there is no third variant here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pick {
    Keep,
    Reject,
}

impl Pick {
    pub fn as_bool(self) -> i64 {
        match self {
            Pick::Keep => 1,
            Pick::Reject => 0,
        }
    }
    pub fn from_bool(v: i64) -> Pick {
        if v == 0 {
            Pick::Reject
        } else {
            Pick::Keep
        }
    }
}

/// One field of a partial update. `Set` writes a value, `Clear` removes it.
#[derive(Debug, Clone)]
pub enum Field<T> {
    Set(T),
    Clear,
}

/// A partial update. A field that is `None` is left untouched; `Some(Set)`
/// writes it; `Some(Clear)` removes it. This is what lets
/// `videre mark --rating 5` change only the rating.
#[derive(Debug, Clone, Default)]
pub struct MarkChange {
    pub rating: Option<Field<i64>>,
    pub pick: Option<Field<Pick>>,
    pub label: Option<Field<String>>,
    pub liked: Option<bool>,
}

impl MarkChange {
    /// True if this change would touch at least one field. `videre mark` refuses
    /// a no-op invocation on the strength of this.
    pub fn any(&self) -> bool {
        self.rating.is_some() || self.pick.is_some() || self.label.is_some() || self.liked.is_some()
    }
}

/// Build a `MarkChange` from the loosely-typed request shapes the CLI flags and
/// the gallery's JSON body share: `rating` where 0 clears, `pick`/`label` where
/// `"none"` clears, `liked` set directly. The one place these string forms map
/// to the typed change, so the two callers cannot drift.
pub fn change_from_parts(
    rating: Option<i64>,
    pick: Option<&str>,
    label: Option<&str>,
    liked: Option<bool>,
) -> MarkChange {
    MarkChange {
        rating: rating.map(|r| if r == 0 { Field::Clear } else { Field::Set(r) }),
        pick: pick.map(|p| match p {
            "keep" => Field::Set(Pick::Keep),
            "reject" => Field::Set(Pick::Reject),
            _ => Field::Clear, // "none"
        }),
        label: label.map(|l| {
            if l == "none" {
                Field::Clear
            } else {
                Field::Set(l.to_string())
            }
        }),
        liked,
    }
}

/// Create the marks table if absent. Idempotent, safe on every open, called
/// from `db::open_wal` the same way the `faces`/`people` tables are ensured.
pub fn ensure_marks_table(conn: &Connection) -> Result<()> {
    conn.execute_batch(
        "CREATE TABLE IF NOT EXISTS marks (
            hash         TEXT PRIMARY KEY,
            rating       INTEGER,
            pick         INTEGER,
            label        TEXT,
            liked        INTEGER NOT NULL DEFAULT 0,
            updated_at   TEXT NOT NULL
        );",
    )?;
    Ok(())
}

/// Read one photo's marks. An unmarked photo is `Marks::default()`.
pub fn get(conn: &Connection, hash: &str) -> Result<Marks> {
    let row = conn
        .query_row(
            "SELECT rating, pick, label, liked FROM marks WHERE hash = ?1",
            [hash],
            |r| {
                Ok(Marks {
                    rating: r.get::<_, Option<i64>>(0)?,
                    pick: r.get::<_, Option<i64>>(1)?.map(Pick::from_bool),
                    label: r.get::<_, Option<String>>(2)?,
                    liked: r.get::<_, i64>(3)? != 0,
                })
            },
        )
        .ok();
    Ok(row.unwrap_or_default())
}

/// Counts of each kind of mark across the library, for `videre stats`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize)]
pub struct MarksSummary {
    pub rated: i64,
    pub picked: i64,
    pub labelled: i64,
    pub liked: i64,
}

/// Summarise the marks table. All zeroes when the table is absent, so a caller
/// that predates marks still gets a valid struct. Returns `rusqlite::Result` to
/// compose with `library_stats::compute`.
pub fn summary(conn: &Connection) -> rusqlite::Result<MarksSummary> {
    if !crate::db::table_exists(conn, "marks")? {
        return Ok(MarksSummary::default());
    }
    Ok(conn.query_row(
        "SELECT COUNT(rating), COUNT(pick), COUNT(label), COALESCE(SUM(liked), 0) FROM marks",
        [],
        |r| {
            Ok(MarksSummary {
                rated: r.get(0)?,
                picked: r.get(1)?,
                labelled: r.get(2)?,
                liked: r.get(3)?,
            })
        },
    )?)
}

/// Read marks for many hashes at once, for the gallery's file list. Only marked
/// hashes appear in the map; an absent key means the photo is unmarked.
pub fn get_many(conn: &Connection, hashes: &[String]) -> Result<HashMap<String, Marks>> {
    let mut out = HashMap::new();
    for h in hashes {
        let m = get(conn, h)?;
        if m != Marks::default() {
            out.insert(h.clone(), m);
        }
    }
    Ok(out)
}

/// Apply `change` to every hash. Fields not named are untouched; a `Clear`
/// removes just that field; a row left with no marks is deleted so `marks`
/// never fills with empty rows. Runs in one transaction. `hashes` is a user
/// selection, not the whole library, so the row count is bounded.
pub fn set(conn: &Connection, hashes: &[String], change: &MarkChange) -> Result<()> {
    let tx = conn.unchecked_transaction()?;
    for h in hashes {
        let mut m = get(&tx, h)?;
        if let Some(f) = &change.rating {
            m.rating = match f {
                Field::Set(v) => Some((*v).clamp(0, 5)),
                Field::Clear => None,
            };
            if m.rating == Some(0) {
                m.rating = None; // 0 means unrated
            }
        }
        if let Some(f) = &change.pick {
            m.pick = match f {
                Field::Set(p) => Some(*p),
                Field::Clear => None,
            };
        }
        if let Some(f) = &change.label {
            m.label = match f {
                Field::Set(s) => Some(s.clone()),
                Field::Clear => None,
            };
        }
        if let Some(v) = change.liked {
            m.liked = v;
        }

        let empty = m.rating.is_none() && m.pick.is_none() && m.label.is_none() && !m.liked;
        if empty {
            tx.execute("DELETE FROM marks WHERE hash = ?1", [h])?;
        } else {
            tx.execute(
                "INSERT INTO marks (hash, rating, pick, label, liked, updated_at)
                 VALUES (?1, ?2, ?3, ?4, ?5, datetime('now'))
                 ON CONFLICT(hash) DO UPDATE SET
                   rating = ?2, pick = ?3, label = ?4, liked = ?5, updated_at = datetime('now')",
                rusqlite::params![
                    h,
                    m.rating,
                    m.pick.map(Pick::as_bool),
                    m.label,
                    m.liked as i64,
                ],
            )?;
        }
    }
    tx.commit()?;
    Ok(())
}

// --- predicates, consumed through `RowSelection` -------------------------------

/// Hashes with rating >= `min` (the "4+ stars" semantics).
pub fn by_rating(conn: &Connection, min: i64) -> Result<HashSet<String>> {
    hashes(conn, "SELECT hash FROM marks WHERE rating >= ?1", [min])
}
/// Hashes with exactly this pick state.
pub fn by_pick(conn: &Connection, pick: Pick) -> Result<HashSet<String>> {
    hashes(
        conn,
        "SELECT hash FROM marks WHERE pick = ?1",
        [pick.as_bool()],
    )
}
/// Hashes with exactly this colour label.
pub fn by_label(conn: &Connection, label: &str) -> Result<HashSet<String>> {
    hashes(conn, "SELECT hash FROM marks WHERE label = ?1", [label])
}
/// Hashes that are liked.
pub fn by_liked(conn: &Connection) -> Result<HashSet<String>> {
    hashes(conn, "SELECT hash FROM marks WHERE liked = 1", [])
}

fn hashes<P: rusqlite::Params>(conn: &Connection, sql: &str, p: P) -> Result<HashSet<String>> {
    let mut stmt = conn.prepare(sql)?;
    let rows = stmt.query_map(p, |r| r.get::<_, String>(0))?;
    Ok(rows.collect::<rusqlite::Result<HashSet<String>>>()?)
}

// --- XMP import ---------------------------------------------------------------

/// How a mark read from a file's XMP is reconciled with a mark already in the
/// db, chosen by `--xmp` on scan/watch/import.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum XmpPrecedence {
    /// The db wins; XMP only fills marks the db does not already have.
    #[default]
    Db,
    /// The file wins; XMP replaces the db mark.
    File,
    /// The more recently changed wins. Reserved (DEBT:27); callers treat it as
    /// `Db` with a warning until the timestamp signal is trustworthy.
    Newest,
}

impl XmpPrecedence {
    pub fn parse(s: &str) -> Result<Self> {
        match s {
            "db" => Ok(Self::Db),
            "file" => Ok(Self::File),
            "newest" => Ok(Self::Newest),
            other => anyhow::bail!("unknown --xmp value {other:?}; expected db, file, or newest"),
        }
    }
}

/// Given the marks already in the db and the rating/label read from XMP, produce
/// the change to apply under `prec`, or None to leave the db untouched. Only
/// rating and label are portable; pick and like have no XMP standard.
pub fn import_change(
    existing: &Marks,
    xmp_rating: Option<i64>,
    xmp_label: Option<String>,
    prec: XmpPrecedence,
) -> Option<MarkChange> {
    // `Newest` is treated as `Db` here; the caller warns once. See DEBT:27.
    let file_wins = matches!(prec, XmpPrecedence::File);
    let want = |db_has: bool| file_wins || !db_has;

    let mut c = MarkChange::default();
    if let Some(r) = xmp_rating {
        if want(existing.rating.is_some()) {
            c.rating = Some(Field::Set(r));
        }
    }
    if let Some(l) = xmp_label {
        if want(existing.label.is_some()) {
            c.label = Some(Field::Set(l));
        }
    }
    if c.any() {
        Some(c)
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn mem() -> Connection {
        let c = Connection::open_in_memory().unwrap();
        c.execute_batch("CREATE TABLE file_hashes (path TEXT PRIMARY KEY, hash TEXT NOT NULL);")
            .unwrap();
        ensure_marks_table(&c).unwrap();
        c
    }

    #[test]
    fn empty_change_touches_nothing() {
        assert!(!MarkChange::default().any());
    }

    #[test]
    fn change_from_parts_maps_the_request_shapes() {
        // rating 0 clears, "none" clears pick/label, liked passes through.
        let c = change_from_parts(Some(0), Some("none"), Some("none"), Some(false));
        assert!(matches!(c.rating, Some(Field::Clear)));
        assert!(matches!(c.pick, Some(Field::Clear)));
        assert!(matches!(c.label, Some(Field::Clear)));
        assert_eq!(c.liked, Some(false));
        let c = change_from_parts(Some(4), Some("reject"), Some("Red"), None);
        assert!(matches!(c.rating, Some(Field::Set(4))));
        assert!(matches!(c.pick, Some(Field::Set(Pick::Reject))));
        assert!(matches!(c.label, Some(Field::Set(ref s)) if s == "Red"));
        assert_eq!(c.liked, None);
        // an absent field stays untouched
        assert!(change_from_parts(None, None, None, None).rating.is_none());
    }

    #[test]
    fn get_many_returns_only_marked_hashes() {
        let c = mem();
        set(
            &c,
            &["a".into()],
            &change_from_parts(Some(5), None, None, None),
        )
        .unwrap();
        let map = get_many(&c, &["a".into(), "b".into()]).unwrap();
        assert_eq!(map.get("a").and_then(|m| m.rating), Some(5));
        assert!(!map.contains_key("b"), "unmarked hash must be absent");
    }

    #[test]
    fn a_rating_change_is_a_change() {
        let c = MarkChange {
            rating: Some(Field::Set(4)),
            ..Default::default()
        };
        assert!(c.any());
    }

    #[test]
    fn ensure_marks_table_is_idempotent() {
        let c = mem();
        ensure_marks_table(&c).unwrap();
        let n: i64 = c
            .query_row("SELECT COUNT(*) FROM marks", [], |r| r.get(0))
            .unwrap();
        assert_eq!(n, 0);
    }

    #[test]
    fn set_then_get_roundtrips_each_field() {
        let c = mem();
        set(
            &c,
            &["abc".into()],
            &MarkChange {
                rating: Some(Field::Set(4)),
                pick: Some(Field::Set(Pick::Keep)),
                label: Some(Field::Set("red".into())),
                liked: Some(true),
            },
        )
        .unwrap();
        assert_eq!(
            get(&c, "abc").unwrap(),
            Marks {
                rating: Some(4),
                pick: Some(Pick::Keep),
                label: Some("red".into()),
                liked: true
            }
        );
    }

    #[test]
    fn clearing_only_touches_named_fields() {
        let c = mem();
        set(
            &c,
            &["abc".into()],
            &MarkChange {
                rating: Some(Field::Set(5)),
                liked: Some(true),
                ..Default::default()
            },
        )
        .unwrap();
        set(
            &c,
            &["abc".into()],
            &MarkChange {
                rating: Some(Field::Clear),
                ..Default::default()
            },
        )
        .unwrap();
        let m = get(&c, "abc").unwrap();
        assert_eq!(m.rating, None);
        assert!(m.liked);
    }

    #[test]
    fn a_row_with_no_marks_left_is_deleted() {
        let c = mem();
        set(
            &c,
            &["abc".into()],
            &MarkChange {
                rating: Some(Field::Set(3)),
                ..Default::default()
            },
        )
        .unwrap();
        set(
            &c,
            &["abc".into()],
            &MarkChange {
                rating: Some(Field::Clear),
                ..Default::default()
            },
        )
        .unwrap();
        let n: i64 = c
            .query_row("SELECT COUNT(*) FROM marks WHERE hash='abc'", [], |r| {
                r.get(0)
            })
            .unwrap();
        assert_eq!(n, 0, "an all-clear row must be removed");
    }

    #[test]
    fn get_of_unmarked_is_default() {
        let c = mem();
        assert_eq!(get(&c, "nope").unwrap(), Marks::default());
    }

    #[test]
    fn by_rating_is_at_least() {
        let c = mem();
        set(
            &c,
            &["a".into()],
            &MarkChange {
                rating: Some(Field::Set(5)),
                ..Default::default()
            },
        )
        .unwrap();
        set(
            &c,
            &["b".into()],
            &MarkChange {
                rating: Some(Field::Set(3)),
                ..Default::default()
            },
        )
        .unwrap();
        let hit = by_rating(&c, 4).unwrap();
        assert!(
            hit.contains("a") && !hit.contains("b"),
            "--rating 4 means >= 4"
        );
    }

    #[test]
    fn by_pick_and_liked_are_exact() {
        let c = mem();
        set(
            &c,
            &["k".into()],
            &MarkChange {
                pick: Some(Field::Set(Pick::Keep)),
                ..Default::default()
            },
        )
        .unwrap();
        set(
            &c,
            &["r".into()],
            &MarkChange {
                pick: Some(Field::Set(Pick::Reject)),
                ..Default::default()
            },
        )
        .unwrap();
        set(
            &c,
            &["l".into()],
            &MarkChange {
                liked: Some(true),
                ..Default::default()
            },
        )
        .unwrap();
        assert_eq!(
            by_pick(&c, Pick::Reject)
                .unwrap()
                .into_iter()
                .collect::<Vec<_>>(),
            vec!["r"]
        );
        assert_eq!(
            by_liked(&c).unwrap().into_iter().collect::<Vec<_>>(),
            vec!["l"]
        );
    }

    #[test]
    fn import_db_precedence_fills_gaps_only() {
        // db already has a rating: db wins, so no change for rating; label is a gap, so filled.
        let existing = Marks {
            rating: Some(5),
            ..Default::default()
        };
        let c = import_change(&existing, Some(2), Some("Red".into()), XmpPrecedence::Db).unwrap();
        assert!(c.rating.is_none(), "db rating kept");
        assert!(matches!(c.label, Some(Field::Set(ref s)) if s == "Red"));
    }

    #[test]
    fn import_file_precedence_overwrites() {
        let existing = Marks {
            rating: Some(5),
            ..Default::default()
        };
        let c = import_change(&existing, Some(2), None, XmpPrecedence::File).unwrap();
        assert!(matches!(c.rating, Some(Field::Set(2))));
    }

    #[test]
    fn import_nothing_to_do_is_none() {
        let existing = Marks {
            rating: Some(5),
            label: Some("Red".into()),
            ..Default::default()
        };
        assert!(
            import_change(&existing, Some(2), Some("Blue".into()), XmpPrecedence::Db).is_none()
        );
    }
}