Skip to main content

meal_planner/
store.rs

1//! SQLite storage bootstrap and Meal Planner persistence boundary.
2mod household;
3#[cfg(test)]
4mod household_tests;
5mod migrations;
6mod plans;
7mod recipes;
8mod school_menus;
9mod shopping_lists;
10#[cfg(test)]
11mod tests;
12
13use crate::{MealPlannerConfig, MealPlannerError};
14use rusqlite::Connection;
15use std::{
16    sync::{Arc, Mutex},
17    time::Duration,
18};
19
20/// Shared SQLite connection for Meal Planner persistence operations.
21#[derive(Clone)]
22pub struct MealPlannerStore {
23    pub(super) connection: Arc<Mutex<Connection>>,
24}
25
26impl MealPlannerStore {
27    /// Open the configured database, creating its parent directory if necessary.
28    pub fn open(config: &MealPlannerConfig) -> Result<Self, MealPlannerError> {
29        let path = config.database_path();
30        if let Some(parent) = path
31            .parent()
32            .filter(|parent| !parent.as_os_str().is_empty())
33        {
34            std::fs::create_dir_all(parent)?;
35        }
36        Self::from_connection(Connection::open(path)?)
37    }
38
39    /// Create an isolated in-memory database for tests.
40    pub fn open_in_memory() -> Result<Self, MealPlannerError> {
41        Self::from_connection(Connection::open_in_memory()?)
42    }
43
44    pub fn health_check(&self) -> Result<(), MealPlannerError> {
45        let connection = self
46            .connection
47            .lock()
48            .map_err(|_| MealPlannerError::LockPoisoned)?;
49        connection.query_row("SELECT 1", [], |row| row.get::<_, i64>(0))?;
50        Ok(())
51    }
52
53    pub fn schema_version(&self) -> Result<i64, MealPlannerError> {
54        let connection = self
55            .connection
56            .lock()
57            .map_err(|_| MealPlannerError::LockPoisoned)?;
58        Ok(connection.pragma_query_value(None, "user_version", |row| row.get(0))?)
59    }
60
61    fn from_connection(mut connection: Connection) -> Result<Self, MealPlannerError> {
62        connection.busy_timeout(Duration::from_secs(5))?;
63        connection.execute_batch("PRAGMA foreign_keys = ON;")?;
64        migrations::apply(&mut connection)?;
65        Ok(Self {
66            connection: Arc::new(Mutex::new(connection)),
67        })
68    }
69}