make table strict, fix bug where app crashes on empty db

This commit is contained in:
Khaïs COLIN 2025-10-24 23:08:23 +02:00
parent a182e4e0cb
commit 18de2714d0
Signed by: logistic-bot
SSH key fingerprint: SHA256:RlpiqKeXpcPFZZ4y9Ou4xi2M8OhRJovIwDlbCaMsuAo
3 changed files with 5 additions and 9 deletions

BIN
foods.db

Binary file not shown.

View file

@ -6,4 +6,4 @@ CREATE TABLE IF NOT EXISTS food (
target_servings INTEGER NOT NULL DEFAULT 1, target_servings INTEGER NOT NULL DEFAULT 1,
actual_servings INTEGER NOT NULL DEFAULT 0, actual_servings INTEGER NOT NULL DEFAULT 0,
color TEXT NOT NULL DEFAULT 'white' color TEXT NOT NULL DEFAULT 'white'
); ) STRICT;

View file

@ -81,7 +81,6 @@ struct PreparedStatements {}
impl<'conn> PreparedStatements { impl<'conn> PreparedStatements {
fn check(conn: &Connection) -> rusqlite::Result<Self> { fn check(conn: &Connection) -> rusqlite::Result<Self> {
conn.prepare_cached(include_str!("create_tables.sql"))?;
conn.prepare_cached(include_str!("increase.sql"))?; conn.prepare_cached(include_str!("increase.sql"))?;
conn.prepare_cached(include_str!("decrease.sql"))?; conn.prepare_cached(include_str!("decrease.sql"))?;
conn.prepare_cached(include_str!("get_food.sql"))?; conn.prepare_cached(include_str!("get_food.sql"))?;
@ -91,11 +90,6 @@ impl<'conn> PreparedStatements {
Ok(PreparedStatements {}) Ok(PreparedStatements {})
} }
fn create_tables(conn: &'conn Connection) -> CachedStatement<'conn> {
conn.prepare_cached(include_str!("create_tables.sql"))
.expect("cached statement is invalid")
}
fn increase(conn: &'conn Connection) -> CachedStatement<'conn> { fn increase(conn: &'conn Connection) -> CachedStatement<'conn> {
conn.prepare_cached(include_str!("increase.sql")) conn.prepare_cached(include_str!("increase.sql"))
.expect("cached statement is invalid") .expect("cached statement is invalid")
@ -149,12 +143,14 @@ async fn main() -> Result<(), std::io::Error> {
let db_connecion_str = "./foods.db".to_string(); let db_connecion_str = "./foods.db".to_string();
debug!(db_connecion_str, "opening database"); debug!(db_connecion_str, "opening database");
let conn = Connection::open(db_connecion_str).expect("failed to open database"); let conn = Connection::open(db_connecion_str).expect("failed to open database");
PreparedStatements::check(&conn).expect("failed to prepare sql statements");
if let Err(e) = PreparedStatements::create_tables(&conn).execute(()) { if let Err(e) = conn.execute(include_str!("create_tables.sql"), ()) {
error!(?e, "failed to create tables"); error!(?e, "failed to create tables");
panic!("failed to create tables: {:#?}", e); panic!("failed to create tables: {:#?}", e);
} }
PreparedStatements::check(&conn).expect("failed to prepare sql statements");
let app = Router::new() let app = Router::new()
.route("/", get(root)) .route("/", get(root))
.route("/increase/{id}", post(increase)) .route("/increase/{id}", post(increase))