smriti/db/
inferred_identity_repo.rs1use rusqlite::{params, Connection, Result as SqliteResult};
6
7pub struct InferredIdentityRepo<'a> {
9 conn: &'a Connection,
10}
11
12impl<'a> InferredIdentityRepo<'a> {
13 pub fn new(conn: &'a Connection) -> Self {
14 Self { conn }
15 }
16
17 pub fn insert_inferred_identity(
18 &self,
19 photo_id: i64,
20 cluster_id: i64,
21 source_photo_id: i64,
22 confidence: f32,
23 ) -> SqliteResult<()> {
24 self.conn.execute(
25 r#"
26 INSERT INTO photo_inferred_identities (photo_id, cluster_id, source_photo_id, confidence, is_inferred)
27 VALUES (?1, ?2, ?3, ?4, TRUE)
28 ON CONFLICT(photo_id, cluster_id) DO UPDATE SET
29 source_photo_id = excluded.source_photo_id,
30 confidence = excluded.confidence,
31 is_inferred = TRUE,
32 created_at = CURRENT_TIMESTAMP
33 "#,
34 params![photo_id, cluster_id, source_photo_id, confidence],
35 )?;
36 self.refresh_cluster_stats(cluster_id)?;
37 Ok(())
38 }
39
40 fn refresh_cluster_stats(&self, cluster_id: i64) -> SqliteResult<()> {
41 self.conn.execute(
42 r#"
43 UPDATE face_clusters SET
44 face_count = (SELECT COUNT(*) FROM faces WHERE cluster_id = ?1),
45 photo_count = (
46 SELECT COUNT(DISTINCT photo_id)
47 FROM (
48 SELECT photo_id FROM faces WHERE cluster_id = ?1
49 UNION
50 SELECT photo_id FROM photo_inferred_identities WHERE cluster_id = ?1
51 )
52 ),
53 representative_face_id = (
54 SELECT id
55 FROM faces
56 WHERE cluster_id = ?1
57 ORDER BY confidence DESC
58 LIMIT 1
59 ),
60 updated_at = CURRENT_TIMESTAMP
61 WHERE id = ?1
62 "#,
63 params![cluster_id],
64 )?;
65
66 Ok(())
67 }
68}