diff --git a/foods.db b/foods.db index 035d690..a769939 100644 Binary files a/foods.db and b/foods.db differ diff --git a/src/main.rs b/src/main.rs index 138f75a..56f3ad2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -87,6 +87,7 @@ impl<'conn> PreparedStatements { conn.prepare_cached(include_str!("get_food.sql"))?; conn.prepare_cached(include_str!("get_foods.sql"))?; conn.prepare_cached(include_str!("get_sum.sql"))?; + conn.prepare_cached(include_str!("set.sql"))?; Ok(PreparedStatements {}) } @@ -119,6 +120,11 @@ impl<'conn> PreparedStatements { conn.prepare_cached(include_str!("get_sum.sql")) .expect("cached statement is invalid") } + + fn set(conn: &'conn Connection) -> CachedStatement<'conn> { + conn.prepare_cached(include_str!("set.sql")) + .expect("cached statement is invalid") + } } type ConnState = Arc>; @@ -153,6 +159,7 @@ async fn main() -> Result<(), std::io::Error> { .route("/", get(root)) .route("/increase/{id}", post(increase)) .route("/decrease/{id}", post(decrease)) + .route("/set/{id}/to/{amount}", post(set)) .layer( TraceLayer::new_for_http().make_span_with(|request: &Request<_>| { let matched_path = request @@ -285,3 +292,27 @@ async fn decrease( .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?, )) } + +fn do_set(conn: &Arc>, id: i32, amount: i32) -> rusqlite::Result<()> { + let conn = conn.lock(); + let mut stmt = PreparedStatements::set(&conn); + let new: i32 = stmt.query_one((id, amount), |row| row.get(0))?; + debug!(id, new_serving_count = new, "set"); + Ok(()) +} + +async fn set( + State(conn): State>>, + Path((id, amount)): Path<(i32, i32)>, +) -> Result, StatusCode> { + do_set(&conn, id, amount).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let food = get_food(&conn, id).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let sum = get_sum(&conn).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let date = get_date(); + let update = FoodUpdateTemplate { food, sum, date }; + Ok(Html( + update + .render() + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?, + )) +} diff --git a/src/set.sql b/src/set.sql new file mode 100644 index 0000000..6830998 --- /dev/null +++ b/src/set.sql @@ -0,0 +1,8 @@ +UPDATE + food +SET + actual_servings = MAX(?2, 0) +WHERE + id = ?1 +RETURNING + actual_servings diff --git a/templates/food.html b/templates/food.html index 8472399..3a0fe85 100644 --- a/templates/food.html +++ b/templates/food.html @@ -20,17 +20,17 @@ {% if loop.index as i32 <= food.target_servings %} {% else %} {% endif %}