Skip to main content

smriti/db/
schema.rs

1//! Database schema creation
2//!
3//! Creates all tables needed for Smriti. The schema is designed to:
4//! - Support all Phase 1 features
5//! - Be extensible for Phase 2
6//! - Allow efficient queries with proper indexes
7
8use rusqlite::{Connection, Result as SqliteResult};
9
10/// Create the complete database schema
11///
12/// This should be called once when initializing a new database.
13pub fn create_schema(conn: &Connection) -> SqliteResult<()> {
14    conn.execute_batch(SCHEMA_SQL)?;
15    conn.execute_batch(SEMANTIC_REVISION_SQL)?;
16    tracing::info!("Database schema created successfully");
17    Ok(())
18}
19
20pub(crate) const SEMANTIC_REVISION_SQL: &str = "
21CREATE TABLE IF NOT EXISTS semantic_revision (id INTEGER PRIMARY KEY CHECK(id = 1), revision INTEGER NOT NULL);
22INSERT OR IGNORE INTO semantic_revision VALUES (1, 0);
23CREATE TRIGGER IF NOT EXISTS semantic_revision_insert AFTER INSERT ON semantic_index_state BEGIN
24    UPDATE semantic_revision SET revision = revision + 1 WHERE id = 1;
25END;
26CREATE TRIGGER IF NOT EXISTS semantic_revision_update AFTER UPDATE ON semantic_index_state BEGIN
27    UPDATE semantic_revision SET revision = revision + 1 WHERE id = 1;
28END;
29CREATE TRIGGER IF NOT EXISTS semantic_revision_delete AFTER DELETE ON semantic_index_state BEGIN
30    UPDATE semantic_revision SET revision = revision + 1 WHERE id = 1;
31END;
32CREATE TRIGGER IF NOT EXISTS semantic_revision_visibility AFTER UPDATE OF is_trashed ON photos
33WHEN old.is_trashed IS NOT new.is_trashed BEGIN
34    UPDATE semantic_revision SET revision = revision + 1 WHERE id = 1;
35END;
36CREATE TRIGGER IF NOT EXISTS semantic_revision_photo_delete AFTER DELETE ON photos BEGIN
37    UPDATE semantic_revision SET revision = revision + 1 WHERE id = 1;
38END;
39";
40
41const SCHEMA_SQL: &str = r#"
42-- ============================================================
43-- SCHEMA VERSION
44-- ============================================================
45
46CREATE TABLE IF NOT EXISTS schema_version (
47    version INTEGER PRIMARY KEY,
48    applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
49);
50
51INSERT INTO schema_version (version) VALUES (33);
52
53-- ============================================================
54-- LIBRARY META — key/value store for library-level bookkeeping
55-- (e.g. the thumbnail-repair cursor)
56-- ============================================================
57
58CREATE TABLE IF NOT EXISTS library_meta (
59    key TEXT PRIMARY KEY,
60    value TEXT NOT NULL
61);
62
63-- ============================================================
64-- PHOTOS TABLE
65-- Core photo metadata
66-- ============================================================
67
68CREATE TABLE IF NOT EXISTS photos (
69    id INTEGER PRIMARY KEY,
70
71    -- File information
72    file_path TEXT NOT NULL,           -- Relative path from drive root
73    file_name TEXT NOT NULL,
74    file_hash TEXT NOT NULL,           -- SHA256 for duplicate detection
75    file_size INTEGER NOT NULL,
76    file_mtime INTEGER,                -- File modification time (unix timestamp)
77
78    -- EXIF metadata
79    date_taken DATETIME,               -- From EXIF, fallback to file mtime
80    date_taken_source TEXT,            -- 'exif' | 'filename' | 'mtime'
81    gps_latitude REAL,
82    gps_longitude REAL,
83    location_city TEXT,                -- Reverse geocoded
84    location_country TEXT,             -- Reverse geocoded
85    camera_make TEXT,
86    camera_model TEXT,
87    iso INTEGER,                       -- ISO sensitivity
88    aperture TEXT,                     -- e.g. "f/2.8"
89    shutter_speed TEXT,                -- e.g. "1/125"
90    focal_length TEXT,                 -- e.g. "50mm"
91    lens_model TEXT,                   -- e.g. "iPhone 15 Pro back camera"
92    flash TEXT,                        -- "Fired" or "Off"
93    gps_altitude REAL,                 -- meters above/below sea level
94    width INTEGER,
95    height INTEGER,
96    orientation INTEGER DEFAULT 1,
97
98    -- Media metadata
99    media_type TEXT NOT NULL DEFAULT 'photo', -- 'photo' | 'video'
100    duration_ms INTEGER,
101    video_codec TEXT,
102    audio_codec TEXT,
103    frame_rate REAL,
104    bitrate INTEGER,
105    has_audio BOOLEAN DEFAULT FALSE,
106
107    -- Processing state
108    thumbnail_path TEXT,               -- Path to cached thumbnail (relative)
109    faces_processed BOOLEAN DEFAULT FALSE,
110    face_attempts INTEGER NOT NULL DEFAULT 0, -- failed face-detection runs
111    metadata_extracted BOOLEAN DEFAULT FALSE,
112    thumbnailed BOOLEAN DEFAULT FALSE,
113    brightness REAL,                   -- Average luma in [0,1], cached from face pipeline
114    phash INTEGER,                     -- 64-bit DCT perceptual hash for near-duplicate detection
115    content_hash TEXT,                 -- cached full-file SHA-256 for exact duplicate grouping
116
117    -- Soft delete
118    is_favorite BOOLEAN DEFAULT FALSE,
119    is_trashed BOOLEAN DEFAULT FALSE,
120    trashed_at DATETIME,
121
122    -- Timestamps
123    indexed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
124    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
125
126    UNIQUE(file_path)
127);
128
129-- ============================================================
130-- FACES TABLE
131-- Detected faces in photos
132-- ============================================================
133
134CREATE TABLE IF NOT EXISTS faces (
135    id INTEGER PRIMARY KEY,
136    photo_id INTEGER NOT NULL,
137    
138    -- Bounding box (normalized 0-1 coordinates)
139    bbox_x REAL NOT NULL,
140    bbox_y REAL NOT NULL,
141    bbox_width REAL NOT NULL,
142    bbox_height REAL NOT NULL,
143    
144    -- Face embedding (512-dimensional vector, stored as blob)
145    embedding BLOB NOT NULL,
146    
147    -- Clustering
148    cluster_id INTEGER,                -- NULL = unassigned
149    confidence REAL,                   -- Detection confidence
150
151    -- Interactive feedback: 0=untouched, 1=user confirmed, -1=user rejected from a candidate
152    user_confirmed INTEGER DEFAULT 0,
153
154    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
155
156    FOREIGN KEY (photo_id) REFERENCES photos(id) ON DELETE CASCADE,
157    FOREIGN KEY (cluster_id) REFERENCES face_clusters(id) ON DELETE SET NULL
158);
159
160-- ============================================================
161-- FACE CLUSTERS TABLE  
162-- A cluster represents a person
163-- ============================================================
164
165CREATE TABLE IF NOT EXISTS face_clusters (
166    id INTEGER PRIMARY KEY,
167    name TEXT,                         -- NULL = unnamed, user sets this
168    representative_face_id INTEGER,    -- Best face for this cluster (for display)
169    face_count INTEGER DEFAULT 0,
170    photo_count INTEGER DEFAULT 0,
171
172    -- 1 if the user has explicitly named/confirmed this cluster
173    is_user_named INTEGER DEFAULT 0,
174
175    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
176    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
177
178    FOREIGN KEY (representative_face_id) REFERENCES faces(id) ON DELETE SET NULL
179);
180
181-- ============================================================
182-- INFERRED IDENTITIES
183-- Contextual person links for photos without visible faces
184-- ============================================================
185
186CREATE TABLE IF NOT EXISTS photo_inferred_identities (
187    id INTEGER PRIMARY KEY,
188    photo_id INTEGER NOT NULL,
189    cluster_id INTEGER NOT NULL,
190    source_photo_id INTEGER NOT NULL,
191    confidence REAL NOT NULL,
192    is_inferred BOOLEAN DEFAULT TRUE,
193    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
194
195    FOREIGN KEY (photo_id) REFERENCES photos(id) ON DELETE CASCADE,
196    FOREIGN KEY (cluster_id) REFERENCES face_clusters(id) ON DELETE CASCADE,
197    FOREIGN KEY (source_photo_id) REFERENCES photos(id) ON DELETE CASCADE,
198    UNIQUE(photo_id, cluster_id)
199);
200
201CREATE TABLE IF NOT EXISTS person_gallery_embeddings (
202    id INTEGER PRIMARY KEY,
203    cluster_id INTEGER NOT NULL,
204    face_id INTEGER NOT NULL,
205    embedding BLOB NOT NULL,
206    pose_label TEXT,
207    quality_score REAL,
208    -- 'auto' = chosen by diversity sampling, 'user_confirmed' = sticky user decision
209    source TEXT DEFAULT 'auto',
210    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
211
212    FOREIGN KEY (cluster_id) REFERENCES face_clusters(id) ON DELETE CASCADE,
213    FOREIGN KEY (face_id) REFERENCES faces(id) ON DELETE CASCADE,
214    UNIQUE(cluster_id, face_id)
215);
216
217-- ============================================================
218-- INTERACTIVE FEEDBACK
219-- User-driven constraints and review queue for face recognition
220-- ============================================================
221
222CREATE TABLE IF NOT EXISTS cluster_cannot_merge (
223    id INTEGER PRIMARY KEY,
224    cluster_a_id INTEGER NOT NULL,
225    cluster_b_id INTEGER NOT NULL,
226    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
227
228    FOREIGN KEY (cluster_a_id) REFERENCES face_clusters(id) ON DELETE CASCADE,
229    FOREIGN KEY (cluster_b_id) REFERENCES face_clusters(id) ON DELETE CASCADE,
230    UNIQUE(cluster_a_id, cluster_b_id)
231);
232
233CREATE TABLE IF NOT EXISTS face_review_queue (
234    id INTEGER PRIMARY KEY,
235    face_id INTEGER NOT NULL,
236    candidate_cluster_id INTEGER NOT NULL,
237    score REAL NOT NULL,               -- top match score (higher = better)
238    ambiguity REAL,                    -- score margin to 2nd candidate (lower = more ambiguous)
239    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
240    resolved_at DATETIME,
241    resolved_as TEXT,                  -- 'same' | 'different' | 'skipped'
242
243    FOREIGN KEY (face_id) REFERENCES faces(id) ON DELETE CASCADE,
244    FOREIGN KEY (candidate_cluster_id) REFERENCES face_clusters(id) ON DELETE CASCADE,
245    UNIQUE(face_id, candidate_cluster_id)
246);
247
248CREATE TABLE IF NOT EXISTS face_negatives (
249    face_id        INTEGER NOT NULL,
250    not_cluster_id INTEGER NOT NULL,
251    created_at     INTEGER NOT NULL DEFAULT (strftime('%s','now')),
252    PRIMARY KEY (face_id, not_cluster_id),
253    FOREIGN KEY (face_id)        REFERENCES faces(id)         ON DELETE CASCADE,
254    FOREIGN KEY (not_cluster_id) REFERENCES face_clusters(id) ON DELETE CASCADE
255);
256
257-- Single-row table: rejection counts from a face-processing run. No
258-- longer written; kept so existing libraries keep a matching schema.
259CREATE TABLE IF NOT EXISTS face_processing_stats (
260    id                INTEGER PRIMARY KEY CHECK (id = 1),
261    rejected_small    INTEGER NOT NULL DEFAULT 0,
262    rejected_lowconf  INTEGER NOT NULL DEFAULT 0,
263    rejected_blurry   INTEGER NOT NULL DEFAULT 0,
264    rejected_yaw      INTEGER NOT NULL DEFAULT 0,
265    completed_at      INTEGER NOT NULL DEFAULT (strftime('%s','now'))
266);
267
268-- ============================================================
269-- MEMORY BLOCKS
270-- User preferences for the Memories feature: hide memories involving
271-- specific people, or (future) specific date ranges.
272-- ============================================================
273
274CREATE TABLE IF NOT EXISTS memory_blocks (
275    id              INTEGER PRIMARY KEY,
276    kind            TEXT NOT NULL,      -- 'person' (v1); 'date_range' future
277    target_key      TEXT NOT NULL,      -- cluster_id as string, or "MM-DD..MM-DD"
278    created_at      DATETIME DEFAULT CURRENT_TIMESTAMP,
279    UNIQUE(kind, target_key)
280);
281
282-- ============================================================
283-- ALBUMS
284-- User-created photo collections
285-- ============================================================
286
287CREATE TABLE IF NOT EXISTS albums (
288    id INTEGER PRIMARY KEY,
289    name TEXT NOT NULL,
290    cover_photo_id INTEGER,
291    cover_auto_picked BOOLEAN DEFAULT TRUE,
292    photo_count INTEGER DEFAULT 0,
293    created_by TEXT NOT NULL DEFAULT 'user' CHECK(created_by IN ('user', 'agent')),
294    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
295    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
296    FOREIGN KEY (cover_photo_id) REFERENCES photos(id) ON DELETE SET NULL
297);
298
299CREATE TABLE IF NOT EXISTS album_photos (
300    id INTEGER PRIMARY KEY,
301    album_id INTEGER NOT NULL,
302    photo_id INTEGER NOT NULL,
303    added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
304    FOREIGN KEY (album_id) REFERENCES albums(id) ON DELETE CASCADE,
305    FOREIGN KEY (photo_id) REFERENCES photos(id) ON DELETE CASCADE,
306    UNIQUE(album_id, photo_id)
307);
308
309-- ============================================================
310-- GOOGLE PHOTOS TAKEOUT
311-- Durable source metadata and album membership for resumable imports.
312-- Originals remain ordinary files under the library root.
313-- ============================================================
314
315CREATE TABLE IF NOT EXISTS google_takeout_items (
316    content_hash TEXT PRIMARY KEY,
317    file_path TEXT NOT NULL UNIQUE,
318    metadata_json TEXT,
319    imported_at DATETIME DEFAULT CURRENT_TIMESTAMP,
320    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
321);
322
323CREATE TABLE IF NOT EXISTS google_takeout_albums (
324    content_hash TEXT NOT NULL,
325    album_name TEXT NOT NULL,
326    PRIMARY KEY (content_hash, album_name),
327    FOREIGN KEY (content_hash) REFERENCES google_takeout_items(content_hash)
328        ON DELETE CASCADE
329);
330
331-- ============================================================
332-- ALBUM SUGGESTIONS
333-- Auto-detected trip/event album proposals
334-- ============================================================
335
336CREATE TABLE IF NOT EXISTS album_suggestions (
337    id INTEGER PRIMARY KEY,
338    kind TEXT NOT NULL,                 -- 'trip' | 'event'
339    title TEXT NOT NULL,
340    photo_ids_json TEXT NOT NULL,       -- JSON array of photo IDs
341    cover_photo_id INTEGER,
342    fingerprint TEXT NOT NULL,          -- Hash of sorted photo IDs
343    status TEXT NOT NULL DEFAULT 'pending', -- 'pending' | 'accepted' | 'dismissed'
344    seen_count INTEGER DEFAULT 0,
345    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
346    FOREIGN KEY (cover_photo_id) REFERENCES photos(id) ON DELETE SET NULL
347);
348
349-- ============================================================
350-- DUPLICATE GROUPS
351-- Groups of identical or near-identical photos
352-- ============================================================
353
354CREATE TABLE IF NOT EXISTS duplicate_groups (
355    id INTEGER PRIMARY KEY,
356    group_hash TEXT,                   -- Shared hash
357    duplicate_type TEXT NOT NULL,      -- 'exact' | 'perceptual'
358    resolved BOOLEAN DEFAULT FALSE,    -- User has dealt with this group
359    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
360);
361
362CREATE TABLE IF NOT EXISTS duplicate_group_members (
363    id INTEGER PRIMARY KEY,
364    group_id INTEGER NOT NULL,
365    photo_id INTEGER NOT NULL,
366    is_suggested_keep BOOLEAN DEFAULT FALSE,  -- Our recommendation
367    
368    FOREIGN KEY (group_id) REFERENCES duplicate_groups(id) ON DELETE CASCADE,
369    FOREIGN KEY (photo_id) REFERENCES photos(id) ON DELETE CASCADE,
370    UNIQUE(group_id, photo_id)
371);
372
373-- ============================================================
374-- BURST GROUPS
375-- Photos taken within seconds of each other
376-- ============================================================
377
378CREATE TABLE IF NOT EXISTS burst_groups (
379    id INTEGER PRIMARY KEY,
380    start_time DATETIME NOT NULL,
381    end_time DATETIME NOT NULL,
382    photo_count INTEGER DEFAULT 0,
383    resolved BOOLEAN DEFAULT FALSE,    -- User has reviewed this burst
384    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
385);
386
387CREATE TABLE IF NOT EXISTS burst_group_members (
388    id INTEGER PRIMARY KEY,
389    group_id INTEGER NOT NULL,
390    photo_id INTEGER NOT NULL,
391    sharpness_score REAL,             -- Higher = sharper
392    blur_score REAL,                  -- Lower = less blur
393    face_count INTEGER DEFAULT 0,
394    is_suggested_best BOOLEAN DEFAULT FALSE,
395    
396    FOREIGN KEY (group_id) REFERENCES burst_groups(id) ON DELETE CASCADE,
397    FOREIGN KEY (photo_id) REFERENCES photos(id) ON DELETE CASCADE,
398    UNIQUE(group_id, photo_id)
399);
400
401-- ============================================================
402-- PHOTO STACKS
403-- Timeline presentation groups for high-confidence related photos
404-- ============================================================
405
406CREATE TABLE IF NOT EXISTS photo_stacks (
407    id INTEGER PRIMARY KEY,
408    kind TEXT NOT NULL,                  -- 'exact_duplicate' | 'perceptual_duplicate' | 'burst'
409    source_group_id INTEGER NOT NULL,    -- duplicate_groups.id or burst_groups.id
410    source_group_hash TEXT,
411    cover_photo_id INTEGER NOT NULL,
412    confidence REAL NOT NULL DEFAULT 1.0,
413    dismissed BOOLEAN DEFAULT FALSE,
414    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
415    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
416    UNIQUE(kind, source_group_id)
417);
418
419CREATE TABLE IF NOT EXISTS photo_stack_members (
420    id INTEGER PRIMARY KEY,
421    stack_id INTEGER NOT NULL,
422    photo_id INTEGER NOT NULL,
423    quality_score REAL NOT NULL DEFAULT 0,
424    score_reasons TEXT,
425    is_cover BOOLEAN DEFAULT FALSE,
426    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
427    FOREIGN KEY (stack_id) REFERENCES photo_stacks(id) ON DELETE CASCADE,
428    FOREIGN KEY (photo_id) REFERENCES photos(id) ON DELETE CASCADE,
429    UNIQUE(stack_id, photo_id)
430);
431
432-- ============================================================
433-- TRASH TABLE
434-- Tracks soft-deleted photos for restore/permanent delete
435-- ============================================================
436
437CREATE TABLE IF NOT EXISTS trash (
438    id INTEGER PRIMARY KEY,
439    photo_id INTEGER NOT NULL UNIQUE,
440    original_path TEXT NOT NULL,
441    trashed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
442
443    FOREIGN KEY (photo_id) REFERENCES photos(id) ON DELETE CASCADE
444);
445
446-- ============================================================
447-- RECENT SEARCHES
448-- Per-library search history (last N queries)
449-- ============================================================
450
451CREATE TABLE IF NOT EXISTS recent_searches (
452    id INTEGER PRIMARY KEY,
453    query TEXT NOT NULL,
454    last_used DATETIME DEFAULT CURRENT_TIMESTAMP,
455    use_count INTEGER DEFAULT 1,
456    UNIQUE(query)
457);
458
459-- ============================================================
460-- EXCLUDED FOLDERS
461-- Per-library folders skipped by scanner and reindexer
462-- ============================================================
463
464CREATE TABLE IF NOT EXISTS excluded_folders (
465    relative_path TEXT PRIMARY KEY,
466    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
467);
468
469-- ============================================================
470-- SEMANTIC SEARCH
471-- ============================================================
472
473CREATE TABLE IF NOT EXISTS semantic_index_state (
474    photo_id INTEGER NOT NULL,
475    model_key TEXT NOT NULL,
476    status TEXT NOT NULL DEFAULT 'pending'
477        CHECK(status IN ('pending', 'indexed', 'failed', 'unsupported')),
478    vector_offset INTEGER,
479    vector_dim INTEGER,
480    attempts INTEGER NOT NULL DEFAULT 0,
481    last_error TEXT,
482    indexed_at DATETIME,
483    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
484    PRIMARY KEY (photo_id, model_key),
485    FOREIGN KEY (photo_id) REFERENCES photos(id) ON DELETE CASCADE
486);
487
488-- ============================================================
489-- INDEXES FOR PERFORMANCE
490-- ============================================================
491
492-- Photos
493CREATE INDEX IF NOT EXISTS idx_photos_date ON photos(date_taken);
494CREATE INDEX IF NOT EXISTS idx_photos_hash ON photos(file_hash);
495CREATE INDEX IF NOT EXISTS idx_photos_location ON photos(location_country, location_city);
496CREATE INDEX IF NOT EXISTS idx_photos_gps_bounds
497    ON photos(is_trashed, gps_latitude, gps_longitude)
498    WHERE gps_latitude IS NOT NULL AND gps_longitude IS NOT NULL;
499CREATE INDEX IF NOT EXISTS idx_photos_trashed ON photos(is_trashed);
500CREATE INDEX IF NOT EXISTS idx_photos_path ON photos(file_path);
501CREATE INDEX IF NOT EXISTS idx_photos_media_type ON photos(media_type);
502CREATE INDEX IF NOT EXISTS idx_photos_favorite
503    ON photos(is_favorite, date_taken DESC) WHERE is_favorite = TRUE;
504CREATE INDEX IF NOT EXISTS idx_photos_favorite_order
505    ON photos(is_favorite, is_trashed, (date_taken IS NULL), date_taken DESC, id DESC)
506    WHERE is_favorite = TRUE;
507CREATE INDEX IF NOT EXISTS idx_photos_metadata_extracted
508    ON photos(metadata_extracted) WHERE metadata_extracted = FALSE;
509CREATE INDEX IF NOT EXISTS idx_photos_thumbnailed
510    ON photos(thumbnailed) WHERE thumbnailed = FALSE;
511CREATE INDEX IF NOT EXISTS idx_photos_trashed_date
512    ON photos(is_trashed, date_taken DESC);
513CREATE INDEX IF NOT EXISTS idx_photos_timeline_order
514    ON photos(is_trashed, (date_taken IS NULL), date_taken DESC, id DESC);
515CREATE INDEX IF NOT EXISTS idx_photos_faces_processed_trashed
516    ON photos(faces_processed, is_trashed, date_taken DESC);
517CREATE INDEX IF NOT EXISTS idx_photos_phash ON photos(phash) WHERE phash IS NOT NULL;
518
519-- Faces
520CREATE INDEX IF NOT EXISTS idx_faces_cluster ON faces(cluster_id);
521CREATE INDEX IF NOT EXISTS idx_faces_photo ON faces(photo_id);
522CREATE INDEX IF NOT EXISTS idx_faces_cluster_confidence
523    ON faces(cluster_id, confidence DESC, id);
524CREATE INDEX IF NOT EXISTS idx_faces_photo_cluster
525    ON faces(photo_id, cluster_id);
526CREATE INDEX IF NOT EXISTS idx_faces_review_pending
527    ON faces(user_confirmed, cluster_id, id)
528    WHERE user_confirmed = 0 AND cluster_id IS NOT NULL;
529CREATE INDEX IF NOT EXISTS idx_face_clusters_name ON face_clusters(name);
530CREATE INDEX IF NOT EXISTS idx_inferred_photo ON photo_inferred_identities(photo_id);
531CREATE INDEX IF NOT EXISTS idx_inferred_cluster ON photo_inferred_identities(cluster_id);
532CREATE INDEX IF NOT EXISTS idx_inferred_is_inferred ON photo_inferred_identities(is_inferred);
533CREATE INDEX IF NOT EXISTS idx_gallery_cluster ON person_gallery_embeddings(cluster_id);
534CREATE INDEX IF NOT EXISTS idx_gallery_face ON person_gallery_embeddings(face_id);
535CREATE INDEX IF NOT EXISTS idx_gallery_source ON person_gallery_embeddings(source);
536CREATE INDEX IF NOT EXISTS idx_cannot_merge_a ON cluster_cannot_merge(cluster_a_id);
537CREATE INDEX IF NOT EXISTS idx_cannot_merge_b ON cluster_cannot_merge(cluster_b_id);
538CREATE INDEX IF NOT EXISTS idx_review_queue_face ON face_review_queue(face_id);
539CREATE INDEX IF NOT EXISTS idx_review_queue_cluster ON face_review_queue(candidate_cluster_id);
540CREATE INDEX IF NOT EXISTS idx_review_queue_unresolved ON face_review_queue(resolved_at)
541    WHERE resolved_at IS NULL;
542CREATE INDEX IF NOT EXISTS idx_face_negatives_cluster ON face_negatives(not_cluster_id);
543CREATE INDEX IF NOT EXISTS idx_memory_blocks_kind ON memory_blocks(kind);
544-- Duplicate and burst group members
545CREATE INDEX IF NOT EXISTS idx_dup_members_group ON duplicate_group_members(group_id);
546CREATE INDEX IF NOT EXISTS idx_dup_members_photo ON duplicate_group_members(photo_id);
547CREATE INDEX IF NOT EXISTS idx_burst_members_group ON burst_group_members(group_id);
548CREATE INDEX IF NOT EXISTS idx_burst_members_photo ON burst_group_members(photo_id);
549CREATE INDEX IF NOT EXISTS idx_photo_stacks_cover ON photo_stacks(cover_photo_id);
550CREATE INDEX IF NOT EXISTS idx_photo_stacks_active ON photo_stacks(dismissed, kind);
551CREATE INDEX IF NOT EXISTS idx_photo_stack_members_stack ON photo_stack_members(stack_id);
552CREATE INDEX IF NOT EXISTS idx_photo_stack_members_photo ON photo_stack_members(photo_id);
553CREATE INDEX IF NOT EXISTS idx_photo_stack_members_cover ON photo_stack_members(stack_id, is_cover);
554CREATE INDEX IF NOT EXISTS idx_trash_trashed_at ON trash(trashed_at);
555
556-- Albums
557CREATE INDEX IF NOT EXISTS idx_album_photos_album ON album_photos(album_id);
558CREATE INDEX IF NOT EXISTS idx_album_photos_photo ON album_photos(photo_id);
559CREATE INDEX IF NOT EXISTS idx_google_takeout_items_path ON google_takeout_items(file_path);
560
561-- Album suggestions
562CREATE INDEX IF NOT EXISTS idx_album_suggestions_status ON album_suggestions(status);
563CREATE INDEX IF NOT EXISTS idx_album_suggestions_fingerprint ON album_suggestions(fingerprint);
564
565-- Recent searches
566CREATE INDEX IF NOT EXISTS idx_recent_searches_used ON recent_searches(last_used DESC);
567
568-- Semantic search
569CREATE INDEX IF NOT EXISTS idx_semantic_state_status
570    ON semantic_index_state(model_key, status);
571CREATE INDEX IF NOT EXISTS idx_semantic_state_photo
572    ON semantic_index_state(photo_id);
573"#;
574
575#[cfg(test)]
576mod tests {
577    use super::*;
578    use rusqlite::Connection;
579
580    #[test]
581    fn test_create_schema() {
582        let conn = Connection::open_in_memory().unwrap();
583        create_schema(&conn).unwrap();
584
585        // Verify photos table exists
586        let count: i32 = conn
587            .query_row(
588                "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='photos'",
589                [],
590                |row| row.get(0),
591            )
592            .unwrap();
593
594        assert_eq!(count, 1);
595
596        let count: i32 = conn
597            .query_row(
598                "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='excluded_folders'",
599                [],
600                |row| row.get(0),
601            )
602            .unwrap();
603
604        assert_eq!(count, 1);
605
606        let plan = conn
607            .prepare(
608                "EXPLAIN QUERY PLAN
609                 SELECT id FROM photos
610                 WHERE is_trashed = 0
611                 ORDER BY date_taken IS NULL ASC, date_taken DESC, id DESC
612                 LIMIT 50",
613            )
614            .unwrap()
615            .query_map([], |row| row.get::<_, String>(3))
616            .unwrap()
617            .collect::<rusqlite::Result<Vec<_>>>()
618            .unwrap()
619            .join("\n");
620        assert!(plan.contains("idx_photos_timeline_order"), "{plan}");
621        assert!(!plan.contains("USE TEMP B-TREE"), "{plan}");
622
623        let plan = conn
624            .prepare(
625                "EXPLAIN QUERY PLAN
626                 SELECT id FROM faces
627                 WHERE cluster_id = 10 AND user_confirmed = 0
628                 ORDER BY id ASC
629                 LIMIT 50",
630            )
631            .unwrap()
632            .query_map([], |row| row.get::<_, String>(3))
633            .unwrap()
634            .collect::<rusqlite::Result<Vec<_>>>()
635            .unwrap()
636            .join("\n");
637        assert!(plan.contains("idx_faces_review_pending"), "{plan}");
638        assert!(!plan.contains("USE TEMP B-TREE"), "{plan}");
639
640        let plan = conn
641            .prepare(
642                "EXPLAIN QUERY PLAN
643                 SELECT id FROM photos
644                 WHERE is_favorite = TRUE AND is_trashed = 0
645                 ORDER BY date_taken IS NULL ASC, date_taken DESC, id DESC
646                 LIMIT 50",
647            )
648            .unwrap()
649            .query_map([], |row| row.get::<_, String>(3))
650            .unwrap()
651            .collect::<rusqlite::Result<Vec<_>>>()
652            .unwrap()
653            .join("\n");
654        assert!(plan.contains("idx_photos_favorite_order"), "{plan}");
655        assert!(!plan.contains("USE TEMP B-TREE"), "{plan}");
656
657        let plan = conn
658            .prepare(
659                "EXPLAIN QUERY PLAN
660                 SELECT id FROM photos
661                 WHERE is_trashed = 0
662                   AND gps_latitude IS NOT NULL
663                   AND gps_longitude IS NOT NULL
664                   AND gps_latitude >= 10.0 AND gps_latitude <= 20.0
665                   AND gps_longitude >= 70.0 AND gps_longitude <= 80.0
666                 LIMIT 50",
667            )
668            .unwrap()
669            .query_map([], |row| row.get::<_, String>(3))
670            .unwrap()
671            .collect::<rusqlite::Result<Vec<_>>>()
672            .unwrap()
673            .join("\n");
674        assert!(plan.contains("idx_photos_gps_bounds"), "{plan}");
675    }
676}