use std::sync::Arc;
pub use sqlx::{sqlite::SqlitePoolOptions, SqlitePool};
use crate::{StoreError, DEFAUTL_NAMESPACE_NAME};
use super::SqliteStore;
pub struct SqliteStoreBuilder {
uri: Option<String>,
pool: Option<Arc<SqlitePool>>,
table_name: Option<String>,
}
impl SqliteStoreBuilder {
pub fn new() -> Self {
Self {
uri: None,
pool: None,
table_name: None,
}
}
pub fn table_name<S: Into<String>>(mut self, table: S) -> Self {
self.table_name = Some(table.into());
self
}
pub fn uri<S: Into<String>>(mut self, uri: S) -> Self {
self.uri = Some(uri.into());
self
}
pub fn pool(mut self, pool: Arc<SqlitePool>) -> Self {
self.pool = Some(pool);
self
}
pub async fn build(self) -> Result<SqliteStore, StoreError> {
let pool = match self.pool {
Some(pool) => pool,
None => {
let uri = self
.uri
.expect("SqliteStore requires either a URI or an existing pool to be set");
Arc::new(SqlitePoolOptions::new().connect(&uri).await.map_err(|_| {
StoreError::ConnectionError("Failed to connect to the database".to_string())
})?)
}
};
let table_name = self.table_name.unwrap_or_else(|| {
log::warn!("Table name not set, using default table name");
DEFAUTL_NAMESPACE_NAME.to_string()
});
Ok(SqliteStore { pool, table_name })
}
}