Skip to main content

sunday_slate/nfl_player_headshots/
store.rs

1use std::collections::HashMap;
2
3use nfl_model::NflPlayerId;
4use sqlx::Sqlite;
5
6use crate::media::{Media, MediaId, store as media_store};
7
8/// Cached gsis ids. Table row is the marker, even if the file is gone.
9pub async fn cached_player_ids<'e, E>(ex: E) -> Result<Vec<NflPlayerId>, sqlx::Error>
10where
11    E: sqlx::Executor<'e, Database = Sqlite>,
12{
13    sqlx::query_scalar::<_, NflPlayerId>("SELECT nfl_player_id FROM nfl_player_headshots")
14        .fetch_all(ex)
15        .await
16}
17
18pub async fn set_headshot_media_id<'e, E>(
19    ex: E,
20    nfl_player_id: &NflPlayerId,
21    media_id: MediaId,
22) -> Result<(), sqlx::Error>
23where
24    E: sqlx::Executor<'e, Database = Sqlite>,
25{
26    sqlx::query!(
27        r#"INSERT INTO nfl_player_headshots (nfl_player_id, headshot_media_id) VALUES (?1, ?2)
28           ON CONFLICT (nfl_player_id) DO UPDATE SET headshot_media_id = excluded.headshot_media_id"#,
29        nfl_player_id,
30        media_id,
31    )
32    .execute(ex)
33    .await
34    .map(|_| ())
35}
36
37pub async fn headshots_for<'e, E>(
38    ex: E,
39    gsis_ids: &[&str],
40) -> Result<HashMap<String, Media>, sqlx::Error>
41where
42    E: sqlx::Executor<'e, Database = Sqlite>,
43{
44    if gsis_ids.is_empty() {
45        return Ok(HashMap::new());
46    }
47    let placeholders = std::iter::repeat_n("?", gsis_ids.len())
48        .collect::<Vec<_>>()
49        .join(",");
50    let sql = format!(
51        r#"SELECT h.nfl_player_id AS key, m.*
52           FROM nfl_player_headshots h
53           JOIN media m ON m.id = h.headshot_media_id
54           WHERE h.nfl_player_id IN ({placeholders})"#
55    );
56    media_store::fetch_keyed(ex, &sql, gsis_ids).await
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62    use crate::media::store as media_store;
63    use sqlx::SqlitePool;
64
65    #[sqlx::test]
66    async fn headshot_batch_lookup_follows_media_links(pool: SqlitePool) {
67        let media_id = media_store::insert(&pool, "headshot.png", "image/png", 12, 256, 128)
68            .await
69            .expect("media");
70        set_headshot_media_id(&pool, &NflPlayerId("00-LINKED".into()), media_id)
71            .await
72            .expect("link");
73
74        let rows = headshots_for(&pool, &["00-LINKED", "00-MISSING", "00-UNKNOWN"])
75            .await
76            .expect("headshots");
77        assert_eq!(rows.len(), 1);
78        assert_eq!(rows["00-LINKED"].id, media_id);
79        assert!(headshots_for(&pool, &[]).await.expect("empty").is_empty());
80    }
81}