Skip to content
1        10        20        30        40        50        60        70        801use std::path::Path;2use std::sync::Arc;3use std::time::Duration;45use tokio::sync::OnceCell;6use turso::Builder;78pub mod invites;9pub mod migration;10pub mod session_store;11pub mod tickets;12pub mod users;1314#[derive(Clone)]15pub struct Database {16    db: Arc<OnceCell<turso::Database>>,17    db_path: String,18}1920impl Database {21    pub fn new(db_path: &str) -> Self {22        Self {23            db: Arc::new(OnceCell::new()),24            db_path: db_path.to_owned(),25        }26    }2728    #[cfg(test)]29    pub fn db_path(&self) -> &str {30        &self.db_path31    }3233    pub async fn conn(&self) -> Result<turso::Connection, String> {34        let db = self35            .db36            .get_or_try_init(|| async {37                let db_path = Path::new(&self.db_path);38                let parent = db_path.parent().unwrap_or(Path::new("."));39                if !parent.exists() {40                    log::info!("Creating parent directory: {}", parent.display());41                    std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;42                }4344                let db_path_str = db_path.to_str().ok_or_else(|| {45                    "Invalid database path: contains non-UTF8 characters".to_string()46                })?;4748                let db = Builder::new_local(db_path_str).build().await.map_err(|e| {49                    log::error!("Failed to create database: {e}");50                    e.to_string()51                })?;5253                log::info!("Created db");54                Ok::<turso::Database, String>(db)55            })56            .await?;5758        let conn = db59            .connect()60            .map_err(|e| format!("Failed to connect to database: {e}"))?;61        conn.busy_timeout(Duration::from_secs(30))62            .map_err(|e| format!("Failed to set busy timeout: {e}"))?;63        Ok(conn)64    }6566    pub async fn init(&self) -> Result<(), String> {67        self.create_tables().await?;6869        log::info!("Database initialized successfully");70        Ok(())71    }72}7374#[cfg(test)]75mod tests {76    use super::*;7778    #[test]79    fn test_database_new_stores_path() {80        let db = Database::new("/tmp/test_pear_new.db");81        assert_eq!(db.db_path(), "/tmp/test_pear_new.db");82    }8384    #[tokio::test]85    async fn test_database_init_creates_file() {86        let db_path = format!("/tmp/test_pear_init_{}.db", uuid::Uuid::new_v4());87        let db = Database::new(&db_path);8889        assert!(db.init().await.is_ok());90        assert!(std::path::Path::new(&db_path).exists());9192        let _ = std::fs::remove_file(&db_path);93    }94}