Skip to main content

nflverse_data/store/
player_stats.rs

1use sqlx::SqlitePool;
2
3use crate::error::NflDataError;
4use crate::model::{PlayerWeekStats, Season, SeasonType, SeasonWeek, TeamAbbr, Week};
5use crate::store::Store;
6use crate::store::sync_state::{self, SyncedAsset};
7
8/// One `player_week_stats` row exactly as stored: the identity is decomposed
9/// into its columns and the classification is a stored column. The domain type
10/// carries a single [`SeasonWeek`] instead, so reads go through this adapter,
11/// which validates the two against each other.
12struct Row {
13    season: Season,
14    week: Week,
15    season_type: SeasonType,
16    gsis_id: String,
17    team: TeamAbbr,
18    opponent: Option<TeamAbbr>,
19    completions: u32,
20    attempts: u32,
21    passing_yards: i32,
22    passing_tds: u32,
23    passing_interceptions: u32,
24    rushing_attempts: u32,
25    rushing_yards: i32,
26    rushing_tds: u32,
27    targets: u32,
28    receptions: u32,
29    receiving_yards: i32,
30    receiving_tds: u32,
31    fumbles_lost: u32,
32    two_point_conversions: u32,
33    special_teams_tds: u32,
34    fumble_recovery_tds: u32,
35}
36
37fn decode_error(message: String) -> sqlx::Error {
38    sqlx::Error::Decode(message.into())
39}
40
41impl TryFrom<Row> for PlayerWeekStats {
42    type Error = sqlx::Error;
43
44    fn try_from(row: Row) -> Result<Self, Self::Error> {
45        let season_week = SeasonWeek::new(row.season, row.week)
46            .ok_or_else(|| decode_error(format!("invalid absolute week {}", row.week.0)))?;
47        let implied = if season_week.postseason() {
48            SeasonType::Post
49        } else {
50            SeasonType::Reg
51        };
52        if row.season_type != implied {
53            return Err(decode_error(format!(
54                "season type {:?} conflicts with absolute week {}",
55                row.season_type, season_week.week.0
56            )));
57        }
58        Ok(Self {
59            season_week,
60            gsis_id: row.gsis_id,
61            team: row.team,
62            opponent: row.opponent,
63            completions: row.completions,
64            attempts: row.attempts,
65            passing_yards: row.passing_yards,
66            passing_tds: row.passing_tds,
67            passing_interceptions: row.passing_interceptions,
68            rushing_attempts: row.rushing_attempts,
69            rushing_yards: row.rushing_yards,
70            rushing_tds: row.rushing_tds,
71            targets: row.targets,
72            receptions: row.receptions,
73            receiving_yards: row.receiving_yards,
74            receiving_tds: row.receiving_tds,
75            fumbles_lost: row.fumbles_lost,
76            two_point_conversions: row.two_point_conversions,
77            special_teams_tds: row.special_teams_tds,
78            fumble_recovery_tds: row.fumble_recovery_tds,
79        })
80    }
81}
82
83pub(crate) async fn replace(
84    store: &Store,
85    asset: &SyncedAsset<'_>,
86    season: Season,
87    stats: &[PlayerWeekStats],
88) -> Result<u64, NflDataError> {
89    for s in stats {
90        debug_assert_eq!(
91            s.season_week.season, season,
92            "player week stats entry season must match the replace() season param"
93        );
94    }
95
96    store
97        .write_tx(async |conn| {
98            sqlx::query!("DELETE FROM player_week_stats WHERE season = ?", season)
99                .execute(&mut *conn)
100                .await?;
101            for s in stats {
102                let season_type = if s.season_week.postseason() {
103                    SeasonType::Post
104                } else {
105                    SeasonType::Reg
106                };
107                sqlx::query!(
108                    r#"INSERT INTO player_week_stats
109                       (season, week, season_type, gsis_id, team, opponent,
110                        completions, attempts,
111                        passing_yards, passing_tds, passing_interceptions,
112                        rushing_attempts, rushing_yards, rushing_tds,
113                        targets, receptions, receiving_yards, receiving_tds,
114                        fumbles_lost, two_point_conversions, special_teams_tds,
115                        fumble_recovery_tds)
116                       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
117                               ?, ?, ?, ?, ?)"#,
118                    s.season_week.season,
119                    s.season_week.week,
120                    season_type,
121                    s.gsis_id,
122                    s.team,
123                    s.opponent,
124                    s.completions,
125                    s.attempts,
126                    s.passing_yards,
127                    s.passing_tds,
128                    s.passing_interceptions,
129                    s.rushing_attempts,
130                    s.rushing_yards,
131                    s.rushing_tds,
132                    s.targets,
133                    s.receptions,
134                    s.receiving_yards,
135                    s.receiving_tds,
136                    s.fumbles_lost,
137                    s.two_point_conversions,
138                    s.special_teams_tds,
139                    s.fumble_recovery_tds,
140                )
141                .execute(&mut *conn)
142                .await?;
143            }
144            sync_state::record(conn, asset).await?;
145            Ok(stats.len() as u64)
146        })
147        .await
148}
149
150pub(crate) async fn for_week(
151    pool: &SqlitePool,
152    season_week: SeasonWeek,
153) -> Result<Vec<PlayerWeekStats>, NflDataError> {
154    let rows = sqlx::query_as!(
155        Row,
156        r#"SELECT
157               season AS "season: Season",
158               week AS "week: Week",
159               season_type AS "season_type: SeasonType",
160               gsis_id,
161               team AS "team: TeamAbbr",
162               opponent AS "opponent: TeamAbbr",
163               completions AS "completions: u32",
164               attempts AS "attempts: u32",
165               passing_yards AS "passing_yards: i32",
166               passing_tds AS "passing_tds: u32",
167               passing_interceptions AS "passing_interceptions: u32",
168               rushing_attempts AS "rushing_attempts: u32",
169               rushing_yards AS "rushing_yards: i32",
170               rushing_tds AS "rushing_tds: u32",
171               targets AS "targets: u32",
172               receptions AS "receptions: u32",
173               receiving_yards AS "receiving_yards: i32",
174               receiving_tds AS "receiving_tds: u32",
175               fumbles_lost AS "fumbles_lost: u32",
176               two_point_conversions AS "two_point_conversions: u32",
177               special_teams_tds AS "special_teams_tds: u32",
178               fumble_recovery_tds AS "fumble_recovery_tds: u32"
179           FROM player_week_stats
180           WHERE season = ? AND week = ?
181           ORDER BY gsis_id, season_type"#,
182        season_week.season,
183        season_week.week
184    )
185    .fetch_all(pool)
186    .await?;
187
188    rows.into_iter()
189        .map(PlayerWeekStats::try_from)
190        .collect::<Result<Vec<_>, _>>()
191        .map_err(NflDataError::from)
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    /// Every numeric field gets a distinct value so that a positional
199    /// argument swap in the INSERT's VALUES list would compile cleanly but
200    /// flip two field values and fail the roundtrip assertion.
201    fn stat_a() -> PlayerWeekStats {
202        PlayerWeekStats {
203            season_week: SeasonWeek::new(Season(2025), Week(1)).unwrap(),
204            gsis_id: "00-1111111".into(),
205            team: TeamAbbr::GB,
206            opponent: Some(TeamAbbr::CHI),
207            completions: 199,
208            attempts: 201,
209            passing_yards: 233,
210            passing_tds: 34,
211            passing_interceptions: 12,
212            rushing_attempts: 41,
213            rushing_yards: -9,
214            rushing_tds: 27,
215            targets: 18,
216            receptions: 15,
217            receiving_yards: 71,
218            receiving_tds: 6,
219            fumbles_lost: 3,
220            two_point_conversions: 2,
221            special_teams_tds: 1,
222            fumble_recovery_tds: 59,
223        }
224    }
225
226    fn stat_b() -> PlayerWeekStats {
227        PlayerWeekStats {
228            season_week: SeasonWeek::new(Season(2025), Week(1)).unwrap(),
229            gsis_id: "00-2222222".into(),
230            team: TeamAbbr::DAL,
231            opponent: Some(TeamAbbr::NYG),
232            completions: 202,
233            attempts: 203,
234            passing_yards: -14,
235            passing_tds: 44,
236            passing_interceptions: 4,
237            rushing_attempts: 55,
238            rushing_yards: 63,
239            rushing_tds: 7,
240            targets: 39,
241            receptions: 28,
242            receiving_yards: 17,
243            receiving_tds: 5,
244            fumbles_lost: 8,
245            two_point_conversions: 6,
246            special_teams_tds: 2,
247            fumble_recovery_tds: 109,
248        }
249    }
250
251    async fn store() -> (tempfile::TempDir, Store) {
252        let dir = tempfile::tempdir().unwrap();
253        let store = Store::open(&format!("sqlite://{}/t.db", dir.path().display()))
254            .await
255            .unwrap();
256        (dir, store)
257    }
258
259    fn asset(name: &str) -> SyncedAsset<'_> {
260        SyncedAsset {
261            release_tag: "stats_player",
262            asset_name: name,
263            updated_at: "2026-06-20T00:00:00Z",
264        }
265    }
266
267    #[tokio::test]
268    async fn replace_then_for_week_roundtrips_every_field() {
269        let (_dir, store) = store().await;
270        let mut written = vec![stat_a(), stat_b()];
271        replace(
272            &store,
273            &asset("stats_player_week_2025.csv"),
274            Season(2025),
275            &written,
276        )
277        .await
278        .unwrap();
279
280        let mut read_back = for_week(store.reader(), written[0].season_week)
281            .await
282            .unwrap();
283
284        // for_week() orders by (gsis_id, season_type), so sorting `written`
285        // the same way makes this a direct full-struct comparison rather
286        // than just a length check.
287        written.sort_by(|a, b| a.gsis_id.cmp(&b.gsis_id));
288        read_back.sort_by(|a, b| a.gsis_id.cmp(&b.gsis_id));
289
290        assert_eq!(read_back, written);
291    }
292
293    #[tokio::test]
294    async fn season_week_roundtrips_postseason_weeks_in_full() {
295        let (_dir, store) = store().await;
296        let mut written = Vec::new();
297        for week in [18u8, 19, 22] {
298            let mut stat = stat_a();
299            stat.season_week = SeasonWeek::new(Season(2025), Week(week)).unwrap();
300            stat.gsis_id = format!("00-{week:07}");
301            written.push(stat);
302        }
303        replace(
304            &store,
305            &asset("stats_player_week_2025.csv"),
306            Season(2025),
307            &written,
308        )
309        .await
310        .unwrap();
311
312        for expected in &written {
313            let rows = for_week(store.reader(), expected.season_week)
314                .await
315                .unwrap();
316            assert_eq!(rows, std::slice::from_ref(expected));
317            assert_eq!(
318                rows[0].season_week.postseason(),
319                expected.season_week.week.0 > 18
320            );
321        }
322    }
323
324    #[tokio::test]
325    async fn season_week_scopes_reads_to_the_season() {
326        let (_dir, store) = store().await;
327        let mut older = stat_a();
328        older.season_week = SeasonWeek::new(Season(2024), Week(1)).unwrap();
329        let mut newer = stat_b();
330        newer.season_week = SeasonWeek::new(Season(2025), Week(1)).unwrap();
331        replace(
332            &store,
333            &asset("stats_player_week_2024.csv"),
334            Season(2024),
335            std::slice::from_ref(&older),
336        )
337        .await
338        .unwrap();
339        replace(
340            &store,
341            &asset("stats_player_week_2025.csv"),
342            Season(2025),
343            std::slice::from_ref(&newer),
344        )
345        .await
346        .unwrap();
347
348        assert_eq!(
349            for_week(store.reader(), newer.season_week).await.unwrap(),
350            [newer]
351        );
352        assert_eq!(
353            for_week(store.reader(), older.season_week).await.unwrap(),
354            [older]
355        );
356    }
357
358    #[tokio::test]
359    async fn season_week_rejects_rows_whose_classification_disagrees() {
360        let (_dir, store) = store().await;
361
362        // season_type is stored as the enum's numeric repr in a TEXT column, so
363        // '0' is what a regular-season row looks like on disk.
364        sqlx::query(
365            r#"INSERT INTO player_week_stats (season, week, season_type, gsis_id, team,
366                   completions, attempts, passing_yards, passing_tds, passing_interceptions,
367                   rushing_attempts, rushing_yards, rushing_tds, targets, receptions,
368                   receiving_yards, receiving_tds, fumbles_lost, two_point_conversions,
369                   special_teams_tds, fumble_recovery_tds)
370               VALUES (2025, 19, '0', '00-1', 'GB', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)"#,
371        )
372        .execute(&store.write)
373        .await
374        .unwrap();
375        let err = for_week(
376            store.reader(),
377            SeasonWeek::new(Season(2025), Week(19)).unwrap(),
378        )
379        .await;
380        assert!(
381            matches!(err, Err(NflDataError::Db(sqlx::Error::Decode(_)))),
382            "{err:?}"
383        );
384    }
385}