| 1 | use chrono::{DateTime, Utc}; |
| 2 | use rusqlite::{OptionalExtension, params}; |
| 3 | |
| 4 | use crate::error::Result; |
| 5 | use crate::models::AvatarRecord; |
| 6 | use crate::store::{Store, json_ids}; |
| 7 | use crate::time::{from_millis, to_millis}; |
| 8 | |
| 9 | impl Store { |
| 10 | pub fn avatar(&self, user_id: &str) -> Result<Option<AvatarRecord>> { |
| 11 | let connection = self.lock()?; |
| 12 | Ok(connection |
| 13 | .query_row( |
| 14 | "SELECT user_id, bytes, content_type, fetched_at FROM avatars WHERE user_id = ?1", |
| 15 | [user_id], |
| 16 | |row| { |
| 17 | Ok(AvatarRecord { |
| 18 | user_id: row.get(0)?, |
| 19 | bytes: row.get(1)?, |
| 20 | content_type: row.get(2)?, |
| 21 | fetched_at: from_millis(row.get(3)?), |
| 22 | }) |
| 23 | }, |
| 24 | ) |
| 25 | .optional()?) |
| 26 | } |
| 27 | |
| 28 | pub fn upsert_avatar(&self, avatar: &AvatarRecord) -> Result<()> { |
| 29 | let connection = self.lock()?; |
| 30 | connection.execute( |
| 31 | "INSERT INTO avatars (user_id, bytes, content_type, fetched_at) VALUES (?1, ?2, ?3, ?4) |
| 32 | ON CONFLICT (user_id) DO UPDATE SET |
| 33 | bytes = excluded.bytes, content_type = excluded.content_type, fetched_at = excluded.fetched_at", |
| 34 | params![ |
| 35 | avatar.user_id, |
| 36 | avatar.bytes, |
| 37 | avatar.content_type, |
| 38 | to_millis(avatar.fetched_at) |
| 39 | ], |
| 40 | )?; |
| 41 | Ok(()) |
| 42 | } |
| 43 | |
| 44 | /// Ids with no avatar row or a row fetched before `cutoff`. |
| 45 | pub fn avatar_ids_needing_fetch( |
| 46 | &self, |
| 47 | user_ids: &[String], |
| 48 | cutoff: DateTime<Utc>, |
| 49 | ) -> Result<Vec<String>> { |
| 50 | let connection = self.lock()?; |
| 51 | let mut statement = connection.prepare_cached( |
| 52 | "SELECT value FROM json_each(?1) |
| 53 | WHERE value NOT IN (SELECT user_id FROM avatars WHERE fetched_at >= ?2)", |
| 54 | )?; |
| 55 | let rows = statement.query_map(params![json_ids(user_ids), to_millis(cutoff)], |row| { |
| 56 | row.get::<_, String>(0) |
| 57 | })?; |
| 58 | Ok(rows.collect::<rusqlite::Result<_>>()?) |
| 59 | } |
| 60 | } |