use std::{error::Error, path::PathBuf, sync::Arc}; use async_trait::async_trait; use crate::{ ConfigInfoType, containers::db::{DBConfigInfoType, DBInfo, PreExistingDBInfo, UnStartedContainer}, util::to_absolute_path, }; #[derive(Clone)] pub struct ContainerConfig { // Add any SQLite-specific configuration options here if needed pub database_name: String, pub absolute_dir_path: PathBuf, } #[derive(Default)] pub struct OptionalContainerConfig { // Add any optional configuration fields here pub database_name: Option, pub absolute_path: Option, } impl OptionalContainerConfig { pub fn fill_with(&self, other: &ContainerConfig) -> ContainerConfig { ContainerConfig { database_name: self .database_name .clone() .unwrap_or_else(|| other.database_name.clone()), absolute_dir_path: self .absolute_path .clone() .unwrap_or_else(|| other.absolute_dir_path.clone()), } } } pub fn get_default_config() -> ContainerConfig { ContainerConfig { database_name: "sqlite".to_string(), absolute_dir_path: to_absolute_path("./generated/sqlite"), } } pub struct SQLiteContainer { pub config: ContainerConfig, } impl SQLiteContainer { fn get_db_absolute_path(&self) -> PathBuf { self.config .absolute_dir_path .join(&self.config.database_name) .with_extension("db") } } #[async_trait] impl DBInfo for SQLiteContainer { async fn get_db_container_config_info(&self) -> DBConfigInfoType { // sqlite filepath url does not include the "sqlite://" prefix let sqlite_url = format!("sqlite://{}", self.get_db_absolute_path().to_string_lossy()); // create the file std::fs::create_dir_all(&self.config.absolute_dir_path) .expect("Failed to create directories for SQLite database"); std::fs::File::create(self.get_db_absolute_path()) .expect("Failed to create SQLite database file"); // ConfigInfoType::PreExisting(PreExistingDBInfo { db_type: crate::containers::db::DBType::SQLite, url: sqlite_url, on_delete: { let db_path = self.get_db_absolute_path(); Arc::new(move || { // delete the sqlite database file if db_path.exists() && let Err(e) = std::fs::remove_file(&db_path) { eprintln!("Failed to delete SQLite database file: {}", e); } }) }, }) } async fn new(user_default_config: Option) -> Self where Self: Sized, { let default_config = get_default_config(); let config = user_default_config .unwrap_or_default() .fill_with(&default_config); SQLiteContainer { config: config.clone(), } } fn get_unstarted_container(&self) -> Result> { Err(Box::new(std::io::Error::other( "SQLite does not use a container", ))) } }