Skip to main content

smriti/db/
migrations.rs

1//! Database migrations for schema versioning
2
3use rusqlite::{Connection, Result as SqliteResult};
4
5/// The highest schema version this binary knows how to produce. Bump
6/// this in lockstep with each new `migrate_vN_to_vM` (and add the
7/// matching `if current_version < N` line in `run_migrations`).
8///
9/// `run_migrations` refuses to open a DB whose `schema_version` is
10/// higher than this — that would mean a newer build wrote it, and
11/// blindly reading would expose missing tables / columns to old code.
12pub const MAX_KNOWN_SCHEMA_VERSION: i32 = 33;
13
14/// Get the current schema version
15pub fn get_schema_version(conn: &Connection) -> SqliteResult<i32> {
16    let result = conn.query_row("SELECT MAX(version) FROM schema_version", [], |row| {
17        row.get(0)
18    });
19
20    match result {
21        Ok(version) => Ok(version),
22        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(0),
23        Err(e) => Err(e),
24    }
25}
26
27/// Distinct error returned by `run_migrations` when the DB is newer
28/// than this binary supports. Surfaced to the user with a friendlier
29/// message than a generic SQLite error.
30#[derive(Debug)]
31pub struct SchemaTooNewError {
32    pub db_version: i32,
33    pub max_supported: i32,
34}
35
36impl std::fmt::Display for SchemaTooNewError {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        write!(
39            f,
40            "Library was created by a newer version of Smriti \
41             (schema v{}). This build only supports up to v{}. \
42             Please update Smriti to open this library.",
43            self.db_version, self.max_supported
44        )
45    }
46}
47
48impl std::error::Error for SchemaTooNewError {}
49
50/// Run any pending migrations
51pub fn run_migrations(conn: &Connection) -> Result<(), Box<dyn std::error::Error>> {
52    let current_version = get_schema_version(conn).unwrap_or(0);
53
54    // Forward-compat guard: don't read schemas this binary doesn't
55    // know about. Better to refuse opening than to silently
56    // mis-interpret unfamiliar columns or miss new tables.
57    if current_version > MAX_KNOWN_SCHEMA_VERSION {
58        return Err(Box::new(SchemaTooNewError {
59            db_version: current_version,
60            max_supported: MAX_KNOWN_SCHEMA_VERSION,
61        }));
62    }
63
64    if current_version < 2 {
65        migrate_v1_to_v2(conn)?;
66    }
67    if current_version < 3 {
68        migrate_v2_to_v3(conn)?;
69    }
70    if current_version < 4 {
71        migrate_v3_to_v4(conn)?;
72    }
73    if current_version < 5 {
74        migrate_v4_to_v5(conn)?;
75    }
76    if current_version < 6 {
77        migrate_v5_to_v6(conn)?;
78    }
79    if current_version < 7 {
80        migrate_v6_to_v7(conn)?;
81    }
82    if current_version < 8 {
83        migrate_v7_to_v8(conn)?;
84    }
85    if current_version < 9 {
86        migrate_v8_to_v9(conn)?;
87    }
88    if current_version < 10 {
89        migrate_v9_to_v10(conn)?;
90    }
91    if current_version < 11 {
92        migrate_v10_to_v11(conn)?;
93    }
94    if current_version < 12 {
95        migrate_v11_to_v12(conn)?;
96    }
97    if current_version < 13 {
98        migrate_v12_to_v13(conn)?;
99    }
100    if current_version < 14 {
101        migrate_v13_to_v14(conn)?;
102    }
103    if current_version < 15 {
104        migrate_v14_to_v15(conn)?;
105    }
106    if current_version < 16 {
107        migrate_v15_to_v16(conn)?;
108    }
109    if current_version < 17 {
110        migrate_v16_to_v17(conn)?;
111    }
112    if current_version < 18 {
113        migrate_v17_to_v18(conn)?;
114    }
115    if current_version < 19 {
116        migrate_v18_to_v19(conn)?;
117    }
118    if current_version < 20 {
119        migrate_v19_to_v20(conn)?;
120    }
121    if current_version < 21 {
122        migrate_v20_to_v21(conn)?;
123    }
124    if current_version < 22 {
125        migrate_v21_to_v22(conn)?;
126    }
127    if current_version < 23 {
128        migrate_v22_to_v23(conn)?;
129    }
130    if current_version < 24 {
131        migrate_v23_to_v24(conn)?;
132    }
133    if current_version < 25 {
134        migrate_v24_to_v25(conn)?;
135    }
136    if current_version < 26 {
137        migrate_v25_to_v26(conn)?;
138    }
139    if current_version < 27 {
140        migrate_v26_to_v27(conn)?;
141    }
142    if current_version < 28 {
143        migrate_v27_to_v28(conn)?;
144    }
145    if current_version < 29 {
146        migrate_v28_to_v29(conn)?;
147    }
148    if current_version < 30 {
149        let tx = conn.unchecked_transaction()?;
150        tx.execute_batch(super::schema::SEMANTIC_REVISION_SQL)?;
151        tx.execute("INSERT INTO schema_version(version) VALUES (30)", [])?;
152        tx.commit()?;
153    }
154    if current_version < 31 {
155        migrate_v30_to_v31(conn)?;
156    }
157    if current_version < 32 {
158        migrate_v31_to_v32(conn)?;
159    }
160    if current_version < 33 {
161        migrate_v32_to_v33(conn)?;
162    }
163    ensure_performance_indexes(conn)?;
164    let updated_version = get_schema_version(conn).unwrap_or(current_version);
165    tracing::info!("Database at schema version {}", updated_version);
166    Ok(())
167}
168
169/// v33: count failed face-detection runs per photo, so a transient failure
170/// (unplugged drive, missing decoder) is retried instead of being recorded
171/// forever as "no faces".
172fn migrate_v32_to_v33(conn: &Connection) -> SqliteResult<()> {
173    let tx = conn.unchecked_transaction()?;
174    let exists = tx
175        .prepare("SELECT 1 FROM pragma_table_info('photos') WHERE name = 'face_attempts'")?
176        .exists([])?;
177    if !exists {
178        tx.execute_batch(
179            "ALTER TABLE photos ADD COLUMN face_attempts INTEGER NOT NULL DEFAULT 0;",
180        )?;
181    }
182    tx.execute("INSERT INTO schema_version (version) VALUES (33)", [])?;
183    tx.commit()?;
184    tracing::info!("Migrated database to schema version 33 (face detection attempts)");
185    Ok(())
186}
187
188fn migrate_v31_to_v32(conn: &Connection) -> SqliteResult<()> {
189    let tx = conn.unchecked_transaction()?;
190    tx.execute_batch(
191        r#"
192        DROP TRIGGER IF EXISTS photos_fts_insert;
193        DROP TRIGGER IF EXISTS photos_fts_update;
194        DROP TRIGGER IF EXISTS photos_fts_delete;
195        DROP TABLE IF EXISTS photos_fts;
196        DROP INDEX IF EXISTS idx_photos_content_category;
197        DROP INDEX IF EXISTS idx_photos_ocr_processed;
198        "#,
199    )?;
200    for column in [
201        "content_category",
202        "ocr_text",
203        "ocr_processed",
204        "ocr_confidence",
205    ] {
206        let exists = tx
207            .prepare("SELECT 1 FROM pragma_table_info('photos') WHERE name = ?1")?
208            .exists([column])?;
209        if exists {
210            tx.execute_batch(&format!("ALTER TABLE photos DROP COLUMN {column};"))?;
211        }
212    }
213    tx.execute("INSERT INTO schema_version (version) VALUES (32)", [])?;
214    tx.commit()?;
215    tracing::info!("Migrated database to schema version 32 (removed unused OCR state)");
216    Ok(())
217}
218
219fn migrate_v30_to_v31(conn: &Connection) -> SqliteResult<()> {
220    let tx = conn.unchecked_transaction()?;
221    // SQLite has no ADD COLUMN IF NOT EXISTS; guard the ALTER so the
222    // migration also tolerates databases whose photos table was created
223    // by a create_schema that already carries the column (tests).
224    let has_content_hash = tx
225        .prepare("SELECT 1 FROM pragma_table_info('photos') WHERE name = 'content_hash'")?
226        .exists([])?;
227    if !has_content_hash {
228        tx.execute_batch("ALTER TABLE photos ADD COLUMN content_hash TEXT;")?;
229    }
230    tx.execute_batch(
231        r#"
232        -- Small key/value store for library-level bookkeeping (e.g. the
233        -- thumbnail-repair cursor).
234        CREATE TABLE IF NOT EXISTS library_meta (
235            key TEXT PRIMARY KEY,
236            value TEXT NOT NULL
237        );
238
239        INSERT INTO schema_version (version) VALUES (31);
240        "#,
241    )?;
242    tx.commit()?;
243    tracing::info!("Migrated database to schema version 31 (content hash cache, library_meta)");
244    Ok(())
245}
246
247fn migrate_v28_to_v29(conn: &Connection) -> SqliteResult<()> {
248    conn.execute("INSERT INTO schema_version(version) VALUES (29)", [])?;
249    Ok(())
250}
251
252fn migrate_v27_to_v28(conn: &Connection) -> SqliteResult<()> {
253    let tx = conn.unchecked_transaction()?;
254    tx.execute_batch(
255        r#"
256        CREATE TABLE IF NOT EXISTS google_takeout_items (
257            content_hash TEXT PRIMARY KEY,
258            file_path TEXT NOT NULL UNIQUE,
259            metadata_json TEXT,
260            imported_at DATETIME DEFAULT CURRENT_TIMESTAMP,
261            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
262        );
263
264        CREATE TABLE IF NOT EXISTS google_takeout_albums (
265            content_hash TEXT NOT NULL,
266            album_name TEXT NOT NULL,
267            PRIMARY KEY (content_hash, album_name),
268            FOREIGN KEY (content_hash) REFERENCES google_takeout_items(content_hash)
269                ON DELETE CASCADE
270        );
271
272        CREATE INDEX IF NOT EXISTS idx_google_takeout_items_path
273            ON google_takeout_items(file_path);
274
275        INSERT INTO schema_version (version) VALUES (28);
276        "#,
277    )?;
278    tx.commit()?;
279    tracing::info!("Migrated database to schema version 28 (Google Takeout imports)");
280    Ok(())
281}
282
283/// Add the indexes the hot queries depend on.
284///
285/// Each statement runs independently and a failure is logged rather than
286/// propagated. These are performance hints, not correctness requirements, and
287/// they reference columns introduced by different migrations — so on a catalog
288/// that predates one of those columns, `execute_batch` would stop at the first
289/// failing statement and silently skip every index after it. Running them
290/// separately means one unavailable column cannot cost us the other indexes,
291/// and cannot fail an open.
292fn ensure_performance_indexes(conn: &Connection) -> SqliteResult<()> {
293    const INDEXES: &[(&str, &str)] = &[
294        (
295            "idx_photos_hash_trashed",
296            "CREATE INDEX IF NOT EXISTS idx_photos_hash_trashed ON photos(file_hash, is_trashed)",
297        ),
298        (
299            "idx_photos_timeline_order",
300            "CREATE INDEX IF NOT EXISTS idx_photos_timeline_order
301                ON photos(is_trashed, (date_taken IS NULL), date_taken DESC, id DESC)",
302        ),
303        (
304            "idx_photos_content_hash",
305            "CREATE INDEX IF NOT EXISTS idx_photos_content_hash
306                ON photos(content_hash) WHERE content_hash IS NOT NULL",
307        ),
308        (
309            "idx_photos_file_size",
310            "CREATE INDEX IF NOT EXISTS idx_photos_file_size ON photos(file_size)",
311        ),
312        (
313            "idx_photos_favorite_order",
314            "CREATE INDEX IF NOT EXISTS idx_photos_favorite_order
315                ON photos(is_favorite, is_trashed, (date_taken IS NULL), date_taken DESC, id DESC)
316                WHERE is_favorite = TRUE",
317        ),
318        (
319            "idx_photos_gps_bounds",
320            "CREATE INDEX IF NOT EXISTS idx_photos_gps_bounds
321                ON photos(is_trashed, gps_latitude, gps_longitude)
322                WHERE gps_latitude IS NOT NULL AND gps_longitude IS NOT NULL",
323        ),
324        // Place filters for search. `resolve_countries` and `resolve_cities`
325        // both aggregate the location columns over every non-trashed row, and
326        // ran on every search *and every page* of one. The pre-existing
327        // idx_photos_location(country, city) cannot serve them because
328        // is_trashed is not a prefix column. This is a covering index: both
329        // statements read location columns and is_trashed and nothing else.
330        // Stored as a normal (not partial) index so a future reader that omits
331        // the IS NOT NULL guard still uses it.
332        (
333            "idx_photos_place",
334            "CREATE INDEX IF NOT EXISTS idx_photos_place
335                ON photos(is_trashed, location_country, location_city)",
336        ),
337        (
338            "idx_faces_review_pending",
339            "CREATE INDEX IF NOT EXISTS idx_faces_review_pending
340                ON faces(user_confirmed, cluster_id, id)
341                WHERE user_confirmed = 0 AND cluster_id IS NOT NULL",
342        ),
343    ];
344
345    for (name, sql) in INDEXES {
346        if let Err(error) = conn.execute(sql, []) {
347            tracing::debug!("performance index {name} not created: {error}");
348        }
349    }
350    Ok(())
351}
352
353fn migrate_v26_to_v27(conn: &Connection) -> SqliteResult<()> {
354    let tx = conn.unchecked_transaction()?;
355    tx.execute_batch(
356        r#"
357        CREATE TABLE IF NOT EXISTS albums (
358            id INTEGER PRIMARY KEY,
359            name TEXT NOT NULL,
360            cover_photo_id INTEGER,
361            cover_auto_picked BOOLEAN DEFAULT TRUE,
362            photo_count INTEGER DEFAULT 0,
363            created_by TEXT NOT NULL DEFAULT 'user' CHECK(created_by IN ('user', 'agent')),
364            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
365            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
366            FOREIGN KEY (cover_photo_id) REFERENCES photos(id) ON DELETE SET NULL
367        );
368
369        CREATE TABLE IF NOT EXISTS album_photos (
370            id INTEGER PRIMARY KEY,
371            album_id INTEGER NOT NULL,
372            photo_id INTEGER NOT NULL,
373            added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
374            FOREIGN KEY (album_id) REFERENCES albums(id) ON DELETE CASCADE,
375            FOREIGN KEY (photo_id) REFERENCES photos(id) ON DELETE CASCADE,
376            UNIQUE(album_id, photo_id)
377        );
378
379        CREATE INDEX IF NOT EXISTS idx_album_photos_album ON album_photos(album_id);
380        CREATE INDEX IF NOT EXISTS idx_album_photos_photo ON album_photos(photo_id);
381        "#,
382    )?;
383    match tx.execute(
384        "ALTER TABLE albums ADD COLUMN created_by TEXT NOT NULL DEFAULT 'user' CHECK(created_by IN ('user', 'agent'))",
385        [],
386    ) {
387        Ok(_) => {}
388        Err(e) => {
389            let msg = e.to_string();
390            if !msg.contains("duplicate column") {
391                return Err(e);
392            }
393        }
394    }
395    tx.execute("INSERT INTO schema_version (version) VALUES (27)", [])?;
396    tx.commit()?;
397    tracing::info!("Migrated database to schema version 27 (album provenance)");
398    Ok(())
399}
400
401fn migrate_v25_to_v26(conn: &Connection) -> SqliteResult<()> {
402    let tx = conn.unchecked_transaction()?;
403    tx.execute_batch(
404        r#"
405        CREATE TABLE IF NOT EXISTS semantic_index_state (
406            photo_id INTEGER NOT NULL,
407            model_key TEXT NOT NULL,
408            status TEXT NOT NULL DEFAULT 'pending'
409                CHECK(status IN ('pending', 'indexed', 'failed', 'unsupported')),
410            vector_offset INTEGER,
411            vector_dim INTEGER,
412            attempts INTEGER NOT NULL DEFAULT 0,
413            last_error TEXT,
414            indexed_at DATETIME,
415            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
416            PRIMARY KEY (photo_id, model_key),
417            FOREIGN KEY (photo_id) REFERENCES photos(id) ON DELETE CASCADE
418        );
419
420        CREATE INDEX IF NOT EXISTS idx_semantic_state_status
421            ON semantic_index_state(model_key, status);
422        CREATE INDEX IF NOT EXISTS idx_semantic_state_photo
423            ON semantic_index_state(photo_id);
424
425        INSERT INTO schema_version (version) VALUES (26);
426        "#,
427    )?;
428    tx.commit()?;
429    tracing::info!("Migrated database to schema version 26 (semantic search)");
430    Ok(())
431}
432
433fn migrate_v24_to_v25(conn: &Connection) -> SqliteResult<()> {
434    let tx = conn.unchecked_transaction()?;
435    tx.execute_batch(
436        r#"
437        CREATE TABLE IF NOT EXISTS excluded_folders (
438            relative_path TEXT PRIMARY KEY,
439            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
440        );
441
442        INSERT INTO schema_version (version) VALUES (25);
443        "#,
444    )?;
445    tx.commit()?;
446    tracing::info!("Migrated database to schema version 25 (excluded folders)");
447    Ok(())
448}
449
450fn migrate_v23_to_v24(conn: &Connection) -> SqliteResult<()> {
451    let tx = conn.unchecked_transaction()?;
452    match tx.execute(
453        "ALTER TABLE photos ADD COLUMN is_favorite BOOLEAN DEFAULT FALSE",
454        [],
455    ) {
456        Ok(_) => {}
457        Err(e) => {
458            let msg = e.to_string();
459            if !msg.contains("duplicate column") {
460                return Err(e);
461            }
462        }
463    }
464    tx.execute(
465        "CREATE INDEX IF NOT EXISTS idx_photos_favorite ON photos(is_favorite, date_taken DESC) WHERE is_favorite = TRUE",
466        [],
467    )?;
468    tx.execute("INSERT INTO schema_version (version) VALUES (24)", [])?;
469    tx.commit()?;
470    tracing::info!("Migrated database to schema version 24 (favorites smart album)");
471    Ok(())
472}
473
474fn migrate_v22_to_v23(conn: &Connection) -> SqliteResult<()> {
475    let tx = conn.unchecked_transaction()?;
476    for (col, def) in &[
477        ("media_type", "TEXT NOT NULL DEFAULT 'photo'"),
478        ("duration_ms", "INTEGER"),
479        ("video_codec", "TEXT"),
480        ("audio_codec", "TEXT"),
481        ("frame_rate", "REAL"),
482        ("bitrate", "INTEGER"),
483        ("has_audio", "BOOLEAN DEFAULT FALSE"),
484    ] {
485        let sql = format!("ALTER TABLE photos ADD COLUMN {} {}", col, def);
486        match tx.execute(&sql, []) {
487            Ok(_) => {}
488            Err(e) => {
489                let msg = e.to_string();
490                if !msg.contains("duplicate column") {
491                    return Err(e);
492                }
493            }
494        }
495    }
496    tx.execute(
497        "CREATE INDEX IF NOT EXISTS idx_photos_media_type ON photos(media_type)",
498        [],
499    )?;
500    tx.execute("INSERT INTO schema_version (version) VALUES (23)", [])?;
501    tx.commit()?;
502    tracing::info!("Migrated database to schema version 23 (video media metadata)");
503    Ok(())
504}
505
506fn migrate_v21_to_v22(conn: &Connection) -> SqliteResult<()> {
507    let tx = conn.unchecked_transaction()?;
508    tx.execute_batch(
509        r#"
510        CREATE TABLE IF NOT EXISTS photo_stacks (
511            id INTEGER PRIMARY KEY,
512            kind TEXT NOT NULL,
513            source_group_id INTEGER NOT NULL,
514            source_group_hash TEXT,
515            cover_photo_id INTEGER NOT NULL,
516            confidence REAL NOT NULL DEFAULT 1.0,
517            dismissed BOOLEAN DEFAULT FALSE,
518            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
519            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
520            UNIQUE(kind, source_group_id)
521        );
522
523        CREATE TABLE IF NOT EXISTS photo_stack_members (
524            id INTEGER PRIMARY KEY,
525            stack_id INTEGER NOT NULL,
526            photo_id INTEGER NOT NULL,
527            quality_score REAL NOT NULL DEFAULT 0,
528            score_reasons TEXT,
529            is_cover BOOLEAN DEFAULT FALSE,
530            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
531            FOREIGN KEY (stack_id) REFERENCES photo_stacks(id) ON DELETE CASCADE,
532            FOREIGN KEY (photo_id) REFERENCES photos(id) ON DELETE CASCADE,
533            UNIQUE(stack_id, photo_id)
534        );
535
536        CREATE INDEX IF NOT EXISTS idx_photo_stacks_cover ON photo_stacks(cover_photo_id);
537        CREATE INDEX IF NOT EXISTS idx_photo_stacks_active ON photo_stacks(dismissed, kind);
538        CREATE INDEX IF NOT EXISTS idx_photo_stack_members_stack ON photo_stack_members(stack_id);
539        CREATE INDEX IF NOT EXISTS idx_photo_stack_members_photo ON photo_stack_members(photo_id);
540        CREATE INDEX IF NOT EXISTS idx_photo_stack_members_cover ON photo_stack_members(stack_id, is_cover);
541        "#,
542    )?;
543    tx.execute("INSERT INTO schema_version (version) VALUES (22)", [])?;
544    tx.commit()?;
545    tracing::info!("Migrated database to schema version 22 (timeline photo stacks)");
546    Ok(())
547}
548
549fn migrate_v18_to_v19(conn: &Connection) -> SqliteResult<()> {
550    // Streaming scanner pipeline stage flags.
551    // Existing rows: anything inserted by the legacy scanner already
552    // has EXIF and (if successful) a thumbnail. Mark them done so the
553    // new workers don't re-process them.
554    let tx = conn.unchecked_transaction()?;
555    for (col, def) in &[
556        ("metadata_extracted", "BOOLEAN DEFAULT FALSE"),
557        ("thumbnailed", "BOOLEAN DEFAULT FALSE"),
558    ] {
559        let sql = format!("ALTER TABLE photos ADD COLUMN {} {}", col, def);
560        match tx.execute(&sql, []) {
561            Ok(_) => {}
562            Err(e) => {
563                let msg = e.to_string();
564                if !msg.contains("duplicate column") {
565                    return Err(e);
566                }
567            }
568        }
569    }
570    tx.execute(
571        "UPDATE photos SET metadata_extracted = TRUE WHERE date_taken IS NOT NULL OR camera_make IS NOT NULL",
572        [],
573    )?;
574    tx.execute(
575        "UPDATE photos SET thumbnailed = TRUE WHERE thumbnail_path IS NOT NULL",
576        [],
577    )?;
578    tx.execute(
579        "CREATE INDEX IF NOT EXISTS idx_photos_metadata_extracted ON photos(metadata_extracted) WHERE metadata_extracted = FALSE",
580        [],
581    )?;
582    tx.execute(
583        "CREATE INDEX IF NOT EXISTS idx_photos_thumbnailed ON photos(thumbnailed) WHERE thumbnailed = FALSE",
584        [],
585    )?;
586    tx.execute("INSERT INTO schema_version (version) VALUES (19)", [])?;
587    tx.commit()?;
588    tracing::info!("Migrated database to schema version 19 (scanner pipeline stages)");
589    Ok(())
590}
591
592fn migrate_v19_to_v20(conn: &Connection) -> SqliteResult<()> {
593    let tx = conn.unchecked_transaction()?;
594    tx.execute_batch(
595        r#"
596        CREATE TABLE IF NOT EXISTS face_negatives (
597            face_id        INTEGER NOT NULL,
598            not_cluster_id INTEGER NOT NULL,
599            created_at     INTEGER NOT NULL DEFAULT (strftime('%s','now')),
600            PRIMARY KEY (face_id, not_cluster_id),
601            FOREIGN KEY (face_id)        REFERENCES faces(id)         ON DELETE CASCADE,
602            FOREIGN KEY (not_cluster_id) REFERENCES face_clusters(id) ON DELETE CASCADE
603        );
604        CREATE INDEX IF NOT EXISTS idx_face_negatives_cluster ON face_negatives(not_cluster_id);
605        INSERT INTO schema_version (version) VALUES (20);
606        "#,
607    )?;
608    tx.commit()?;
609    tracing::info!("Migrated database to schema version 20 (face_negatives)");
610    Ok(())
611}
612
613fn migrate_v20_to_v21(conn: &Connection) -> SqliteResult<()> {
614    let tx = conn.unchecked_transaction()?;
615    tx.execute_batch(
616        r#"
617        CREATE TABLE IF NOT EXISTS face_processing_stats (
618            id                INTEGER PRIMARY KEY CHECK (id = 1),
619            rejected_small    INTEGER NOT NULL DEFAULT 0,
620            rejected_lowconf  INTEGER NOT NULL DEFAULT 0,
621            rejected_blurry   INTEGER NOT NULL DEFAULT 0,
622            rejected_yaw      INTEGER NOT NULL DEFAULT 0,
623            completed_at      INTEGER NOT NULL DEFAULT (strftime('%s','now'))
624        );
625        INSERT INTO schema_version (version) VALUES (21);
626        "#,
627    )?;
628    tx.commit()?;
629    tracing::info!("Migrated database to schema version 21 (face_processing_stats)");
630    Ok(())
631}
632
633fn migrate_v17_to_v18(conn: &Connection) -> SqliteResult<()> {
634    // Perceptual hash for near-duplicate detection. 64-bit DCT phash;
635    // populated lazily by the thumbnail pipeline (see services/thumbnail.rs)
636    // and read by DuplicateDetector::find_perceptual_duplicates.
637    let tx = conn.unchecked_transaction()?;
638    match tx.execute("ALTER TABLE photos ADD COLUMN phash INTEGER", []) {
639        Ok(_) => {}
640        Err(e) => {
641            let msg = e.to_string();
642            if !msg.contains("duplicate column") {
643                return Err(e);
644            }
645        }
646    }
647    tx.execute(
648        "CREATE INDEX IF NOT EXISTS idx_photos_phash ON photos(phash) WHERE phash IS NOT NULL",
649        [],
650    )?;
651    tx.execute("INSERT INTO schema_version (version) VALUES (18)", [])?;
652    tx.commit()?;
653    tracing::info!("Migrated database to schema version 18 (photos.phash)");
654    Ok(())
655}
656
657fn migrate_v16_to_v17(conn: &Connection) -> SqliteResult<()> {
658    // Persist average brightness per photo. Previously face_processor
659    // recomputed it every run; now it's stored, queried via SQL during
660    // contextual identity propagation, and reused across runs.
661    let tx = conn.unchecked_transaction()?;
662    match tx.execute("ALTER TABLE photos ADD COLUMN brightness REAL", []) {
663        Ok(_) => {}
664        Err(e) => {
665            let msg = e.to_string();
666            if !msg.contains("duplicate column") {
667                return Err(e);
668            }
669        }
670    }
671    tx.execute("INSERT INTO schema_version (version) VALUES (17)", [])?;
672    tx.commit()?;
673    tracing::info!("Migrated database to schema version 17 (photos.brightness)");
674    Ok(())
675}
676
677fn migrate_v15_to_v16(conn: &Connection) -> SqliteResult<()> {
678    // Path-string normalization: rewrite stored relative paths to use
679    // forward slashes only. Backslashes from prior Windows writes are
680    // remapped so the same drive opens identically on every OS.
681    let tx = conn.unchecked_transaction()?;
682    tx.execute_batch(
683        r#"
684        UPDATE photos SET file_path = REPLACE(file_path, '\', '/');
685        UPDATE photos SET thumbnail_path = REPLACE(thumbnail_path, '\', '/')
686            WHERE thumbnail_path IS NOT NULL;
687        UPDATE trash SET original_path = REPLACE(original_path, '\', '/');
688
689        INSERT INTO schema_version (version) VALUES (16);
690        "#,
691    )?;
692    tx.commit()?;
693    tracing::info!("Migrated database to schema version 16 (forward-slash paths)");
694    Ok(())
695}
696
697fn migrate_v14_to_v15(conn: &Connection) -> SqliteResult<()> {
698    // Phase 2 Track A4/B2: composite indexes for hot query paths.
699    // Single-column indexes exist for these columns already, but the
700    // combined access pattern (filter-then-sort) hit the table before.
701    conn.execute_batch(
702        r#"
703        CREATE INDEX IF NOT EXISTS idx_photos_trashed_date
704            ON photos(is_trashed, date_taken DESC);
705
706        CREATE INDEX IF NOT EXISTS idx_photos_faces_processed_trashed
707            ON photos(faces_processed, is_trashed, date_taken DESC);
708
709        CREATE INDEX IF NOT EXISTS idx_faces_cluster_confidence
710            ON faces(cluster_id, confidence DESC, id);
711
712        CREATE INDEX IF NOT EXISTS idx_faces_photo_cluster
713            ON faces(photo_id, cluster_id);
714
715        INSERT INTO schema_version (version) VALUES (15);
716        "#,
717    )?;
718    tracing::info!("Migrated database to schema version 15 (composite indexes)");
719    Ok(())
720}
721
722fn migrate_v13_to_v14(conn: &Connection) -> SqliteResult<()> {
723    conn.execute_batch(
724        r#"
725        CREATE TABLE IF NOT EXISTS recent_searches (
726            id INTEGER PRIMARY KEY,
727            query TEXT NOT NULL,
728            last_used DATETIME DEFAULT CURRENT_TIMESTAMP,
729            use_count INTEGER DEFAULT 1,
730            UNIQUE(query)
731        );
732
733        CREATE INDEX IF NOT EXISTS idx_recent_searches_used
734            ON recent_searches(last_used DESC);
735
736        INSERT INTO schema_version (version) VALUES (14);
737        "#,
738    )?;
739    tracing::info!("Migrated database to schema version 14 (recent searches)");
740    Ok(())
741}
742
743fn migrate_v12_to_v13(conn: &Connection) -> SqliteResult<()> {
744    conn.execute_batch(
745        r#"
746        CREATE TABLE IF NOT EXISTS album_suggestions (
747            id INTEGER PRIMARY KEY,
748            kind TEXT NOT NULL,
749            title TEXT NOT NULL,
750            photo_ids_json TEXT NOT NULL,
751            cover_photo_id INTEGER,
752            fingerprint TEXT NOT NULL,
753            status TEXT NOT NULL DEFAULT 'pending',
754            seen_count INTEGER DEFAULT 0,
755            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
756            FOREIGN KEY (cover_photo_id) REFERENCES photos(id) ON DELETE SET NULL
757        );
758
759        CREATE INDEX IF NOT EXISTS idx_album_suggestions_status ON album_suggestions(status);
760        CREATE INDEX IF NOT EXISTS idx_album_suggestions_fingerprint ON album_suggestions(fingerprint);
761
762        INSERT INTO schema_version (version) VALUES (13);
763        "#,
764    )?;
765
766    tracing::info!("Migrated database to schema version 13 (album suggestions)");
767    Ok(())
768}
769
770fn migrate_v11_to_v12(conn: &Connection) -> SqliteResult<()> {
771    conn.execute_batch(
772        r#"
773        CREATE TABLE IF NOT EXISTS albums (
774            id INTEGER PRIMARY KEY,
775            name TEXT NOT NULL,
776            cover_photo_id INTEGER,
777            cover_auto_picked BOOLEAN DEFAULT TRUE,
778            photo_count INTEGER DEFAULT 0,
779            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
780            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
781            FOREIGN KEY (cover_photo_id) REFERENCES photos(id) ON DELETE SET NULL
782        );
783
784        CREATE TABLE IF NOT EXISTS album_photos (
785            id INTEGER PRIMARY KEY,
786            album_id INTEGER NOT NULL,
787            photo_id INTEGER NOT NULL,
788            added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
789            FOREIGN KEY (album_id) REFERENCES albums(id) ON DELETE CASCADE,
790            FOREIGN KEY (photo_id) REFERENCES photos(id) ON DELETE CASCADE,
791            UNIQUE(album_id, photo_id)
792        );
793
794        CREATE INDEX IF NOT EXISTS idx_album_photos_album ON album_photos(album_id);
795        CREATE INDEX IF NOT EXISTS idx_album_photos_photo ON album_photos(photo_id);
796
797        INSERT INTO schema_version (version) VALUES (12);
798        "#,
799    )?;
800
801    tracing::info!("Migrated database to schema version 12 (albums)");
802    Ok(())
803}
804
805fn migrate_v10_to_v11(conn: &Connection) -> SqliteResult<()> {
806    conn.execute_batch(
807        r#"
808        CREATE TABLE IF NOT EXISTS memory_blocks (
809            id INTEGER PRIMARY KEY,
810            kind TEXT NOT NULL,
811            target_key TEXT NOT NULL,
812            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
813            UNIQUE(kind, target_key)
814        );
815
816        CREATE INDEX IF NOT EXISTS idx_memory_blocks_kind ON memory_blocks(kind);
817
818        INSERT INTO schema_version (version) VALUES (11);
819        "#,
820    )?;
821
822    tracing::info!("Migrated database to schema version 11 (memory blocks)");
823    Ok(())
824}
825
826fn migrate_v3_to_v4(conn: &Connection) -> SqliteResult<()> {
827    // Add lens_model, flash, gps_altitude (these were missed in v3).
828    // Wrap in an explicit transaction so a crash mid-loop doesn't leave
829    // some columns added without bumping schema_version.
830    let tx = conn.unchecked_transaction()?;
831    let columns = [
832        ("lens_model", "TEXT"),
833        ("flash", "TEXT"),
834        ("gps_altitude", "REAL"),
835    ];
836
837    for (col, col_type) in &columns {
838        let sql = format!("ALTER TABLE photos ADD COLUMN {} {}", col, col_type);
839        match tx.execute(&sql, []) {
840            Ok(_) => {}
841            Err(e) => {
842                let msg = e.to_string();
843                if !msg.contains("duplicate column") {
844                    return Err(e);
845                }
846            }
847        }
848    }
849
850    tx.execute("INSERT INTO schema_version (version) VALUES (4)", [])?;
851    tx.commit()?;
852    tracing::info!("Migrated database to schema version 4 (lens, flash, altitude)");
853    Ok(())
854}
855
856fn migrate_v5_to_v6(conn: &Connection) -> SqliteResult<()> {
857    conn.execute("INSERT INTO schema_version (version) VALUES (6)", [])?;
858    Ok(())
859}
860
861fn migrate_v6_to_v7(conn: &Connection) -> SqliteResult<()> {
862    match conn.execute(
863        "ALTER TABLE face_clusters ADD COLUMN photo_count INTEGER DEFAULT 0",
864        [],
865    ) {
866        Ok(_) => {}
867        Err(e) => {
868            let msg = e.to_string();
869            if !msg.contains("duplicate column") {
870                return Err(e);
871            }
872        }
873    }
874
875    conn.execute_batch(
876        r#"
877        UPDATE face_clusters
878        SET
879            face_count = (SELECT COUNT(*) FROM faces WHERE cluster_id = face_clusters.id),
880            photo_count = (
881                SELECT COUNT(DISTINCT photo_id)
882                FROM (
883                    SELECT photo_id FROM faces WHERE cluster_id = face_clusters.id
884                    UNION
885                    SELECT photo_id FROM photo_inferred_identities WHERE cluster_id = face_clusters.id
886                )
887            ),
888            representative_face_id = (
889                SELECT id
890                FROM faces
891                WHERE cluster_id = face_clusters.id
892                ORDER BY confidence DESC
893                LIMIT 1
894            ),
895            updated_at = CURRENT_TIMESTAMP;
896
897        INSERT INTO schema_version (version) VALUES (7);
898        "#,
899    )?;
900
901    tracing::info!("Migrated database to schema version 7 (face cluster photo counts)");
902    Ok(())
903}
904
905fn migrate_v7_to_v8(conn: &Connection) -> SqliteResult<()> {
906    match conn.execute(
907        "ALTER TABLE photo_inferred_identities ADD COLUMN is_inferred BOOLEAN DEFAULT TRUE",
908        [],
909    ) {
910        Ok(_) => {}
911        Err(e) => {
912            let msg = e.to_string();
913            if !msg.contains("duplicate column") {
914                return Err(e);
915            }
916        }
917    }
918
919    conn.execute_batch(
920        r#"
921        UPDATE photo_inferred_identities
922        SET is_inferred = TRUE
923        WHERE is_inferred IS NULL;
924
925        CREATE INDEX IF NOT EXISTS idx_inferred_is_inferred ON photo_inferred_identities(is_inferred);
926
927        INSERT INTO schema_version (version) VALUES (8);
928        "#,
929    )?;
930
931    tracing::info!("Migrated database to schema version 8 (inferred identity flag)");
932    Ok(())
933}
934
935fn migrate_v9_to_v10(conn: &Connection) -> SqliteResult<()> {
936    let add_col = |sql: &str| -> SqliteResult<()> {
937        match conn.execute(sql, []) {
938            Ok(_) => Ok(()),
939            Err(e) => {
940                let msg = e.to_string();
941                if msg.contains("duplicate column") {
942                    Ok(())
943                } else {
944                    Err(e)
945                }
946            }
947        }
948    };
949
950    add_col("ALTER TABLE faces ADD COLUMN user_confirmed INTEGER DEFAULT 0")?;
951    add_col("ALTER TABLE face_clusters ADD COLUMN is_user_named INTEGER DEFAULT 0")?;
952    add_col("ALTER TABLE person_gallery_embeddings ADD COLUMN source TEXT DEFAULT 'auto'")?;
953
954    conn.execute_batch(
955        r#"
956        CREATE TABLE IF NOT EXISTS cluster_cannot_merge (
957            id INTEGER PRIMARY KEY,
958            cluster_a_id INTEGER NOT NULL,
959            cluster_b_id INTEGER NOT NULL,
960            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
961            FOREIGN KEY (cluster_a_id) REFERENCES face_clusters(id) ON DELETE CASCADE,
962            FOREIGN KEY (cluster_b_id) REFERENCES face_clusters(id) ON DELETE CASCADE,
963            UNIQUE(cluster_a_id, cluster_b_id)
964        );
965
966        CREATE INDEX IF NOT EXISTS idx_cannot_merge_a ON cluster_cannot_merge(cluster_a_id);
967        CREATE INDEX IF NOT EXISTS idx_cannot_merge_b ON cluster_cannot_merge(cluster_b_id);
968
969        CREATE TABLE IF NOT EXISTS face_review_queue (
970            id INTEGER PRIMARY KEY,
971            face_id INTEGER NOT NULL,
972            candidate_cluster_id INTEGER NOT NULL,
973            score REAL NOT NULL,
974            ambiguity REAL,
975            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
976            resolved_at DATETIME,
977            resolved_as TEXT,
978            FOREIGN KEY (face_id) REFERENCES faces(id) ON DELETE CASCADE,
979            FOREIGN KEY (candidate_cluster_id) REFERENCES face_clusters(id) ON DELETE CASCADE,
980            UNIQUE(face_id, candidate_cluster_id)
981        );
982
983        CREATE INDEX IF NOT EXISTS idx_review_queue_face ON face_review_queue(face_id);
984        CREATE INDEX IF NOT EXISTS idx_review_queue_cluster ON face_review_queue(candidate_cluster_id);
985        CREATE INDEX IF NOT EXISTS idx_review_queue_unresolved
986            ON face_review_queue(resolved_at) WHERE resolved_at IS NULL;
987
988        CREATE INDEX IF NOT EXISTS idx_gallery_source ON person_gallery_embeddings(source);
989
990        INSERT INTO schema_version (version) VALUES (10);
991        "#,
992    )?;
993
994    tracing::info!("Migrated database to schema version 10 (face feedback tables)");
995    Ok(())
996}
997
998fn migrate_v8_to_v9(conn: &Connection) -> SqliteResult<()> {
999    conn.execute_batch(
1000        r#"
1001        CREATE TABLE IF NOT EXISTS person_gallery_embeddings (
1002            id INTEGER PRIMARY KEY,
1003            cluster_id INTEGER NOT NULL,
1004            face_id INTEGER NOT NULL,
1005            embedding BLOB NOT NULL,
1006            pose_label TEXT,
1007            quality_score REAL,
1008            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
1009
1010            FOREIGN KEY (cluster_id) REFERENCES face_clusters(id) ON DELETE CASCADE,
1011            FOREIGN KEY (face_id) REFERENCES faces(id) ON DELETE CASCADE,
1012            UNIQUE(cluster_id, face_id)
1013        );
1014
1015        CREATE INDEX IF NOT EXISTS idx_gallery_cluster ON person_gallery_embeddings(cluster_id);
1016        CREATE INDEX IF NOT EXISTS idx_gallery_face ON person_gallery_embeddings(face_id);
1017
1018        INSERT INTO schema_version (version) VALUES (9);
1019        "#,
1020    )?;
1021
1022    tracing::info!("Migrated database to schema version 9 (person gallery embeddings)");
1023    Ok(())
1024}
1025
1026fn migrate_v4_to_v5(conn: &Connection) -> SqliteResult<()> {
1027    conn.execute_batch(
1028        r#"
1029        CREATE TABLE IF NOT EXISTS photo_inferred_identities (
1030            id INTEGER PRIMARY KEY,
1031            photo_id INTEGER NOT NULL,
1032            cluster_id INTEGER NOT NULL,
1033            source_photo_id INTEGER NOT NULL,
1034            confidence REAL NOT NULL,
1035            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
1036
1037            FOREIGN KEY (photo_id) REFERENCES photos(id) ON DELETE CASCADE,
1038            FOREIGN KEY (cluster_id) REFERENCES face_clusters(id) ON DELETE CASCADE,
1039            FOREIGN KEY (source_photo_id) REFERENCES photos(id) ON DELETE CASCADE,
1040            UNIQUE(photo_id, cluster_id)
1041        );
1042
1043        CREATE INDEX IF NOT EXISTS idx_inferred_photo ON photo_inferred_identities(photo_id);
1044        CREATE INDEX IF NOT EXISTS idx_inferred_cluster ON photo_inferred_identities(cluster_id);
1045
1046        INSERT INTO schema_version (version) VALUES (5);
1047        "#,
1048    )?;
1049
1050    tracing::info!("Migrated database to schema version 5 (inferred identities)");
1051    Ok(())
1052}
1053
1054fn migrate_v2_to_v3(conn: &Connection) -> SqliteResult<()> {
1055    // Add EXIF shooting parameters. Wrap the ALTER loop + version
1056    // bump in one transaction so partial application can't leave us
1057    // with some columns added but schema_version still at 2.
1058    let tx = conn.unchecked_transaction()?;
1059    let columns = [
1060        ("iso", "INTEGER"),
1061        ("aperture", "TEXT"),
1062        ("shutter_speed", "TEXT"),
1063        ("focal_length", "TEXT"),
1064        ("lens_model", "TEXT"),
1065        ("flash", "TEXT"),
1066        ("gps_altitude", "REAL"),
1067    ];
1068
1069    for (col, col_type) in &columns {
1070        let sql = format!("ALTER TABLE photos ADD COLUMN {} {}", col, col_type);
1071        match tx.execute(&sql, []) {
1072            Ok(_) => {}
1073            Err(e) => {
1074                // Column may already exist if migration was partially applied
1075                let msg = e.to_string();
1076                if !msg.contains("duplicate column") {
1077                    return Err(e);
1078                }
1079            }
1080        }
1081    }
1082
1083    tx.execute("INSERT INTO schema_version (version) VALUES (3)", [])?;
1084    tx.commit()?;
1085    tracing::info!("Migrated database to schema version 3 (EXIF shooting params)");
1086    Ok(())
1087}
1088
1089fn migrate_v1_to_v2(conn: &Connection) -> SqliteResult<()> {
1090    conn.execute_batch(
1091        r#"
1092        CREATE TABLE IF NOT EXISTS trash (
1093            id INTEGER PRIMARY KEY,
1094            photo_id INTEGER NOT NULL UNIQUE,
1095            original_path TEXT NOT NULL,
1096            trashed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
1097            FOREIGN KEY (photo_id) REFERENCES photos(id) ON DELETE CASCADE
1098        );
1099
1100        CREATE INDEX IF NOT EXISTS idx_trash_trashed_at ON trash(trashed_at);
1101        CREATE INDEX IF NOT EXISTS idx_face_clusters_name ON face_clusters(name);
1102
1103        INSERT INTO schema_version (version) VALUES (2);
1104        "#,
1105    )?;
1106
1107    Ok(())
1108}
1109
1110#[cfg(test)]
1111mod tests {
1112    use super::*;
1113    use rusqlite::Connection;
1114
1115    fn revision_28_fixture() -> Connection {
1116        let conn = Connection::open_in_memory().unwrap();
1117        crate::db::create_schema(&conn).unwrap();
1118        conn.execute_batch(
1119            "DROP TRIGGER semantic_revision_insert;
1120             DROP TRIGGER semantic_revision_update;
1121             DROP TRIGGER semantic_revision_delete;
1122             DROP TRIGGER semantic_revision_visibility;
1123             DROP TRIGGER semantic_revision_photo_delete;
1124             DROP TABLE semantic_revision;
1125             DELETE FROM schema_version;
1126             INSERT INTO schema_version(version) VALUES(28);
1127             INSERT INTO photos(file_path,file_name,file_hash,file_size)
1128                VALUES('one.jpg','one.jpg','abcd',1);",
1129        )
1130        .unwrap();
1131        conn
1132    }
1133
1134    #[test]
1135    fn latest_migrations_match_fresh_objects() {
1136        let migrated = revision_28_fixture();
1137        run_migrations(&migrated).unwrap();
1138        run_migrations(&migrated).unwrap();
1139        let fresh = Connection::open_in_memory().unwrap();
1140        crate::db::create_schema(&fresh).unwrap();
1141        run_migrations(&fresh).unwrap();
1142        fn objects(conn: &Connection) -> Vec<(String, String)> {
1143            conn.prepare("SELECT type,name FROM sqlite_master ORDER BY type,name")
1144                .unwrap()
1145                .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))
1146                .unwrap()
1147                .collect::<rusqlite::Result<Vec<_>>>()
1148                .unwrap()
1149        }
1150        assert_eq!(objects(&migrated), objects(&fresh));
1151        assert_eq!(
1152            get_schema_version(&migrated).unwrap(),
1153            MAX_KNOWN_SCHEMA_VERSION
1154        );
1155        assert_eq!(
1156            migrated
1157                .query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0))
1158                .unwrap(),
1159            "ok"
1160        );
1161        assert!(!migrated
1162            .prepare("PRAGMA foreign_key_check")
1163            .unwrap()
1164            .exists([])
1165            .unwrap());
1166    }
1167
1168    #[test]
1169    fn run_migrations_reports_newer_schema_version() {
1170        let conn = Connection::open_in_memory().unwrap();
1171        conn.execute_batch(
1172            r#"
1173            CREATE TABLE schema_version (
1174                version INTEGER PRIMARY KEY,
1175                applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
1176            );
1177            INSERT INTO schema_version (version) VALUES (999);
1178            "#,
1179        )
1180        .unwrap();
1181
1182        let err = run_migrations(&conn).unwrap_err();
1183        let schema = err
1184            .downcast_ref::<SchemaTooNewError>()
1185            .expect("newer schema should produce SchemaTooNewError");
1186        assert_eq!(schema.db_version, 999);
1187        assert_eq!(schema.max_supported, MAX_KNOWN_SCHEMA_VERSION);
1188    }
1189
1190    #[test]
1191    fn migrate_v27_to_v28_adds_takeout_ledger() {
1192        let conn = Connection::open_in_memory().unwrap();
1193        conn.execute_batch(
1194            r#"
1195            CREATE TABLE schema_version (
1196                version INTEGER PRIMARY KEY,
1197                applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
1198            );
1199            INSERT INTO schema_version (version) VALUES (27);
1200            "#,
1201        )
1202        .unwrap();
1203
1204        migrate_v27_to_v28(&conn).unwrap();
1205        assert_eq!(get_schema_version(&conn).unwrap(), 28);
1206        let table_count: i64 = conn
1207            .query_row(
1208                "SELECT COUNT(*) FROM sqlite_master
1209                 WHERE type = 'table'
1210                   AND name IN ('google_takeout_items', 'google_takeout_albums')",
1211                [],
1212                |row| row.get(0),
1213            )
1214            .unwrap();
1215        assert_eq!(table_count, 2);
1216    }
1217
1218    #[test]
1219    fn run_migrations_adds_timeline_order_index_without_version_bump() {
1220        let conn = Connection::open_in_memory().unwrap();
1221        conn.execute_batch(
1222            r#"
1223            CREATE TABLE schema_version (
1224                version INTEGER PRIMARY KEY,
1225                applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
1226            );
1227            INSERT INTO schema_version (version) VALUES (30);
1228            CREATE TABLE photos (
1229                id INTEGER PRIMARY KEY,
1230                date_taken DATETIME,
1231                file_size INTEGER NOT NULL DEFAULT 0,
1232                gps_latitude REAL,
1233                gps_longitude REAL,
1234                is_favorite BOOLEAN DEFAULT FALSE,
1235                is_trashed BOOLEAN DEFAULT FALSE
1236            );
1237            CREATE TABLE faces (
1238                id INTEGER PRIMARY KEY,
1239                photo_id INTEGER NOT NULL,
1240                cluster_id INTEGER,
1241                user_confirmed INTEGER DEFAULT 0
1242            );
1243            "#,
1244        )
1245        .unwrap();
1246
1247        run_migrations(&conn).unwrap();
1248
1249        let version = get_schema_version(&conn).unwrap();
1250        assert_eq!(version, MAX_KNOWN_SCHEMA_VERSION);
1251        let plan = conn
1252            .prepare(
1253                "EXPLAIN QUERY PLAN
1254                 SELECT id FROM photos
1255                 WHERE is_trashed = 0
1256                 ORDER BY date_taken IS NULL ASC, date_taken DESC, id DESC
1257                 LIMIT 50",
1258            )
1259            .unwrap()
1260            .query_map([], |row| row.get::<_, String>(3))
1261            .unwrap()
1262            .collect::<rusqlite::Result<Vec<_>>>()
1263            .unwrap()
1264            .join("\n");
1265        assert!(plan.contains("idx_photos_timeline_order"), "{plan}");
1266        assert!(!plan.contains("USE TEMP B-TREE"), "{plan}");
1267        let plan = conn
1268            .prepare(
1269                "EXPLAIN QUERY PLAN
1270                 SELECT id FROM faces
1271                 WHERE cluster_id = 10 AND user_confirmed = 0
1272                 ORDER BY id ASC
1273                 LIMIT 50",
1274            )
1275            .unwrap()
1276            .query_map([], |row| row.get::<_, String>(3))
1277            .unwrap()
1278            .collect::<rusqlite::Result<Vec<_>>>()
1279            .unwrap()
1280            .join("\n");
1281        assert!(plan.contains("idx_faces_review_pending"), "{plan}");
1282        assert!(!plan.contains("USE TEMP B-TREE"), "{plan}");
1283        let plan = conn
1284            .prepare(
1285                "EXPLAIN QUERY PLAN
1286                 SELECT id FROM photos
1287                 WHERE is_favorite = TRUE AND is_trashed = 0
1288                 ORDER BY date_taken IS NULL ASC, date_taken DESC, id DESC
1289                 LIMIT 50",
1290            )
1291            .unwrap()
1292            .query_map([], |row| row.get::<_, String>(3))
1293            .unwrap()
1294            .collect::<rusqlite::Result<Vec<_>>>()
1295            .unwrap()
1296            .join("\n");
1297        assert!(plan.contains("idx_photos_favorite_order"), "{plan}");
1298        assert!(!plan.contains("USE TEMP B-TREE"), "{plan}");
1299        let plan = conn
1300            .prepare(
1301                "EXPLAIN QUERY PLAN
1302                 SELECT id FROM photos
1303                 WHERE is_trashed = 0
1304                   AND gps_latitude IS NOT NULL
1305                   AND gps_longitude IS NOT NULL
1306                   AND gps_latitude >= 10.0 AND gps_latitude <= 20.0
1307                   AND gps_longitude >= 70.0 AND gps_longitude <= 80.0
1308                 LIMIT 50",
1309            )
1310            .unwrap()
1311            .query_map([], |row| row.get::<_, String>(3))
1312            .unwrap()
1313            .collect::<rusqlite::Result<Vec<_>>>()
1314            .unwrap()
1315            .join("\n");
1316        assert!(plan.contains("idx_photos_gps_bounds"), "{plan}");
1317    }
1318
1319    #[test]
1320    fn test_migrate_v18_to_v19() -> rusqlite::Result<()> {
1321        let conn = Connection::open_in_memory().unwrap();
1322        conn.execute_batch(
1323            r#"
1324            CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY, applied_at DATETIME DEFAULT CURRENT_TIMESTAMP);
1325            INSERT INTO schema_version (version) VALUES (1);
1326
1327            CREATE TABLE IF NOT EXISTS photos (
1328                id INTEGER PRIMARY KEY,
1329                file_path TEXT NOT NULL,
1330                file_name TEXT NOT NULL,
1331                file_hash TEXT NOT NULL,
1332                file_size INTEGER NOT NULL,
1333                file_mtime INTEGER,
1334                date_taken DATETIME,
1335                date_taken_source TEXT,
1336                gps_latitude REAL,
1337                gps_longitude REAL,
1338                location_city TEXT,
1339                location_country TEXT,
1340                camera_make TEXT,
1341                camera_model TEXT,
1342                iso INTEGER,
1343                aperture TEXT,
1344                shutter_speed TEXT,
1345                focal_length TEXT,
1346                lens_model TEXT,
1347                flash TEXT,
1348                gps_altitude REAL,
1349                width INTEGER,
1350                height INTEGER,
1351                orientation INTEGER DEFAULT 1,
1352                thumbnail_path TEXT,
1353                faces_processed BOOLEAN DEFAULT FALSE,
1354                brightness REAL,
1355                phash INTEGER,
1356                is_trashed BOOLEAN DEFAULT FALSE,
1357                trashed_at DATETIME,
1358                indexed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
1359                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
1360                UNIQUE(file_path)
1361            );
1362            "#,
1363        ).unwrap();
1364
1365        // Insert a row that already has EXIF data (simulates legacy scanner)
1366        conn.execute(
1367            "INSERT INTO photos (file_path, file_name, file_hash, file_size, date_taken, camera_make, thumbnail_path, faces_processed) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, 0)",
1368            rusqlite::params!["/photos/img1.jpg", "img1.jpg", "abc123", 1000000, "2024-01-01T00:00:00Z", "Canon", "thumb/img1.jpg"],
1369        ).unwrap();
1370
1371        // Insert a row with no EXIF and no thumbnail
1372        conn.execute(
1373            "INSERT INTO photos (file_path, file_name, file_hash, file_size, faces_processed) VALUES (?1, ?2, ?3, ?4, 0)",
1374            rusqlite::params!["/photos/img2.png", "img2.png", "def456", 500000],
1375        ).unwrap();
1376
1377        // Advance schema version to 18 (simulate all prior migrations done)
1378        conn.execute("INSERT INTO schema_version (version) VALUES (18)", [])
1379            .unwrap();
1380
1381        // Run v18->v19 migration
1382        migrate_v18_to_v19(&conn).unwrap();
1383
1384        // Verify columns exist
1385        let columns: Vec<String> = conn
1386            .prepare("PRAGMA table_info(photos)")?
1387            .query_map([], |row| row.get::<_, String>(1))?
1388            .collect::<rusqlite::Result<Vec<_>>>()?;
1389        assert!(columns.iter().any(|c| c == "metadata_extracted"));
1390        assert!(columns.iter().any(|c| c == "thumbnailed"));
1391
1392        // Row with EXIF data should have metadata_extracted = TRUE
1393        let meta_flag: bool = conn
1394            .query_row(
1395                "SELECT metadata_extracted FROM photos WHERE file_path = '/photos/img1.jpg'",
1396                [],
1397                |row| row.get(0),
1398            )
1399            .unwrap();
1400        assert!(meta_flag);
1401
1402        // Row without EXIF should have metadata_extracted = FALSE
1403        let meta_flag2: bool = conn
1404            .query_row(
1405                "SELECT metadata_extracted FROM photos WHERE file_path = '/photos/img2.png'",
1406                [],
1407                |row| row.get(0),
1408            )
1409            .unwrap();
1410        assert!(!meta_flag2);
1411
1412        // Row with thumbnail should have thumbnailed = TRUE
1413        let thumb_flag: bool = conn
1414            .query_row(
1415                "SELECT thumbnailed FROM photos WHERE file_path = '/photos/img1.jpg'",
1416                [],
1417                |row| row.get(0),
1418            )
1419            .unwrap();
1420        assert!(thumb_flag);
1421
1422        // Row without thumbnail should have thumbnailed = FALSE
1423        let thumb_flag2: bool = conn
1424            .query_row(
1425                "SELECT thumbnailed FROM photos WHERE file_path = '/photos/img2.png'",
1426                [],
1427                |row| row.get(0),
1428            )
1429            .unwrap();
1430        assert!(!thumb_flag2);
1431
1432        // Verify partial indexes exist
1433        let idx_count: i64 = conn.query_row(
1434            "SELECT COUNT(*) FROM sqlite_master WHERE type='index' AND name IN ('idx_photos_metadata_extracted', 'idx_photos_thumbnailed')",
1435            [],
1436            |row| row.get(0),
1437        ).unwrap();
1438        assert_eq!(idx_count, 2);
1439        Ok(())
1440    }
1441
1442    #[test]
1443    fn test_migrate_v24_to_v25() {
1444        let conn = Connection::open_in_memory().unwrap();
1445        conn.execute_batch(
1446            r#"
1447            CREATE TABLE schema_version (
1448                version INTEGER PRIMARY KEY,
1449                applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
1450            );
1451            INSERT INTO schema_version (version) VALUES (24);
1452            "#,
1453        )
1454        .unwrap();
1455
1456        migrate_v24_to_v25(&conn).unwrap();
1457
1458        let table_count: i64 = conn
1459            .query_row(
1460                "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='excluded_folders'",
1461                [],
1462                |row| row.get(0),
1463            )
1464            .unwrap();
1465        assert_eq!(table_count, 1);
1466
1467        let version = get_schema_version(&conn).unwrap();
1468        assert_eq!(version, 25);
1469    }
1470}