Skip to main content

nflverse_data/store/
team_stats.rs

1use sqlx::SqlitePool;
2
3use crate::error::NflDataError;
4use crate::model::{Season, SeasonType, SeasonWeek, TeamAbbr, TeamWeekStats, Week};
5use crate::store::Store;
6use crate::store::sync_state::{self, SyncedAsset};
7
8/// One `team_week_stats` row exactly as stored: decomposed identity plus the
9/// stored classification. The domain type carries a single [`SeasonWeek`], so
10/// reads go through this adapter, which validates the two against each other.
11struct Row {
12    season: Season,
13    week: Week,
14    season_type: SeasonType,
15    team: TeamAbbr,
16    opponent: TeamAbbr,
17    game_id: String,
18    sacks: u32,
19    interceptions: u32,
20    fumble_recoveries: u32,
21    safeties: u32,
22    touchdowns: u32,
23    blocked_kicks: u32,
24    conversion_returns: u32,
25    points_allowed: i32,
26}
27
28fn decode_error(message: String) -> sqlx::Error {
29    sqlx::Error::Decode(message.into())
30}
31
32impl TryFrom<Row> for TeamWeekStats {
33    type Error = sqlx::Error;
34
35    fn try_from(row: Row) -> Result<Self, Self::Error> {
36        let season_week = SeasonWeek::new(row.season, row.week)
37            .ok_or_else(|| decode_error(format!("invalid absolute week {}", row.week.0)))?;
38        let implied = if season_week.postseason() {
39            SeasonType::Post
40        } else {
41            SeasonType::Reg
42        };
43        if row.season_type != implied {
44            return Err(decode_error(format!(
45                "season type {:?} conflicts with absolute week {}",
46                row.season_type, season_week.week.0
47            )));
48        }
49        Ok(Self {
50            season_week,
51            team: row.team,
52            opponent: row.opponent,
53            game_id: row.game_id,
54            sacks: row.sacks,
55            interceptions: row.interceptions,
56            fumble_recoveries: row.fumble_recoveries,
57            safeties: row.safeties,
58            touchdowns: row.touchdowns,
59            blocked_kicks: row.blocked_kicks,
60            conversion_returns: row.conversion_returns,
61            points_allowed: row.points_allowed,
62        })
63    }
64}
65
66pub(crate) async fn replace(
67    store: &Store,
68    asset: &SyncedAsset<'_>,
69    season: Season,
70    stats: &[TeamWeekStats],
71) -> Result<u64, NflDataError> {
72    for s in stats {
73        debug_assert_eq!(
74            s.season_week.season, season,
75            "team week stats entry season must match the replace() season param"
76        );
77    }
78
79    store
80        .write_tx(async |conn| {
81            sqlx::query!("DELETE FROM team_week_stats WHERE season = ?", season)
82                .execute(&mut *conn)
83                .await?;
84            for s in stats {
85                let season_type = if s.season_week.postseason() {
86                    SeasonType::Post
87                } else {
88                    SeasonType::Reg
89                };
90                sqlx::query!(
91                    r#"INSERT INTO team_week_stats
92                       (season, week, season_type, team, opponent, game_id,
93                        sacks, interceptions, fumble_recoveries, safeties,
94                        touchdowns, blocked_kicks, conversion_returns, points_allowed)
95                       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"#,
96                    s.season_week.season,
97                    s.season_week.week,
98                    season_type,
99                    s.team,
100                    s.opponent,
101                    s.game_id,
102                    s.sacks,
103                    s.interceptions,
104                    s.fumble_recoveries,
105                    s.safeties,
106                    s.touchdowns,
107                    s.blocked_kicks,
108                    s.conversion_returns,
109                    s.points_allowed,
110                )
111                .execute(&mut *conn)
112                .await?;
113            }
114            sync_state::record(conn, asset).await?;
115            Ok(stats.len() as u64)
116        })
117        .await
118}
119
120/// One row per team for the week, read straight from the pbp-derived table —
121/// opponent and points_allowed were computed at ingest, so no joins.
122pub(crate) async fn for_week(
123    pool: &SqlitePool,
124    season_week: SeasonWeek,
125) -> Result<Vec<TeamWeekStats>, NflDataError> {
126    let rows = sqlx::query_as!(
127        Row,
128        r#"SELECT
129               season AS "season: Season",
130               week AS "week: Week",
131               season_type AS "season_type: SeasonType",
132               team AS "team: TeamAbbr",
133               opponent AS "opponent: TeamAbbr",
134               game_id,
135               sacks AS "sacks: u32",
136               interceptions AS "interceptions: u32",
137               fumble_recoveries AS "fumble_recoveries: u32",
138               safeties AS "safeties: u32",
139               touchdowns AS "touchdowns: u32",
140               blocked_kicks AS "blocked_kicks: u32",
141               conversion_returns AS "conversion_returns: u32",
142               points_allowed AS "points_allowed: i32"
143           FROM team_week_stats
144           WHERE season = ? AND week = ?
145           ORDER BY team, season_type"#,
146        season_week.season,
147        season_week.week
148    )
149    .fetch_all(pool)
150    .await?;
151
152    rows.into_iter()
153        .map(TeamWeekStats::try_from)
154        .collect::<Result<Vec<_>, _>>()
155        .map_err(NflDataError::from)
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161    use crate::store::sync_state::SyncedAsset;
162
163    fn row(team: &str, opp: &str) -> TeamWeekStats {
164        // Distinct primes so a positional INSERT swap fails the roundtrip.
165        TeamWeekStats {
166            season_week: SeasonWeek::new(Season(2025), Week(1)).unwrap(),
167            team: team.parse().unwrap(),
168            opponent: opp.parse().unwrap(),
169            game_id: "2025_01_AAA_BBB".into(),
170            sacks: 3,
171            interceptions: 5,
172            fumble_recoveries: 7,
173            safeties: 11,
174            touchdowns: 13,
175            blocked_kicks: 17,
176            conversion_returns: 19,
177            points_allowed: 23,
178        }
179    }
180
181    async fn store() -> (tempfile::TempDir, Store) {
182        let dir = tempfile::tempdir().unwrap();
183        let store = Store::open(&format!("sqlite://{}/t.db", dir.path().display()))
184            .await
185            .unwrap();
186        (dir, store)
187    }
188
189    fn asset(name: &str) -> SyncedAsset<'_> {
190        SyncedAsset {
191            release_tag: "pbp",
192            asset_name: name,
193            updated_at: "2026-06-30T10:36:16Z",
194        }
195    }
196
197    #[tokio::test]
198    async fn replace_then_for_week_roundtrips() {
199        let (_dir, store) = store().await;
200        let aaa = row("KC", "BUF");
201        replace(
202            &store,
203            &asset("play_by_play_2025.csv"),
204            Season(2025),
205            std::slice::from_ref(&aaa),
206        )
207        .await
208        .unwrap();
209        let back = for_week(store.reader(), aaa.season_week).await.unwrap();
210        assert_eq!(back, vec![aaa]);
211    }
212
213    #[tokio::test]
214    async fn season_week_roundtrips_postseason_weeks_in_full() {
215        let (_dir, store) = store().await;
216        let mut written = Vec::new();
217        for week in [18u8, 19, 22] {
218            let mut stats = row("KC", "BUF");
219            stats.season_week = SeasonWeek::new(Season(2025), Week(week)).unwrap();
220            stats.game_id = format!("2025_{week:02}_BUF_KC");
221            written.push(stats);
222        }
223        replace(
224            &store,
225            &asset("play_by_play_2025.csv"),
226            Season(2025),
227            &written,
228        )
229        .await
230        .unwrap();
231
232        for expected in &written {
233            let rows = for_week(store.reader(), expected.season_week)
234                .await
235                .unwrap();
236            assert_eq!(rows, std::slice::from_ref(expected));
237            assert_eq!(
238                rows[0].season_week.postseason(),
239                expected.season_week.week.0 > 18
240            );
241        }
242    }
243
244    #[tokio::test]
245    async fn season_week_scopes_reads_to_the_season() {
246        let (_dir, store) = store().await;
247        let mut older = row("KC", "BUF");
248        older.season_week = SeasonWeek::new(Season(2024), Week(1)).unwrap();
249        let mut newer = row("KC", "BUF");
250        newer.season_week = SeasonWeek::new(Season(2025), Week(1)).unwrap();
251        newer.points_allowed = 99;
252        replace(
253            &store,
254            &asset("play_by_play_2024.csv"),
255            Season(2024),
256            std::slice::from_ref(&older),
257        )
258        .await
259        .unwrap();
260        replace(
261            &store,
262            &asset("play_by_play_2025.csv"),
263            Season(2025),
264            std::slice::from_ref(&newer),
265        )
266        .await
267        .unwrap();
268
269        assert_eq!(
270            for_week(store.reader(), newer.season_week).await.unwrap(),
271            [newer]
272        );
273        assert_eq!(
274            for_week(store.reader(), older.season_week).await.unwrap(),
275            [older]
276        );
277    }
278
279    #[tokio::test]
280    async fn season_week_rejects_rows_whose_classification_disagrees() {
281        let (_dir, store) = store().await;
282        // season_type is stored as the enum's numeric repr in a TEXT column, so
283        // '1' is what a postseason row looks like on disk.
284        sqlx::query(
285            r#"INSERT INTO team_week_stats (season, week, season_type, team, opponent, game_id,
286                   sacks, interceptions, fumble_recoveries, safeties, touchdowns,
287                   blocked_kicks, conversion_returns, points_allowed)
288               VALUES (2025, 18, '1', 'KC', 'BUF', '2025_18_BUF_KC', 0, 0, 0, 0, 0, 0, 0, 0)"#,
289        )
290        .execute(&store.write)
291        .await
292        .unwrap();
293
294        let err = for_week(
295            store.reader(),
296            SeasonWeek::new(Season(2025), Week(18)).unwrap(),
297        )
298        .await;
299        assert!(
300            matches!(err, Err(NflDataError::Db(sqlx::Error::Decode(_)))),
301            "{err:?}"
302        );
303    }
304}