Skip to main content

smriti/db/
photo_repo.rs

1//! Photo database repository
2//!
3//! Handles all database operations for photos.
4
5use chrono::{DateTime, Utc};
6use rusqlite::{params, Connection, OptionalExtension, Result as SqliteResult};
7
8use crate::models::{MediaType, Photo};
9
10/// A discovered file ready for database insertion
11#[derive(Debug, Clone)]
12pub struct PhotoInsert {
13    pub relative_path: String,
14    pub file_name: String,
15    pub file_hash: String,
16    pub file_size: i64,
17    pub file_mtime: Option<i64>,
18    pub date_taken: Option<String>,
19    pub date_taken_source: Option<String>,
20    pub gps_latitude: Option<f64>,
21    pub gps_longitude: Option<f64>,
22    pub location_city: Option<String>,
23    pub location_country: Option<String>,
24    pub camera_make: Option<String>,
25    pub camera_model: Option<String>,
26    pub iso: Option<i32>,
27    pub aperture: Option<String>,
28    pub shutter_speed: Option<String>,
29    pub focal_length: Option<String>,
30    pub lens_model: Option<String>,
31    pub flash: Option<String>,
32    pub gps_altitude: Option<f64>,
33    pub width: Option<i32>,
34    pub height: Option<i32>,
35    pub orientation: i32,
36    pub media_type: MediaType,
37    pub duration_ms: Option<i64>,
38    pub video_codec: Option<String>,
39    pub audio_codec: Option<String>,
40    pub frame_rate: Option<f32>,
41    pub bitrate: Option<i64>,
42    pub has_audio: bool,
43}
44
45/// Photo repository for database operations
46pub struct PhotoRepo<'a> {
47    conn: &'a Connection,
48}
49
50pub type FavoriteAlbumSummary = (
51    i64,
52    Option<i64>,
53    Option<String>,
54    Option<String>,
55    Option<String>,
56);
57
58impl<'a> PhotoRepo<'a> {
59    pub fn new(conn: &'a Connection) -> Self {
60        Self { conn }
61    }
62
63    /// Batch insert stub rows (streaming scanner Phase 1B).
64    ///
65    /// Uses `INSERT OR IGNORE` so an idempotent re-scan never blows away
66    /// metadata that Phase 2+ already filled in. Only sets the columns
67    /// known at walk time; everything else (EXIF, thumbnail, geocoding)
68    /// is updated later by the pipeline workers.
69    pub fn insert_batch_stub(&self, photos: &[PhotoInsert]) -> SqliteResult<usize> {
70        let tx = self.conn.unchecked_transaction()?;
71        let mut count = 0;
72
73        for photo in photos {
74            let changed = tx.execute(
75                r#"
76                INSERT INTO photos (
77                    file_path, file_name, file_hash, file_size, file_mtime,
78                    orientation, media_type, metadata_extracted, thumbnailed, faces_processed
79                ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, FALSE, FALSE, FALSE)
80                ON CONFLICT(file_path) DO NOTHING
81                "#,
82                params![
83                    photo.relative_path,
84                    photo.file_name,
85                    photo.file_hash,
86                    photo.file_size,
87                    photo.file_mtime,
88                    photo.orientation,
89                    photo.media_type.as_str(),
90                ],
91            )?;
92            count += changed;
93        }
94
95        tx.commit()?;
96        Ok(count)
97    }
98
99    /// Batch insert photos within a transaction
100    pub fn insert_batch(&self, photos: &[PhotoInsert]) -> SqliteResult<usize> {
101        let tx = self.conn.unchecked_transaction()?;
102        let mut count = 0;
103
104        for photo in photos {
105            tx.execute(
106                r#"
107                INSERT INTO photos (
108                    file_path, file_name, file_hash, file_size, file_mtime,
109                    date_taken, date_taken_source,
110                    gps_latitude, gps_longitude,
111                    location_city, location_country,
112                    camera_make, camera_model,
113                    iso, aperture, shutter_speed, focal_length,
114                    lens_model, flash, gps_altitude,
115                    width, height, orientation,
116                    media_type, duration_ms, video_codec, audio_codec,
117                    frame_rate, bitrate, has_audio
118                ) VALUES (
119                    ?1, ?2, ?3, ?4, ?5,
120                    ?6, ?7,
121                    ?8, ?9,
122                    ?10, ?11,
123                    ?12, ?13,
124                    ?14, ?15, ?16, ?17,
125                    ?18, ?19, ?20,
126                    ?21, ?22, ?23,
127                    ?24, ?25, ?26, ?27,
128                    ?28, ?29, ?30
129                )
130                ON CONFLICT(file_path) DO UPDATE SET
131                    file_hash = excluded.file_hash,
132                    file_size = excluded.file_size,
133                    file_mtime = excluded.file_mtime,
134                    date_taken = excluded.date_taken,
135                    date_taken_source = excluded.date_taken_source,
136                    gps_latitude = excluded.gps_latitude,
137                    gps_longitude = excluded.gps_longitude,
138                    location_city = COALESCE(excluded.location_city, photos.location_city),
139                    location_country = COALESCE(excluded.location_country, photos.location_country),
140                    camera_make = excluded.camera_make,
141                    camera_model = excluded.camera_model,
142                    iso = excluded.iso,
143                    aperture = excluded.aperture,
144                    shutter_speed = excluded.shutter_speed,
145                    focal_length = excluded.focal_length,
146                    lens_model = excluded.lens_model,
147                    flash = excluded.flash,
148                    gps_altitude = excluded.gps_altitude,
149                    width = excluded.width,
150                    height = excluded.height,
151                    orientation = excluded.orientation,
152                    media_type = excluded.media_type,
153                    duration_ms = excluded.duration_ms,
154                    video_codec = excluded.video_codec,
155                    audio_codec = excluded.audio_codec,
156                    frame_rate = excluded.frame_rate,
157                    bitrate = excluded.bitrate,
158                    has_audio = excluded.has_audio,
159                    updated_at = CURRENT_TIMESTAMP
160                "#,
161                params![
162                    photo.relative_path,
163                    photo.file_name,
164                    photo.file_hash,
165                    photo.file_size,
166                    photo.file_mtime,
167                    photo.date_taken,
168                    photo.date_taken_source,
169                    photo.gps_latitude,
170                    photo.gps_longitude,
171                    photo.location_city,
172                    photo.location_country,
173                    photo.camera_make,
174                    photo.camera_model,
175                    photo.iso,
176                    photo.aperture,
177                    photo.shutter_speed,
178                    photo.focal_length,
179                    photo.lens_model,
180                    photo.flash,
181                    photo.gps_altitude,
182                    photo.width,
183                    photo.height,
184                    photo.orientation,
185                    photo.media_type.as_str(),
186                    photo.duration_ms,
187                    photo.video_codec,
188                    photo.audio_codec,
189                    photo.frame_rate,
190                    photo.bitrate,
191                    photo.has_audio,
192                ],
193            )?;
194            count += 1;
195        }
196
197        tx.commit()?;
198        Ok(count)
199    }
200
201    /// Get total photo count
202    pub fn count(&self) -> SqliteResult<i64> {
203        self.conn.query_row(
204            "SELECT COUNT(*) FROM photos WHERE is_trashed = FALSE",
205            [],
206            |row| row.get(0),
207        )
208    }
209
210    pub fn count_timeline_visible(&self, show_stacks: bool) -> SqliteResult<i64> {
211        if !show_stacks {
212            return self.count();
213        }
214        self.conn.query_row(
215            &format!(
216                r#"
217            WITH live_stacks AS ({live_stacks_cte})
218            SELECT COUNT(*)
219              FROM photos p
220             WHERE p.is_trashed = FALSE
221               AND NOT EXISTS (
222                   SELECT 1
223                     FROM photo_stack_members m
224                     JOIN live_stacks s ON s.id = m.stack_id
225                    WHERE m.photo_id = p.id
226                      AND p.id != s.cover_photo_id
227               )
228            "#,
229                live_stacks_cte = LIVE_STACKS_CTE
230            ),
231            [],
232            |row| row.get(0),
233        )
234    }
235
236    /// Timeline-visible photos per capture year, in timeline order (newest
237    /// year first, undated last). Uses the same visibility rules as
238    /// `count_timeline_visible`, so the counts add up to the timeline total
239    /// and let the scrubber place year markers without loading every row.
240    pub fn timeline_year_counts(&self, show_stacks: bool) -> SqliteResult<Vec<(Option<i32>, i64)>> {
241        let stack_filter = if show_stacks {
242            r#"AND NOT EXISTS (
243                   SELECT 1
244                     FROM photo_stack_members m
245                     JOIN live_stacks s ON s.id = m.stack_id
246                    WHERE m.photo_id = p.id
247                      AND p.id != s.cover_photo_id
248               )"#
249        } else {
250            ""
251        };
252        let sql = format!(
253            r#"
254            WITH live_stacks AS ({live_stacks_cte})
255            SELECT CAST(substr(p.date_taken, 1, 4) AS INTEGER) AS year, COUNT(*)
256              FROM photos p
257             WHERE p.is_trashed = FALSE
258               {stack_filter}
259             GROUP BY year
260             ORDER BY year IS NULL ASC, year DESC
261            "#,
262            live_stacks_cte = LIVE_STACKS_CTE,
263        );
264        let mut stmt = self.conn.prepare(&sql)?;
265        let rows = stmt.query_map([], |row| Ok((row.get::<_, Option<i32>>(0)?, row.get(1)?)))?;
266        rows.collect()
267    }
268
269    /// Photos awaiting EXIF / geocoding extraction (Phase 2 of the
270    /// streaming scanner). Drives the "Resume reading metadata" banner.
271    pub fn count_pending_metadata(&self) -> SqliteResult<i64> {
272        self.conn.query_row(
273            "SELECT COUNT(*) FROM photos WHERE metadata_extracted = FALSE AND is_trashed = FALSE",
274            [],
275            |row| row.get(0),
276        )
277    }
278
279    /// Photos awaiting thumbnail generation (Phase 3).
280    pub fn count_pending_thumbnails(&self) -> SqliteResult<i64> {
281        self.conn.query_row(
282            "SELECT COUNT(*) FROM photos WHERE thumbnailed = FALSE AND is_trashed = FALSE AND media_type = 'photo'",
283            [],
284            |row| row.get(0),
285        )
286    }
287
288    /// Every stored relative path, trashed rows included.
289    pub fn all_file_paths(&self) -> SqliteResult<std::collections::HashSet<String>> {
290        let mut stmt = self.conn.prepare("SELECT file_path FROM photos")?;
291        let rows = stmt.query_map([], |row| row.get::<_, String>(0))?;
292        rows.collect()
293    }
294
295    /// Get all photos ordered by date
296    pub fn get_all_by_date(&self, limit: i64, offset: i64) -> SqliteResult<Vec<Photo>> {
297        let mut stmt = self.conn.prepare(
298            r#"
299            SELECT
300                id, file_path, file_name, file_hash, file_size,
301                date_taken, date_taken_source,
302                gps_latitude, gps_longitude,
303                location_city, location_country,
304                camera_make, camera_model,
305                iso, aperture, shutter_speed, focal_length,
306                lens_model, flash, gps_altitude,
307                width, height, orientation,
308                media_type, duration_ms, video_codec, audio_codec,
309                frame_rate, bitrate, has_audio,
310                thumbnail_path, faces_processed,
311                is_favorite,
312                is_trashed, trashed_at,
313                indexed_at, updated_at
314            FROM photos
315            WHERE is_trashed = FALSE
316            ORDER BY date_taken DESC
317            LIMIT ?1 OFFSET ?2
318            "#,
319        )?;
320
321        let rows = stmt.query_map(params![limit, offset], row_to_photo)?;
322
323        let mut photos = Vec::new();
324        for row in rows {
325            photos.push(row?);
326        }
327
328        Ok(photos)
329    }
330
331    /// Get photos by IDs ordered by date (descending).
332    pub fn get_by_ids(&self, photo_ids: &[i64]) -> SqliteResult<Vec<Photo>> {
333        if photo_ids.is_empty() {
334            return Ok(Vec::new());
335        }
336
337        let mut all = Vec::new();
338
339        // Keep IN clause under SQLite variable limits.
340        for chunk in photo_ids.chunks(900) {
341            let placeholders = (0..chunk.len()).map(|_| "?").collect::<Vec<_>>().join(",");
342
343            let sql = format!(
344                r#"
345                SELECT
346                    id, file_path, file_name, file_hash, file_size,
347                    date_taken, date_taken_source,
348                    gps_latitude, gps_longitude,
349                    location_city, location_country,
350                    camera_make, camera_model,
351                    iso, aperture, shutter_speed, focal_length,
352                    lens_model, flash, gps_altitude,
353                    width, height, orientation,
354                    media_type, duration_ms, video_codec, audio_codec,
355                    frame_rate, bitrate, has_audio,
356                    thumbnail_path, faces_processed,
357                    is_favorite,
358                    is_trashed, trashed_at,
359                    indexed_at, updated_at
360                FROM photos
361                WHERE is_trashed = FALSE AND id IN ({})
362                "#,
363                placeholders
364            );
365
366            let mut stmt = self.conn.prepare(&sql)?;
367            let rows = stmt.query_map(
368                rusqlite::params_from_iter(chunk.iter().copied()),
369                row_to_photo,
370            )?;
371            for row in rows {
372                all.push(row?);
373            }
374        }
375
376        all.sort_by_key(|p| std::cmp::Reverse(p.date_taken));
377        Ok(all)
378    }
379
380    /// Get a single photo by ID.
381    pub fn get_by_id(&self, id: i64) -> SqliteResult<Option<Photo>> {
382        let mut stmt = self.conn.prepare(
383            r#"
384            SELECT
385                id, file_path, file_name, file_hash, file_size,
386                date_taken, date_taken_source,
387                gps_latitude, gps_longitude,
388                location_city, location_country,
389                camera_make, camera_model,
390                iso, aperture, shutter_speed, focal_length,
391                lens_model, flash, gps_altitude,
392                width, height, orientation,
393                media_type, duration_ms, video_codec, audio_codec,
394                frame_rate, bitrate, has_audio,
395                thumbnail_path, faces_processed,
396                is_favorite,
397                is_trashed, trashed_at,
398                indexed_at, updated_at
399            FROM photos
400            WHERE id = ?1
401            "#,
402        )?;
403
404        match stmt.query_row(params![id], row_to_photo) {
405            Ok(photo) => Ok(Some(photo)),
406            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
407            Err(e) => Err(e),
408        }
409    }
410
411    pub fn set_favorite(&self, id: i64, is_favorite: bool) -> SqliteResult<usize> {
412        self.conn.execute(
413            "UPDATE photos SET is_favorite = ?1, updated_at = CURRENT_TIMESTAMP WHERE id = ?2",
414            params![is_favorite, id],
415        )
416    }
417
418    pub fn favorites_album_summary(&self) -> SqliteResult<Option<FavoriteAlbumSummary>> {
419        self.conn.query_row(
420            r#"
421            SELECT
422                COUNT(*),
423                (
424                    SELECT id
425                    FROM photos
426                    WHERE is_favorite = TRUE AND is_trashed = FALSE
427                    ORDER BY date_taken IS NULL ASC, date_taken DESC, id DESC
428                    LIMIT 1
429                ),
430                (
431                    SELECT thumbnail_path
432                    FROM photos
433                    WHERE is_favorite = TRUE AND is_trashed = FALSE
434                    ORDER BY date_taken IS NULL ASC, date_taken DESC, id DESC
435                    LIMIT 1
436                ),
437                MIN(date_taken),
438                MAX(date_taken)
439            FROM photos
440            WHERE is_favorite = TRUE AND is_trashed = FALSE
441            "#,
442            [],
443            |row| {
444                let count: i64 = row.get(0)?;
445                if count == 0 {
446                    Ok(None)
447                } else {
448                    Ok(Some((
449                        count,
450                        row.get(1)?,
451                        row.get(2)?,
452                        row.get(3)?,
453                        row.get(4)?,
454                    )))
455                }
456            },
457        )
458    }
459}
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464    use crate::db::schema::create_schema;
465    use rusqlite::Connection;
466
467    #[test]
468    fn timeline_year_counts_match_timeline_order_and_total() {
469        let conn = Connection::open_in_memory().unwrap();
470        create_schema(&conn).unwrap();
471        for (id, date, trashed) in [
472            (1, Some("2019-05-01T10:00:00"), false),
473            (2, Some("2021-01-02T10:00:00"), false),
474            (3, Some("2021-12-31T23:00:00"), false),
475            (4, None, false),
476            (5, Some("2021-06-01T10:00:00"), true),
477        ] {
478            conn.execute(
479                "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, date_taken, is_trashed)
480                 VALUES (?1, ?2, ?2, ?2, 2048, ?3, ?4)",
481                params![id, format!("p{id}.jpg"), date, trashed],
482            )
483            .unwrap();
484        }
485        let repo = PhotoRepo::new(&conn);
486        let counts = repo.timeline_year_counts(true).unwrap();
487        assert_eq!(counts, vec![(Some(2021), 2), (Some(2019), 1), (None, 1)]);
488        let sum: i64 = counts.iter().map(|(_, n)| n).sum();
489        assert_eq!(sum, repo.count_timeline_visible(true).unwrap());
490    }
491
492    #[test]
493    fn insert_batch_stub_counts_only_new_rows() {
494        let conn = Connection::open_in_memory().unwrap();
495        create_schema(&conn).unwrap();
496        let repo = PhotoRepo::new(&conn);
497        let photo = PhotoInsert {
498            relative_path: "img.jpg".into(),
499            file_name: "img.jpg".into(),
500            file_hash: "hash".into(),
501            file_size: 12,
502            file_mtime: Some(100),
503            date_taken: None,
504            date_taken_source: None,
505            gps_latitude: None,
506            gps_longitude: None,
507            location_city: None,
508            location_country: None,
509            camera_make: None,
510            camera_model: None,
511            iso: None,
512            aperture: None,
513            shutter_speed: None,
514            focal_length: None,
515            lens_model: None,
516            flash: None,
517            gps_altitude: None,
518            width: None,
519            height: None,
520            orientation: 1,
521            media_type: MediaType::Photo,
522            duration_ms: None,
523            video_codec: None,
524            audio_codec: None,
525            frame_rate: None,
526            bitrate: None,
527            has_audio: false,
528        };
529
530        assert_eq!(
531            repo.insert_batch_stub(std::slice::from_ref(&photo))
532                .unwrap(),
533            1
534        );
535        assert_eq!(repo.insert_batch_stub(&[photo]).unwrap(), 0);
536    }
537
538    #[test]
539    fn list_after_by_person_uses_valid_stack_aliases() {
540        let conn = Connection::open_in_memory().unwrap();
541        create_schema(&conn).unwrap();
542        conn.execute(
543            "INSERT INTO face_clusters (id, face_count, photo_count) VALUES (7, 1, 1)",
544            [],
545        )
546        .unwrap();
547        conn.execute(
548            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, date_taken, is_trashed)
549             VALUES (1, 'img.jpg', 'img.jpg', 'hash', 12, '2024-01-01T00:00:00Z', 0)",
550            [],
551        )
552        .unwrap();
553        conn.execute(
554            "INSERT INTO faces (photo_id, bbox_x, bbox_y, bbox_width, bbox_height, embedding, cluster_id, confidence)
555             VALUES (1, 0.0, 0.0, 0.1, 0.1, zeroblob(16), 7, 0.9)",
556            [],
557        )
558        .unwrap();
559
560        let rows = PhotoRepo::new(&conn)
561            .list_after_by_person(7, None, 10)
562            .unwrap();
563        assert_eq!(rows.len(), 1);
564        assert_eq!(rows[0].id, 1);
565        assert!(rows[0].stack_id.is_none());
566    }
567
568    #[test]
569    fn list_after_by_person_includes_inferred_identity_photos() {
570        let conn = Connection::open_in_memory().unwrap();
571        create_schema(&conn).unwrap();
572        conn.execute(
573            "INSERT INTO face_clusters (id, face_count, photo_count) VALUES (7, 1, 2)",
574            [],
575        )
576        .unwrap();
577        conn.execute(
578            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, date_taken, is_trashed)
579             VALUES
580             (1, 'direct.jpg', 'direct.jpg', 'hash-direct', 12, '2024-02-01T00:00:00Z', 0),
581             (2, 'inferred.jpg', 'inferred.jpg', 'hash-inferred', 12, '2024-01-01T00:00:00Z', 0)",
582            [],
583        )
584        .unwrap();
585        conn.execute(
586            "INSERT INTO faces (photo_id, bbox_x, bbox_y, bbox_width, bbox_height, embedding, cluster_id, confidence)
587             VALUES (1, 0.0, 0.0, 0.1, 0.1, zeroblob(16), 7, 0.9)",
588            [],
589        )
590        .unwrap();
591        conn.execute(
592            "INSERT INTO photo_inferred_identities (photo_id, cluster_id, source_photo_id, confidence)
593             VALUES (2, 7, 1, 0.8)",
594            [],
595        )
596        .unwrap();
597
598        let ids = PhotoRepo::new(&conn)
599            .list_after_by_person(7, None, 10)
600            .unwrap()
601            .into_iter()
602            .map(|p| p.id)
603            .collect::<Vec<_>>();
604
605        assert_eq!(ids, vec![1, 2]);
606    }
607
608    #[test]
609    fn favorites_summary_only_exists_for_visible_favorites() {
610        let conn = Connection::open_in_memory().unwrap();
611        create_schema(&conn).unwrap();
612        conn.execute(
613            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, date_taken, thumbnail_path, is_favorite, is_trashed)
614             VALUES
615             (1, 'a.jpg', 'a.jpg', 'hash-a', 12, '2024-01-01T00:00:00Z', 'thumb-a.jpg', 1, 0),
616             (2, 'b.jpg', 'b.jpg', 'hash-b', 12, '2024-02-01T00:00:00Z', 'thumb-b.jpg', 1, 1),
617             (3, 'c.jpg', 'c.jpg', 'hash-c', 12, '2024-03-01T00:00:00Z', 'thumb-c.jpg', 0, 0)",
618            [],
619        )
620        .unwrap();
621
622        let repo = PhotoRepo::new(&conn);
623        let summary = repo.favorites_album_summary().unwrap().unwrap();
624        assert_eq!(summary.0, 1);
625        assert_eq!(summary.1, Some(1));
626        assert_eq!(summary.2.as_deref(), Some("thumb-a.jpg"));
627
628        repo.set_favorite(1, false).unwrap();
629        assert!(repo.favorites_album_summary().unwrap().is_none());
630    }
631
632    #[test]
633    fn timeline_neighbors_follow_timeline_order_and_skip_trash() {
634        let conn = Connection::open_in_memory().unwrap();
635        create_schema(&conn).unwrap();
636        conn.execute(
637            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, date_taken, is_trashed)
638             VALUES
639             (1, 'a.jpg', 'a.jpg', 'hash-a', 12, '2025-01-02T00:00:00Z', 0),
640             (2, 'b.jpg', 'b.jpg', 'hash-b', 12, '2025-01-01T00:00:00Z', 0),
641             (3, 'c.jpg', 'c.jpg', 'hash-c', 12, '2024-12-31T00:00:00Z', 1),
642             (4, 'd.jpg', 'd.jpg', 'hash-d', 12, NULL, 0)",
643            [],
644        )
645        .unwrap();
646
647        let repo = PhotoRepo::new(&conn);
648        let n = repo.timeline_neighbors(2, false).unwrap().unwrap();
649        assert_eq!(n.prev_id, Some(1));
650        assert_eq!(n.next_id, Some(4));
651
652        let null_n = repo.timeline_neighbors(4, false).unwrap().unwrap();
653        assert_eq!(null_n.prev_id, Some(2));
654        assert_eq!(null_n.next_id, None);
655    }
656
657    #[test]
658    fn list_at_offset_uses_timeline_order_and_skip_trash() {
659        let conn = Connection::open_in_memory().unwrap();
660        create_schema(&conn).unwrap();
661        conn.execute(
662            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, date_taken, is_trashed)
663             VALUES
664             (1, 'a.jpg', 'a.jpg', 'hash-a', 12, '2025-01-04T00:00:00Z', 0),
665             (2, 'b.jpg', 'b.jpg', 'hash-b', 12, '2025-01-03T00:00:00Z', 0),
666             (3, 'c.jpg', 'c.jpg', 'hash-c', 12, '2025-01-02T00:00:00Z', 1),
667             (4, 'd.jpg', 'd.jpg', 'hash-d', 12, '2025-01-01T00:00:00Z', 0),
668             (5, 'e.jpg', 'e.jpg', 'hash-e', 12, NULL, 0)",
669            [],
670        )
671        .unwrap();
672
673        let rows = PhotoRepo::new(&conn)
674            .list_at_offset(1, 2, false, false)
675            .unwrap();
676        assert_eq!(rows.iter().map(|p| p.id).collect::<Vec<_>>(), vec![2, 4]);
677    }
678
679    #[test]
680    fn list_after_by_date_uses_half_open_end() {
681        let conn = Connection::open_in_memory().unwrap();
682        create_schema(&conn).unwrap();
683        conn.execute(
684            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, date_taken, is_trashed)
685             VALUES
686             (1, 'a.jpg', 'a.jpg', 'hash-a', 12, '2025-01-01T23:59:59Z', 0),
687             (2, 'b.jpg', 'b.jpg', 'hash-b', 12, '2025-01-02T00:00:00Z', 0)",
688            [],
689        )
690        .unwrap();
691
692        let rows = PhotoRepo::new(&conn)
693            .list_after_by_date("2025-01-01T00:00:00Z", "2025-01-02T00:00:00Z", None, 10)
694            .unwrap();
695        assert_eq!(rows.iter().map(|p| p.id).collect::<Vec<_>>(), vec![1]);
696    }
697
698    #[test]
699    fn timeline_neighbors_hide_non_cover_stack_members_when_enabled() {
700        let conn = Connection::open_in_memory().unwrap();
701        create_schema(&conn).unwrap();
702        conn.execute(
703            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, date_taken, is_trashed)
704             VALUES
705             (1, 'a.jpg', 'a.jpg', 'hash-a', 12, '2025-01-04T00:00:00Z', 0),
706             (2, 'b.jpg', 'b.jpg', 'hash-b', 12, '2025-01-03T00:00:00Z', 0),
707             (3, 'c.jpg', 'c.jpg', 'hash-c', 12, '2025-01-02T00:00:00Z', 0),
708             (4, 'd.jpg', 'd.jpg', 'hash-d', 12, '2025-01-01T00:00:00Z', 0)",
709            [],
710        )
711        .unwrap();
712        conn.execute(
713            "INSERT INTO photo_stacks (id, kind, source_group_id, cover_photo_id)
714             VALUES (10, 'burst', 99, 2)",
715            [],
716        )
717        .unwrap();
718        conn.execute(
719            "INSERT INTO photo_stack_members (stack_id, photo_id, is_cover)
720             VALUES (10, 2, 1), (10, 3, 0)",
721            [],
722        )
723        .unwrap();
724
725        let repo = PhotoRepo::new(&conn);
726        let n = repo.timeline_neighbors(2, true).unwrap().unwrap();
727        assert_eq!(n.prev_id, Some(1));
728        assert_eq!(n.next_id, Some(4));
729
730        let unstacked = repo.timeline_neighbors(2, false).unwrap().unwrap();
731        assert_eq!(unstacked.next_id, Some(3));
732    }
733
734    #[test]
735    fn stacked_timeline_counts_only_live_members() {
736        let conn = Connection::open_in_memory().unwrap();
737        create_schema(&conn).unwrap();
738        conn.execute(
739            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, date_taken, is_trashed)
740             VALUES
741             (1, 'a.jpg', 'a.jpg', 'hash-a', 12, '2025-01-04T00:00:00Z', 0),
742             (2, 'b.jpg', 'b.jpg', 'hash-b', 12, '2025-01-03T00:00:00Z', 0),
743             (3, 'c.jpg', 'c.jpg', 'hash-c', 12, '2025-01-02T00:00:00Z', 1),
744             (4, 'd.jpg', 'd.jpg', 'hash-d', 12, '2025-01-01T00:00:00Z', 0)",
745            [],
746        )
747        .unwrap();
748        conn.execute(
749            "INSERT INTO photo_stacks (id, kind, source_group_id, cover_photo_id)
750             VALUES (10, 'burst', 99, 2)",
751            [],
752        )
753        .unwrap();
754        conn.execute(
755            "INSERT INTO photo_stack_members (stack_id, photo_id, is_cover)
756             VALUES (10, 2, 1), (10, 3, 0), (10, 4, 0)",
757            [],
758        )
759        .unwrap();
760
761        let repo = PhotoRepo::new(&conn);
762        let rows = repo.list_after(None, 10, false, true).unwrap();
763        let stacked = rows.iter().find(|p| p.id == 2).unwrap();
764        assert_eq!(stacked.stack_member_count, Some(2));
765        assert!(rows.iter().all(|p| p.id != 4));
766    }
767
768    #[test]
769    fn stacked_timeline_ignores_stack_when_cover_is_trashed() {
770        let conn = Connection::open_in_memory().unwrap();
771        create_schema(&conn).unwrap();
772        conn.execute(
773            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, date_taken, is_trashed)
774             VALUES
775             (1, 'a.jpg', 'a.jpg', 'hash-a', 12, '2025-01-04T00:00:00Z', 0),
776             (2, 'b.jpg', 'b.jpg', 'hash-b', 12, '2025-01-03T00:00:00Z', 1),
777             (3, 'c.jpg', 'c.jpg', 'hash-c', 12, '2025-01-02T00:00:00Z', 0)",
778            [],
779        )
780        .unwrap();
781        conn.execute(
782            "INSERT INTO photo_stacks (id, kind, source_group_id, cover_photo_id)
783             VALUES (10, 'burst', 99, 2)",
784            [],
785        )
786        .unwrap();
787        conn.execute(
788            "INSERT INTO photo_stack_members (stack_id, photo_id, is_cover)
789             VALUES (10, 2, 1), (10, 3, 0)",
790            [],
791        )
792        .unwrap();
793
794        let repo = PhotoRepo::new(&conn);
795        let rows = repo.list_after(None, 10, false, true).unwrap();
796        let photo = rows.iter().find(|p| p.id == 3).unwrap();
797        assert_eq!(photo.stack_id, None);
798
799        let neighbors = repo.timeline_neighbors(1, true).unwrap().unwrap();
800        assert_eq!(neighbors.next_id, Some(3));
801    }
802}
803
804/// Convert a database row to a Photo struct.
805///
806/// The selected columns must match the ordering used by `PhotoRepo`.
807pub(crate) fn row_to_photo(row: &rusqlite::Row) -> SqliteResult<Photo> {
808    Ok(Photo {
809        id: row.get(0)?,
810        file_path: row.get(1)?,
811        file_name: row.get(2)?,
812        file_hash: row.get(3)?,
813        file_size: row.get(4)?,
814        date_taken: row
815            .get::<_, Option<String>>(5)?
816            .and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
817            .map(|d| d.with_timezone(&Utc)),
818        date_taken_source: row.get(6)?,
819        gps_latitude: row.get(7)?,
820        gps_longitude: row.get(8)?,
821        location_city: row.get(9)?,
822        location_country: row.get(10)?,
823        camera_make: row.get(11)?,
824        camera_model: row.get(12)?,
825        iso: row.get(13)?,
826        aperture: row.get(14)?,
827        shutter_speed: row.get(15)?,
828        focal_length: row.get(16)?,
829        lens_model: row.get(17)?,
830        flash: row.get(18)?,
831        gps_altitude: row.get(19)?,
832        width: row.get(20)?,
833        height: row.get(21)?,
834        orientation: row.get::<_, Option<i32>>(22)?.unwrap_or(1),
835        media_type: row
836            .get::<_, Option<String>>(23)?
837            .map(|s| MediaType::from_db(&s))
838            .unwrap_or_default(),
839        duration_ms: row.get(24)?,
840        video_codec: row.get(25)?,
841        audio_codec: row.get(26)?,
842        frame_rate: row.get(27)?,
843        bitrate: row.get(28)?,
844        has_audio: row.get::<_, Option<bool>>(29)?.unwrap_or(false),
845        thumbnail_path: row.get(30)?,
846        faces_processed: row.get(31)?,
847        is_favorite: row.get::<_, Option<bool>>(32)?.unwrap_or(false),
848        is_trashed: row.get(33)?,
849        trashed_at: row
850            .get::<_, Option<String>>(34)?
851            .and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
852            .map(|d| d.with_timezone(&Utc)),
853        indexed_at: row
854            .get::<_, String>(35)?
855            .parse::<DateTime<Utc>>()
856            .unwrap_or(DateTime::<Utc>::UNIX_EPOCH),
857        updated_at: row
858            .get::<_, String>(36)?
859            .parse::<DateTime<Utc>>()
860            .unwrap_or(DateTime::<Utc>::UNIX_EPOCH),
861    })
862}
863
864/// Cursor-based pagination methods used by the Tauri command surface.
865///
866/// A short descriptor for a photo that's enough to render a grid cell or
867/// a map pin, without paying the cost of a full Photo materialisation.
868///
869/// Cursor-paginated reads use `(date_taken DESC, id DESC)` with explicit
870/// `IS NULL` ordering so a stable cursor can be carried across pages.
871#[derive(Debug, Clone)]
872pub struct PhotoLite {
873    pub id: i64,
874    pub date_taken: Option<DateTime<Utc>>,
875    pub thumbnail_path: Option<String>,
876    pub width: Option<i32>,
877    pub height: Option<i32>,
878    pub orientation: i32,
879    pub is_trashed: bool,
880    pub is_favorite: bool,
881    pub gps_latitude: Option<f64>,
882    pub gps_longitude: Option<f64>,
883    pub media_type: MediaType,
884    pub duration_ms: Option<i64>,
885    pub stack_id: Option<i64>,
886    pub stack_kind: Option<String>,
887    pub stack_member_count: Option<i64>,
888    pub stack_cover_photo_id: Option<i64>,
889}
890
891#[derive(Debug, Clone, Copy, PartialEq, Eq)]
892pub struct TimelineNeighbors {
893    pub prev_id: Option<i64>,
894    pub next_id: Option<i64>,
895}
896
897fn row_to_photo_lite(row: &rusqlite::Row) -> SqliteResult<PhotoLite> {
898    Ok(PhotoLite {
899        id: row.get(0)?,
900        date_taken: row
901            .get::<_, Option<String>>(1)?
902            .and_then(|s| DateTime::parse_from_rfc3339(&s).ok())
903            .map(|d| d.with_timezone(&Utc)),
904        thumbnail_path: row.get(2)?,
905        width: row.get(3)?,
906        height: row.get(4)?,
907        orientation: row.get::<_, Option<i32>>(5)?.unwrap_or(1),
908        is_trashed: row.get(6)?,
909        is_favorite: row.get::<_, Option<bool>>(7)?.unwrap_or(false),
910        gps_latitude: row.get(8)?,
911        gps_longitude: row.get(9)?,
912        media_type: row
913            .get::<_, Option<String>>(10)?
914            .map(|s| MediaType::from_db(&s))
915            .unwrap_or_default(),
916        duration_ms: row.get(11)?,
917        stack_id: row.get(12)?,
918        stack_kind: row.get(13)?,
919        stack_member_count: row.get(14)?,
920        stack_cover_photo_id: row.get(15)?,
921    })
922}
923
924const PHOTO_LITE_COLUMNS: &str = r#"
925    id, date_taken, thumbnail_path,
926    width, height, orientation, is_trashed, is_favorite,
927    gps_latitude, gps_longitude,
928    media_type, duration_ms,
929    NULL AS stack_id, NULL AS stack_kind, NULL AS stack_member_count, NULL AS stack_cover_photo_id
930"#;
931
932const PHOTO_LITE_P_COLUMNS: &str = r#"
933    p.id, p.date_taken, p.thumbnail_path,
934    p.width, p.height, p.orientation, p.is_trashed, p.is_favorite,
935    p.gps_latitude, p.gps_longitude,
936    p.media_type, p.duration_ms,
937    NULL AS stack_id, NULL AS stack_kind, NULL AS stack_member_count, NULL AS stack_cover_photo_id
938"#;
939
940const PHOTO_LITE_STACKED_COLUMNS: &str = r#"
941    p.id, p.date_taken, p.thumbnail_path,
942    p.width, p.height, p.orientation, p.is_trashed, p.is_favorite,
943    p.gps_latitude, p.gps_longitude,
944    p.media_type, p.duration_ms,
945    s.id AS stack_id, s.kind AS stack_kind, s.stack_member_count AS stack_member_count,
946    s.cover_photo_id AS stack_cover_photo_id
947"#;
948
949const LIVE_STACKS_CTE: &str = r#"
950    SELECT s.id,
951           s.kind,
952           s.cover_photo_id,
953           COUNT(live_p.id) AS stack_member_count
954      FROM photo_stacks s
955      JOIN photos cover ON cover.id = s.cover_photo_id AND cover.is_trashed = FALSE
956      JOIN photo_stack_members live_m ON live_m.stack_id = s.id
957      JOIN photos live_p ON live_p.id = live_m.photo_id AND live_p.is_trashed = FALSE
958     WHERE s.dismissed = FALSE
959     GROUP BY s.id
960    HAVING COUNT(live_p.id) >= 2
961"#;
962
963impl<'a> PhotoRepo<'a> {
964    /// Cursor-paginated timeline list. Cursor key is `(date_taken, id)`
965    /// descending. NULL date_taken sorts last via SQLite's `IS NULL`.
966    /// `limit` is clamped by the caller; this just trusts it.
967    pub fn list_after(
968        &self,
969        cursor: Option<(Option<DateTime<Utc>>, i64)>,
970        limit: i64,
971        include_trashed: bool,
972        show_stacks: bool,
973    ) -> SqliteResult<Vec<PhotoLite>> {
974        if show_stacks && !include_trashed {
975            return self.list_after_stacked(cursor, limit);
976        }
977        let trash_clause = if include_trashed {
978            "1=1"
979        } else {
980            "is_trashed = 0"
981        };
982
983        let (sql, rows): (String, Vec<PhotoLite>) = match cursor {
984            Some((Some(d), id)) => {
985                let s = format!(
986                    "SELECT {cols} FROM photos
987                     WHERE {trash}
988                       AND ((date_taken IS NOT NULL AND
989                             (date_taken < ?1 OR (date_taken = ?1 AND id < ?2)))
990                            OR (date_taken IS NULL AND ?1 IS NULL AND id < ?2))
991                     ORDER BY date_taken IS NULL ASC, date_taken DESC, id DESC
992                     LIMIT ?3",
993                    cols = PHOTO_LITE_COLUMNS,
994                    trash = trash_clause
995                );
996                let date_str = d.to_rfc3339();
997                let mut stmt = self.conn.prepare(&s)?;
998                let mapped = stmt.query_map(params![date_str, id, limit], row_to_photo_lite)?;
999                let mut v = Vec::new();
1000                for r in mapped {
1001                    v.push(r?);
1002                }
1003                (s, v)
1004            }
1005            Some((None, id)) => {
1006                let s = format!(
1007                    "SELECT {cols} FROM photos
1008                     WHERE {trash} AND date_taken IS NULL AND id < ?1
1009                     ORDER BY id DESC LIMIT ?2",
1010                    cols = PHOTO_LITE_COLUMNS,
1011                    trash = trash_clause
1012                );
1013                let mut stmt = self.conn.prepare(&s)?;
1014                let mapped = stmt.query_map(params![id, limit], row_to_photo_lite)?;
1015                let mut v = Vec::new();
1016                for r in mapped {
1017                    v.push(r?);
1018                }
1019                (s, v)
1020            }
1021            None => {
1022                let s = format!(
1023                    "SELECT {cols} FROM photos
1024                     WHERE {trash}
1025                     ORDER BY date_taken IS NULL ASC, date_taken DESC, id DESC
1026                     LIMIT ?1",
1027                    cols = PHOTO_LITE_COLUMNS,
1028                    trash = trash_clause
1029                );
1030                let mut stmt = self.conn.prepare(&s)?;
1031                let mapped = stmt.query_map(params![limit], row_to_photo_lite)?;
1032                let mut v = Vec::new();
1033                for r in mapped {
1034                    v.push(r?);
1035                }
1036                (s, v)
1037            }
1038        };
1039        let _ = sql; // suppress unused if logging removed
1040        Ok(rows)
1041    }
1042
1043    /// Offset-addressed timeline window. Used only for fast jumps into
1044    /// very large timelines; cursor paging remains the normal path.
1045    pub fn list_at_offset(
1046        &self,
1047        offset: i64,
1048        limit: i64,
1049        include_trashed: bool,
1050        show_stacks: bool,
1051    ) -> SqliteResult<Vec<PhotoLite>> {
1052        if show_stacks && !include_trashed {
1053            return self.list_at_offset_stacked(offset, limit);
1054        }
1055        let trash_clause = if include_trashed {
1056            "1=1"
1057        } else {
1058            "is_trashed = 0"
1059        };
1060        let sql = format!(
1061            "SELECT {cols} FROM photos
1062             WHERE {trash}
1063             ORDER BY date_taken IS NULL ASC, date_taken DESC, id DESC
1064             LIMIT ?1 OFFSET ?2",
1065            cols = PHOTO_LITE_COLUMNS,
1066            trash = trash_clause
1067        );
1068        let mut stmt = self.conn.prepare(&sql)?;
1069        let rows = stmt
1070            .query_map(params![limit, offset], row_to_photo_lite)?
1071            .collect::<SqliteResult<Vec<_>>>()?;
1072        Ok(rows)
1073    }
1074
1075    fn list_after_stacked(
1076        &self,
1077        cursor: Option<(Option<DateTime<Utc>>, i64)>,
1078        limit: i64,
1079    ) -> SqliteResult<Vec<PhotoLite>> {
1080        let base = format!(
1081            r#"
1082            WITH live_stacks AS ({live_stacks_cte})
1083            SELECT {cols}
1084              FROM photos p
1085              LEFT JOIN photo_stack_members sm ON sm.photo_id = p.id
1086              LEFT JOIN live_stacks s ON s.id = sm.stack_id
1087             WHERE p.is_trashed = 0
1088               AND (s.id IS NULL OR p.id = s.cover_photo_id)
1089            "#,
1090            cols = PHOTO_LITE_STACKED_COLUMNS,
1091            live_stacks_cte = LIVE_STACKS_CTE
1092        );
1093        let group = " GROUP BY p.id, s.id";
1094
1095        match cursor {
1096            Some((Some(d), id)) => {
1097                let sql = format!(
1098                    "{base}
1099                     AND ((p.date_taken IS NOT NULL AND
1100                           (p.date_taken < ?1 OR (p.date_taken = ?1 AND p.id < ?2)))
1101                          OR (p.date_taken IS NULL AND ?1 IS NULL AND p.id < ?2))
1102                     {group}
1103                     ORDER BY p.date_taken IS NULL ASC, p.date_taken DESC, p.id DESC
1104                     LIMIT ?3"
1105                );
1106                let date_str = d.to_rfc3339();
1107                let mut stmt = self.conn.prepare(&sql)?;
1108                let rows = stmt.query_map(params![date_str, id, limit], row_to_photo_lite)?;
1109                rows.collect()
1110            }
1111            Some((None, id)) => {
1112                let sql = format!(
1113                    "{base}
1114                     AND p.date_taken IS NULL AND p.id < ?1
1115                     {group}
1116                     ORDER BY p.id DESC LIMIT ?2"
1117                );
1118                let mut stmt = self.conn.prepare(&sql)?;
1119                let rows = stmt.query_map(params![id, limit], row_to_photo_lite)?;
1120                rows.collect()
1121            }
1122            None => {
1123                let sql = format!(
1124                    "{base}
1125                     {group}
1126                     ORDER BY p.date_taken IS NULL ASC, p.date_taken DESC, p.id DESC
1127                     LIMIT ?1"
1128                );
1129                let mut stmt = self.conn.prepare(&sql)?;
1130                let rows = stmt.query_map(params![limit], row_to_photo_lite)?;
1131                rows.collect()
1132            }
1133        }
1134    }
1135
1136    fn list_at_offset_stacked(&self, offset: i64, limit: i64) -> SqliteResult<Vec<PhotoLite>> {
1137        let sql = format!(
1138            r#"
1139            WITH live_stacks AS ({live_stacks_cte})
1140            SELECT {cols}
1141              FROM photos p
1142              LEFT JOIN photo_stack_members sm ON sm.photo_id = p.id
1143              LEFT JOIN live_stacks s ON s.id = sm.stack_id
1144             WHERE p.is_trashed = 0
1145               AND (s.id IS NULL OR p.id = s.cover_photo_id)
1146             GROUP BY p.id, s.id
1147             ORDER BY p.date_taken IS NULL ASC, p.date_taken DESC, p.id DESC
1148             LIMIT ?1 OFFSET ?2
1149            "#,
1150            cols = PHOTO_LITE_STACKED_COLUMNS,
1151            live_stacks_cte = LIVE_STACKS_CTE
1152        );
1153        let mut stmt = self.conn.prepare(&sql)?;
1154        let rows = stmt
1155            .query_map(params![limit, offset], row_to_photo_lite)?
1156            .collect::<SqliteResult<Vec<_>>>()?;
1157        Ok(rows)
1158    }
1159
1160    pub fn timeline_neighbors(
1161        &self,
1162        photo_id: i64,
1163        show_stacks: bool,
1164    ) -> SqliteResult<Option<TimelineNeighbors>> {
1165        let Some(current) = self.get_by_id(photo_id)? else {
1166            return Ok(None);
1167        };
1168
1169        let visible = if show_stacks {
1170            "p.is_trashed = 0 AND NOT EXISTS (
1171                SELECT 1
1172                  FROM photo_stack_members sm
1173                  JOIN live_stacks s ON s.id = sm.stack_id
1174                 WHERE sm.photo_id = p.id
1175                   AND p.id <> s.cover_photo_id
1176            )"
1177        } else {
1178            "p.is_trashed = 0"
1179        };
1180
1181        let prev_id = if current.date_taken.is_some() {
1182            let sql = format!(
1183                "WITH live_stacks AS ({live_stacks_cte})
1184                 SELECT p.id FROM photos p
1185                 JOIN photos cur ON cur.id = ?1
1186                 WHERE {visible}
1187                   AND p.date_taken IS NOT NULL
1188                   AND p.id <> cur.id
1189                   AND (p.date_taken > cur.date_taken OR (p.date_taken = cur.date_taken AND p.id > cur.id))
1190                 ORDER BY p.date_taken ASC, p.id ASC
1191                 LIMIT 1",
1192                live_stacks_cte = LIVE_STACKS_CTE
1193            );
1194            self.conn
1195                .query_row(&sql, params![current.id], |r| r.get(0))
1196                .optional()?
1197        } else {
1198            let sql = format!(
1199                "WITH live_stacks AS ({live_stacks_cte})
1200                 SELECT p.id FROM photos p
1201                 WHERE {visible}
1202                   AND p.date_taken IS NULL
1203                   AND p.id > ?1
1204                 ORDER BY p.id ASC
1205                 LIMIT 1",
1206                live_stacks_cte = LIVE_STACKS_CTE
1207            );
1208            let null_prev: Option<i64> = self
1209                .conn
1210                .query_row(&sql, params![current.id], |r| r.get(0))
1211                .optional()?;
1212            if null_prev.is_some() {
1213                null_prev
1214            } else {
1215                let sql = format!(
1216                    "WITH live_stacks AS ({live_stacks_cte})
1217                     SELECT p.id FROM photos p
1218                     WHERE {visible}
1219                       AND p.date_taken IS NOT NULL
1220                     ORDER BY p.date_taken ASC, p.id ASC
1221                     LIMIT 1",
1222                    live_stacks_cte = LIVE_STACKS_CTE
1223                );
1224                self.conn.query_row(&sql, [], |r| r.get(0)).optional()?
1225            }
1226        };
1227
1228        let next_id = if current.date_taken.is_some() {
1229            let sql = format!(
1230                "WITH live_stacks AS ({live_stacks_cte})
1231                 SELECT p.id FROM photos p
1232                 JOIN photos cur ON cur.id = ?1
1233                 WHERE {visible}
1234                   AND (
1235                        (p.date_taken IS NOT NULL
1236                         AND (p.date_taken < cur.date_taken OR (p.date_taken = cur.date_taken AND p.id < cur.id)))
1237                        OR p.date_taken IS NULL
1238                   )
1239                 ORDER BY p.date_taken IS NULL ASC, p.date_taken DESC, p.id DESC
1240                 LIMIT 1",
1241                live_stacks_cte = LIVE_STACKS_CTE
1242            );
1243            self.conn
1244                .query_row(&sql, params![current.id], |r| r.get(0))
1245                .optional()?
1246        } else {
1247            let sql = format!(
1248                "WITH live_stacks AS ({live_stacks_cte})
1249                 SELECT p.id FROM photos p
1250                 WHERE {visible}
1251                   AND p.date_taken IS NULL
1252                   AND p.id < ?1
1253                 ORDER BY p.id DESC
1254                 LIMIT 1",
1255                live_stacks_cte = LIVE_STACKS_CTE
1256            );
1257            self.conn
1258                .query_row(&sql, params![current.id], |r| r.get(0))
1259                .optional()?
1260        };
1261
1262        Ok(Some(TimelineNeighbors { prev_id, next_id }))
1263    }
1264
1265    /// Cursor-paginated photos in a specific album, ordered by date.
1266    pub fn list_after_by_album(
1267        &self,
1268        album_id: i64,
1269        cursor: Option<(Option<DateTime<Utc>>, i64)>,
1270        limit: i64,
1271    ) -> SqliteResult<Vec<PhotoLite>> {
1272        let base = format!(
1273            "SELECT {cols} FROM photos p
1274             JOIN album_photos ap ON ap.photo_id = p.id
1275             WHERE ap.album_id = ?1 AND p.is_trashed = 0",
1276            cols = PHOTO_LITE_P_COLUMNS
1277        );
1278
1279        match cursor {
1280            Some((Some(d), id)) => {
1281                let sql = format!(
1282                    "{base}
1283                     AND ((p.date_taken IS NOT NULL AND
1284                           (p.date_taken < ?2 OR (p.date_taken = ?2 AND p.id < ?3)))
1285                          OR (p.date_taken IS NULL AND ?2 IS NULL AND p.id < ?3))
1286                     ORDER BY p.date_taken IS NULL ASC, p.date_taken DESC, p.id DESC
1287                     LIMIT ?4"
1288                );
1289                let date_str = d.to_rfc3339();
1290                let mut stmt = self.conn.prepare(&sql)?;
1291                let rows = stmt
1292                    .query_map(params![album_id, date_str, id, limit], row_to_photo_lite)?
1293                    .collect::<SqliteResult<Vec<_>>>()?;
1294                Ok(rows)
1295            }
1296            Some((None, id)) => {
1297                let sql = format!(
1298                    "{base} AND p.date_taken IS NULL AND p.id < ?2
1299                     ORDER BY p.id DESC LIMIT ?3"
1300                );
1301                let mut stmt = self.conn.prepare(&sql)?;
1302                let rows = stmt
1303                    .query_map(params![album_id, id, limit], row_to_photo_lite)?
1304                    .collect::<SqliteResult<Vec<_>>>()?;
1305                Ok(rows)
1306            }
1307            None => {
1308                let sql = format!(
1309                    "{base}
1310                     ORDER BY p.date_taken IS NULL ASC, p.date_taken DESC, p.id DESC
1311                     LIMIT ?2"
1312                );
1313                let mut stmt = self.conn.prepare(&sql)?;
1314                let rows = stmt
1315                    .query_map(params![album_id, limit], row_to_photo_lite)?
1316                    .collect::<SqliteResult<Vec<_>>>()?;
1317                Ok(rows)
1318            }
1319        }
1320    }
1321
1322    /// Cursor-paginated favorite photos. This backs the virtual
1323    /// Favorites album without writing synthetic rows to `albums`.
1324    pub fn list_after_favorites(
1325        &self,
1326        cursor: Option<(Option<DateTime<Utc>>, i64)>,
1327        limit: i64,
1328    ) -> SqliteResult<Vec<PhotoLite>> {
1329        let base = format!(
1330            "SELECT {cols} FROM photos
1331             WHERE is_favorite = TRUE AND is_trashed = 0",
1332            cols = PHOTO_LITE_COLUMNS
1333        );
1334
1335        match cursor {
1336            Some((Some(d), id)) => {
1337                let sql = format!(
1338                    "{base}
1339                     AND ((date_taken IS NOT NULL AND
1340                           (date_taken < ?1 OR (date_taken = ?1 AND id < ?2)))
1341                          OR (date_taken IS NULL AND ?1 IS NULL AND id < ?2))
1342                     ORDER BY date_taken IS NULL ASC, date_taken DESC, id DESC
1343                     LIMIT ?3"
1344                );
1345                let date_str = d.to_rfc3339();
1346                let mut stmt = self.conn.prepare(&sql)?;
1347                let rows = stmt
1348                    .query_map(params![date_str, id, limit], row_to_photo_lite)?
1349                    .collect::<SqliteResult<Vec<_>>>()?;
1350                Ok(rows)
1351            }
1352            Some((None, id)) => {
1353                let sql = format!(
1354                    "{base} AND date_taken IS NULL AND id < ?1
1355                     ORDER BY id DESC LIMIT ?2"
1356                );
1357                let mut stmt = self.conn.prepare(&sql)?;
1358                let rows = stmt
1359                    .query_map(params![id, limit], row_to_photo_lite)?
1360                    .collect::<SqliteResult<Vec<_>>>()?;
1361                Ok(rows)
1362            }
1363            None => {
1364                let sql = format!(
1365                    "{base}
1366                     ORDER BY date_taken IS NULL ASC, date_taken DESC, id DESC
1367                     LIMIT ?1"
1368                );
1369                let mut stmt = self.conn.prepare(&sql)?;
1370                let rows = stmt
1371                    .query_map(params![limit], row_to_photo_lite)?
1372                    .collect::<SqliteResult<Vec<_>>>()?;
1373                Ok(rows)
1374            }
1375        }
1376    }
1377
1378    /// Cursor-paginated photos featuring a person (face cluster).
1379    pub fn list_after_by_person(
1380        &self,
1381        cluster_id: i64,
1382        cursor: Option<(Option<DateTime<Utc>>, i64)>,
1383        limit: i64,
1384    ) -> SqliteResult<Vec<PhotoLite>> {
1385        let base = format!(
1386            "SELECT DISTINCT {cols} FROM photos p
1387             JOIN (
1388                 SELECT photo_id FROM faces WHERE cluster_id = ?1
1389                 UNION
1390                 SELECT photo_id FROM photo_inferred_identities WHERE cluster_id = ?1
1391             ) matches ON matches.photo_id = p.id
1392             WHERE p.is_trashed = 0",
1393            cols = PHOTO_LITE_P_COLUMNS
1394        );
1395
1396        match cursor {
1397            Some((Some(d), id)) => {
1398                let sql = format!(
1399                    "{base}
1400                     AND ((p.date_taken IS NOT NULL AND
1401                           (p.date_taken < ?2 OR (p.date_taken = ?2 AND p.id < ?3)))
1402                          OR (p.date_taken IS NULL AND ?2 IS NULL AND p.id < ?3))
1403                     ORDER BY p.date_taken IS NULL ASC, p.date_taken DESC, p.id DESC
1404                     LIMIT ?4"
1405                );
1406                let date_str = d.to_rfc3339();
1407                let mut stmt = self.conn.prepare(&sql)?;
1408                let rows = stmt
1409                    .query_map(params![cluster_id, date_str, id, limit], row_to_photo_lite)?
1410                    .collect::<SqliteResult<Vec<_>>>()?;
1411                Ok(rows)
1412            }
1413            Some((None, id)) => {
1414                let sql = format!(
1415                    "{base} AND p.date_taken IS NULL AND p.id < ?2
1416                     ORDER BY p.id DESC LIMIT ?3"
1417                );
1418                let mut stmt = self.conn.prepare(&sql)?;
1419                let rows = stmt
1420                    .query_map(params![cluster_id, id, limit], row_to_photo_lite)?
1421                    .collect::<SqliteResult<Vec<_>>>()?;
1422                Ok(rows)
1423            }
1424            None => {
1425                let sql = format!(
1426                    "{base}
1427                     ORDER BY p.date_taken IS NULL ASC, p.date_taken DESC, p.id DESC
1428                     LIMIT ?2"
1429                );
1430                let mut stmt = self.conn.prepare(&sql)?;
1431                let rows = stmt
1432                    .query_map(params![cluster_id, limit], row_to_photo_lite)?
1433                    .collect::<SqliteResult<Vec<_>>>()?;
1434                Ok(rows)
1435            }
1436        }
1437    }
1438
1439    /// Cursor-paginated photos in a half-open date range: [start, end).
1440    pub fn list_after_by_date(
1441        &self,
1442        start_iso: &str,
1443        end_iso: &str,
1444        cursor: Option<(Option<DateTime<Utc>>, i64)>,
1445        limit: i64,
1446    ) -> SqliteResult<Vec<PhotoLite>> {
1447        let base = format!(
1448            "SELECT {cols} FROM photos
1449             WHERE is_trashed = 0
1450               AND date_taken IS NOT NULL
1451               AND date_taken >= ?1 AND date_taken < ?2",
1452            cols = PHOTO_LITE_COLUMNS
1453        );
1454        match cursor {
1455            Some((Some(d), id)) => {
1456                let sql = format!(
1457                    "{base}
1458                     AND (date_taken < ?3 OR (date_taken = ?3 AND id < ?4))
1459                     ORDER BY date_taken DESC, id DESC LIMIT ?5"
1460                );
1461                let date_str = d.to_rfc3339();
1462                let mut stmt = self.conn.prepare(&sql)?;
1463                let rows = stmt
1464                    .query_map(
1465                        params![start_iso, end_iso, date_str, id, limit],
1466                        row_to_photo_lite,
1467                    )?
1468                    .collect::<SqliteResult<Vec<_>>>()?;
1469                Ok(rows)
1470            }
1471            Some((None, _)) | None => {
1472                let sql = format!(
1473                    "{base}
1474                     ORDER BY date_taken DESC, id DESC LIMIT ?3"
1475                );
1476                let mut stmt = self.conn.prepare(&sql)?;
1477                let rows = stmt
1478                    .query_map(params![start_iso, end_iso, limit], row_to_photo_lite)?
1479                    .collect::<SqliteResult<Vec<_>>>()?;
1480                Ok(rows)
1481            }
1482        }
1483    }
1484
1485    /// Photos within a lat/lng bounding box that have GPS coordinates.
1486    /// Used by `map.pins` for server-side aggregation.
1487    ///
1488    /// Bounds are inclusive on all sides. Returns a hard cap of `cap` rows.
1489    pub fn list_in_bounds(
1490        &self,
1491        north: f64,
1492        south: f64,
1493        east: f64,
1494        west: f64,
1495        cap: i64,
1496    ) -> SqliteResult<Vec<PhotoLite>> {
1497        // Handle the antimeridian-crossing case (west > east) by splitting.
1498        let lng_clause = if west <= east {
1499            "gps_longitude >= ?3 AND gps_longitude <= ?4"
1500        } else {
1501            "(gps_longitude >= ?3 OR gps_longitude <= ?4)"
1502        };
1503        let sql = format!(
1504            "SELECT {cols} FROM photos
1505             WHERE is_trashed = 0
1506               AND gps_latitude IS NOT NULL
1507               AND gps_longitude IS NOT NULL
1508               AND gps_latitude >= ?2 AND gps_latitude <= ?1
1509               AND {lng}
1510             ORDER BY date_taken IS NULL ASC, date_taken DESC, id DESC
1511             LIMIT ?5",
1512            cols = PHOTO_LITE_COLUMNS,
1513            lng = lng_clause,
1514        );
1515        let mut stmt = self.conn.prepare(&sql)?;
1516        let rows = stmt
1517            .query_map(params![north, south, west, east, cap], row_to_photo_lite)?
1518            .collect::<SqliteResult<Vec<_>>>()?;
1519        Ok(rows)
1520    }
1521}