From 3acd78e76cf749e05cdf1147963abdd9ba61380e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kha=C3=AFs=20COLIN?= Date: Sun, 19 Oct 2025 19:31:00 +0200 Subject: [PATCH] added a Food:from_row impl --- src/main.rs | 44 +++++++++++++++++++------------------------- 1 file changed, 19 insertions(+), 25 deletions(-) diff --git a/src/main.rs b/src/main.rs index a6363c1..24964b4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,7 +9,7 @@ use axum::{ routing::{get, post}, }; use parking_lot::Mutex; -use rusqlite::{CachedStatement, Connection}; +use rusqlite::{CachedStatement, Connection, Row}; use tower_http::trace::TraceLayer; use tower_request_id::{RequestId, RequestIdLayer}; use tracing::{debug, error, info, info_span}; @@ -40,6 +40,22 @@ struct Food { color: String, } +impl Food { + fn from_row(row: &Row<'_>) -> rusqlite::Result { + { + Ok(Food { + id: row.get(0)?, + portion: row.get(1)?, + name: row.get(2)?, + kc_per_serving: row.get(3)?, + target_servings: row.get(4)?, + actual_servings: row.get(5)?, + color: row.get(6)?, + }) + } + } +} + #[derive(Clone)] struct PreparedStatements {} @@ -157,17 +173,7 @@ fn get_foods(conn: &ConnState) -> Vec { let conn = conn.lock(); let mut stmt = PreparedStatements::get_foods(&conn); let foods: Vec<_> = stmt - .query_map((), |row| { - Ok(Food { - id: row.get(0).unwrap(), - portion: row.get(1).unwrap(), - name: row.get(2).unwrap(), - kc_per_serving: row.get(3).unwrap(), - target_servings: row.get(4).unwrap(), - actual_servings: row.get(5).unwrap(), - color: row.get(6).unwrap(), - }) - }) + .query_map((), Food::from_row) .unwrap() .collect::>() .unwrap(); @@ -200,19 +206,7 @@ fn do_increase(conn: &Arc>, id: i32) { fn get_food(conn: &Arc>, id: i32) -> Food { let conn = conn.lock(); let mut stmt = PreparedStatements::get_food(&conn); - let food = stmt - .query_one((id,), |row| { - Ok(Food { - id: row.get(0).unwrap(), - portion: row.get(1).unwrap(), - name: row.get(2).unwrap(), - kc_per_serving: row.get(3).unwrap(), - target_servings: row.get(4).unwrap(), - actual_servings: row.get(5).unwrap(), - color: row.get(6).unwrap(), - }) - }) - .unwrap(); + let food = stmt.query_one((id,), Food::from_row).unwrap(); debug!(?food); food }