use crate::storage::error::StorageError;
use std::path::{Path, PathBuf};
pub struct Storage {
data_dir: PathBuf,
}
impl Storage {
pub fn new(data_dir: impl Into<PathBuf>) -> Result<Self, StorageError> {
let data_dir = data_dir.into();
if !data_dir.exists() {
return Err(StorageError::DirectoryNotFound(data_dir));
}
Ok(Self { data_dir })
}
pub fn new_or_create(data_dir: impl Into<PathBuf>) -> Result<Self, StorageError> {
let data_dir = data_dir.into();
if !data_dir.exists() {
std::fs::create_dir_all(&data_dir).map_err(|e| StorageError::io(&data_dir, e))?;
}
Ok(Self { data_dir })
}
pub fn data_dir(&self) -> &Path {
&self.data_dir
}
pub fn database_path(&self, db_name: &str) -> PathBuf {
self.data_dir.join(db_name)
}
pub fn database_dir_exists(&self, db_name: &str) -> bool {
self.database_path(db_name).exists()
}
pub fn schema_path(&self, db_name: &str, schema_name: &str) -> PathBuf {
self.database_path(db_name).join(schema_name)
}
pub fn schema_dir_exists(&self, db_name: &str, schema_name: &str) -> bool {
self.schema_path(db_name, schema_name).exists()
}
pub fn table_path(&self, db: &str, schema: &str, table: &str) -> Result<PathBuf, StorageError> {
if !self.database_dir_exists(db) {
return Err(StorageError::DirectoryNotFound(self.database_path(db)));
}
if !self.schema_dir_exists(db, schema) {
return Err(StorageError::DirectoryNotFound(
self.schema_path(db, schema),
));
}
Ok(self.schema_path(db, schema).join(format!("{}.dat", table)))
}
}