Skip to main content

smriti/db/
takeout_import_repo.rs

1//! Durable bookkeeping for Google Photos Takeout imports.
2
3use std::collections::BTreeSet;
4
5use rusqlite::{params, Connection, OptionalExtension, Result as SqliteResult};
6
7pub struct TakeoutImportRepo<'a> {
8    conn: &'a Connection,
9}
10
11#[derive(Debug, Clone)]
12pub struct TakeoutLedgerItem {
13    pub content_hash: String,
14    pub file_path: String,
15    pub metadata_json: Option<String>,
16    pub albums: BTreeSet<String>,
17}
18
19impl<'a> TakeoutImportRepo<'a> {
20    pub fn new(conn: &'a Connection) -> Self {
21        Self { conn }
22    }
23
24    pub fn path_for_hash(&self, content_hash: &str) -> SqliteResult<Option<String>> {
25        self.conn
26            .query_row(
27                "SELECT file_path FROM google_takeout_items WHERE content_hash = ?1",
28                params![content_hash],
29                |row| row.get(0),
30            )
31            .optional()
32    }
33
34    pub fn upsert_items(&self, items: &[TakeoutLedgerItem]) -> SqliteResult<()> {
35        let tx = self.conn.unchecked_transaction()?;
36        for item in items {
37            tx.execute(
38                r#"
39                INSERT INTO google_takeout_items (content_hash, file_path, metadata_json)
40                VALUES (?1, ?2, ?3)
41                ON CONFLICT(content_hash) DO UPDATE SET
42                    file_path = excluded.file_path,
43                    metadata_json = COALESCE(excluded.metadata_json, google_takeout_items.metadata_json),
44                    updated_at = CURRENT_TIMESTAMP
45                "#,
46                params![item.content_hash, item.file_path, item.metadata_json],
47            )?;
48            for album in &item.albums {
49                tx.execute(
50                    "INSERT OR IGNORE INTO google_takeout_albums (content_hash, album_name) VALUES (?1, ?2)",
51                    params![item.content_hash, album],
52                )?;
53            }
54        }
55        tx.commit()
56    }
57
58    pub fn candidate_existing_files(
59        &self,
60        sizes: &std::collections::HashSet<i64>,
61    ) -> SqliteResult<Vec<(String, i64)>> {
62        let mut stmt = self
63            .conn
64            .prepare("SELECT file_path, file_size FROM photos WHERE is_trashed = FALSE")?;
65        let rows = stmt.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?;
66        let mut result = Vec::new();
67        for row in rows {
68            let row = row?;
69            if sizes.contains(&row.1) {
70                result.push(row);
71            }
72        }
73        Ok(result)
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80    use crate::db::Database;
81    use tempfile::tempdir;
82
83    #[test]
84    fn upsert_is_idempotent_and_unions_albums() {
85        let dir = tempdir().unwrap();
86        let db = Database::open_for_drive(dir.path()).unwrap();
87        crate::db::create_schema(&db.conn).unwrap();
88        let repo = TakeoutImportRepo::new(&db.conn);
89        let item = |metadata: Option<&str>, album: &str| TakeoutLedgerItem {
90            content_hash: "abc".into(),
91            file_path: "Imported from Google Photos/2020/a.jpg".into(),
92            metadata_json: metadata.map(str::to_string),
93            albums: BTreeSet::from([album.to_string()]),
94        };
95        repo.upsert_items(&[item(Some(r#"{"favorited":true}"#), "Trip")])
96            .unwrap();
97        repo.upsert_items(&[item(None, "Family")]).unwrap();
98
99        assert_eq!(
100            repo.path_for_hash("abc").unwrap().as_deref(),
101            Some("Imported from Google Photos/2020/a.jpg")
102        );
103        let count: i64 = db
104            .conn
105            .query_row(
106                "SELECT COUNT(*) FROM google_takeout_albums WHERE content_hash = 'abc'",
107                [],
108                |r| r.get(0),
109            )
110            .unwrap();
111        assert_eq!(count, 2);
112    }
113}