added a Food:from_row impl

This commit is contained in:
Khaïs COLIN 2025-10-19 19:31:00 +02:00
parent 080bb80956
commit 3acd78e76c
Signed by: logistic-bot
SSH key fingerprint: SHA256:RlpiqKeXpcPFZZ4y9Ou4xi2M8OhRJovIwDlbCaMsuAo

View file

@ -9,7 +9,7 @@ use axum::{
routing::{get, post}, routing::{get, post},
}; };
use parking_lot::Mutex; use parking_lot::Mutex;
use rusqlite::{CachedStatement, Connection}; use rusqlite::{CachedStatement, Connection, Row};
use tower_http::trace::TraceLayer; use tower_http::trace::TraceLayer;
use tower_request_id::{RequestId, RequestIdLayer}; use tower_request_id::{RequestId, RequestIdLayer};
use tracing::{debug, error, info, info_span}; use tracing::{debug, error, info, info_span};
@ -40,6 +40,22 @@ struct Food {
color: String, color: String,
} }
impl Food {
fn from_row(row: &Row<'_>) -> rusqlite::Result<Self> {
{
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)] #[derive(Clone)]
struct PreparedStatements {} struct PreparedStatements {}
@ -157,17 +173,7 @@ fn get_foods(conn: &ConnState) -> Vec<Food> {
let conn = conn.lock(); let conn = conn.lock();
let mut stmt = PreparedStatements::get_foods(&conn); let mut stmt = PreparedStatements::get_foods(&conn);
let foods: Vec<_> = stmt let foods: Vec<_> = stmt
.query_map((), |row| { .query_map((), Food::from_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() .unwrap()
.collect::<Result<_, _>>() .collect::<Result<_, _>>()
.unwrap(); .unwrap();
@ -200,19 +206,7 @@ fn do_increase(conn: &Arc<Mutex<Connection>>, id: i32) {
fn get_food(conn: &Arc<Mutex<Connection>>, id: i32) -> Food { fn get_food(conn: &Arc<Mutex<Connection>>, id: i32) -> Food {
let conn = conn.lock(); let conn = conn.lock();
let mut stmt = PreparedStatements::get_food(&conn); let mut stmt = PreparedStatements::get_food(&conn);
let food = stmt let food = stmt.query_one((id,), Food::from_row).unwrap();
.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();
debug!(?food); debug!(?food);
food food
} }