diff --git a/Cargo.toml b/Cargo.toml index 369aca84..ff027b29 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,10 +13,10 @@ [features] default = [ # Storages - "sled-storage", - "csv-storage", - "sheet-storage", - "memory-storage", + "sled-database", + "csv-database", + "sheet-database", + "memory-database", # Functionality "alter-table", "auto-increment", @@ -25,10 +25,10 @@ ] # Storages - sled-storage = ["sled", "bincode"] - csv-storage = ["csv", "linecount"] - sheet-storage = ["umya-spreadsheet"] - memory-storage = [] + sled-database = ["sled", "bincode"] + csv-database = ["csv", "linecount"] + sheet-database = ["umya-spreadsheet"] + memory-database = [] # Functionality alter-table = [] diff --git a/src/data/index.rs b/src/data/index.rs index c637907d..cf1a03fd 100644 --- a/src/data/index.rs +++ b/src/data/index.rs @@ -1,5 +1,5 @@ use { - crate::{result::Result, Column, Ingredient, Method, Recipe, StorageInner, Value}, + crate::{result::Result, Column, DatabaseInner, Ingredient, Method, Recipe, Value}, rayon::prelude::*, serde::{Deserialize, Serialize}, std::{cmp::Ordering, collections::HashMap}, @@ -30,7 +30,7 @@ impl Index { } pub async fn reset( &self, - storage: &mut StorageInner, + storage: &mut DatabaseInner, table: &str, columns: &[Column], ) -> Result<()> { diff --git a/src/data/schema.rs b/src/data/schema.rs index 05d449d2..0865c262 100644 --- a/src/data/schema.rs +++ b/src/data/schema.rs @@ -148,7 +148,7 @@ impl SchemaDiff { changes.push(RenameTable(table_name.clone())) } if let Some(column_defs) = &self.column_defs { - for (index, column_def) in column_defs.into_iter() { + for (index, column_def) in column_defs.iter() { match (index, column_def) { (None, None) => (), (Some(index), Some(column_def)) => { @@ -164,7 +164,7 @@ impl SchemaDiff { } } if let Some(indexes) = &self.indexes { - for (index, index_def) in indexes.into_iter() { + for (index, index_def) in indexes.iter() { match (index, index_def) { (None, None) => (), (Some(index), Some(index_def)) => { diff --git a/src/store/auto_increment.rs b/src/database/auto_increment.rs similarity index 75% rename from src/store/auto_increment.rs rename to src/database/auto_increment.rs index e0aa56c2..30200d1a 100644 --- a/src/store/auto_increment.rs +++ b/src/database/auto_increment.rs @@ -1,4 +1,7 @@ -use {super::StorageError, crate::Result, async_trait::async_trait}; +use { + crate::{DatabaseError, Result}, + async_trait::async_trait, +}; #[async_trait(?Send)] pub trait AutoIncrement { @@ -16,7 +19,7 @@ pub trait AutoIncrement { /*start_value*/ i64, )>, > { - Err(StorageError::Unimplemented.into()) + Err(DatabaseError::Unimplemented.into()) } async fn set_increment_value( @@ -25,6 +28,6 @@ pub trait AutoIncrement { _column_name: &str, _end: i64, ) -> Result<()> { - Err(StorageError::Unimplemented.into()) + Err(DatabaseError::Unimplemented.into()) } } diff --git a/src/store/store.rs b/src/database/base.rs similarity index 63% rename from src/store/store.rs rename to src/database/base.rs index 7d60673e..3918b423 100644 --- a/src/store/store.rs +++ b/src/database/base.rs @@ -1,20 +1,20 @@ use { - crate::{IndexFilter, Plane, Result, Schema, StorageError, Value}, + crate::{DatabaseError, IndexFilter, Plane, Result, Schema, Value}, async_trait::async_trait, }; /// `Store` -> `SELECT` #[async_trait(?Send)] -pub trait Store { +pub trait DBBase { async fn fetch_schema(&self, _table_name: &str) -> Result> { - Err(StorageError::Unimplemented.into()) + Err(DatabaseError::Unimplemented.into()) } async fn scan_schemas(&self) -> Result> { - Err(StorageError::Unimplemented.into()) + Err(DatabaseError::Unimplemented.into()) } async fn scan_data(&self, _table_name: &str) -> Result { - Err(StorageError::Unimplemented.into()) + Err(DatabaseError::Unimplemented.into()) } async fn scan_data_indexed( @@ -22,13 +22,13 @@ pub trait Store { _table_name: &str, _index_filters: IndexFilter, ) -> Result { - Err(StorageError::Unimplemented.into()) + Err(DatabaseError::Unimplemented.into()) } async fn scan_index( &self, _table_name: &str, _index_filter: IndexFilter, ) -> Result> { - Err(StorageError::Unimplemented.into()) + Err(DatabaseError::Unimplemented.into()) } } diff --git a/src/database/mod.rs b/src/database/mod.rs new file mode 100644 index 00000000..75c170ef --- /dev/null +++ b/src/database/mod.rs @@ -0,0 +1,99 @@ +mod auto_increment; +mod base; +mod mutable; + +use std::sync::{Mutex, MutexGuard}; +use { + crate::Result, + serde::{Deserialize, Serialize}, + std::fmt::Debug, + thiserror::Error, +}; + +pub use {auto_increment::AutoIncrement, base::DBBase, mutable::DBMut}; + +#[derive(Error, Serialize, Debug, PartialEq)] +pub enum DatabaseError { + #[error("this database has not yet implemented this method")] + Unimplemented, + #[error("tried to connect to an unknown database")] + UnknownConnection, + #[error("table not found")] + TableNotFound, +} + +#[derive(Serialize, Deserialize)] +pub enum Connection { + Unknown, + #[cfg(feature = "memory-database")] + Memory, + #[cfg(feature = "sled-database")] + Sled(String), + #[cfg(feature = "csv-database")] + CSV(String, crate::CSVSettings), + #[cfg(feature = "sheet-database")] + Sheet(String), +} +impl Default for Connection { + fn default() -> Self { + Connection::Unknown + } +} +impl TryFrom for Database { + type Error = crate::Error; + fn try_from(connection: Connection) -> Result { + use { + crate::{CSVDatabase, MemoryDatabase, SheetDatabase, SledDatabase}, + Connection::*, + }; + let database: Mutex> = Mutex::new(match &connection { + #[cfg(feature = "memory-database")] + Memory => Box::new(MemoryDatabase::new()), + #[cfg(feature = "sled-database")] + Sled(path) => Box::new(SledDatabase::new(path)?), + #[cfg(feature = "csv-database")] + CSV(path, settings) => Box::new(CSVDatabase::new_with_settings(path, settings.clone())?), + #[cfg(feature = "sheet-database")] + Sheet(path) => Box::new(SheetDatabase::new(path)?), + Unknown => return Err(DatabaseError::UnknownConnection.into()), + }); + Ok(Database { + database, + source_connection: connection, + }) + } +} + +pub struct Database { + source_connection: Connection, + database: Mutex>, +} +impl Database { + pub fn new(database: Box) -> Self { + let database = Mutex::new(database); + Self { + database, + source_connection: Connection::default(), + } + } + pub fn get(&self) -> MutexGuard> { + self.database + .lock() + .expect("Unreachable: Database wasn't replaced!") + } + pub fn get_mut(&mut self) -> &mut Box { + self.database + .get_mut() + .expect("Unreachable: Database wasn't replaced!") + } + pub fn into_source(self) -> Connection { + self.source_connection + } + pub fn from_source(connection: Connection) -> Result { + connection.try_into() + } +} + +pub type DatabaseInner = dyn DBFull; + +pub trait DBFull: DBBase + DBMut + AutoIncrement {} diff --git a/src/store/store_mut.rs b/src/database/mutable.rs similarity index 67% rename from src/store/store_mut.rs rename to src/database/mutable.rs index b85b6e98..722c0456 100644 --- a/src/store/store_mut.rs +++ b/src/database/mutable.rs @@ -1,29 +1,29 @@ use { - crate::{Result, Row, Schema, SchemaDiff, StorageError, Value}, + crate::{DatabaseError, Result, Row, Schema, SchemaDiff, Value}, async_trait::async_trait, }; /// `StoreMut` -> `INSERT`, `CREATE`, `DELETE`, `DROP`, `UPDATE` #[async_trait(?Send)] -pub trait StoreMut { +pub trait DBMut { async fn insert_schema(&mut self, _schema: &Schema) -> Result<()> { - Err(StorageError::Unimplemented.into()) + Err(DatabaseError::Unimplemented.into()) } async fn delete_schema(&mut self, _table_name: &str) -> Result<()> { - Err(StorageError::Unimplemented.into()) + Err(DatabaseError::Unimplemented.into()) } // Shouldn't this be AlterTable? async fn insert_data(&mut self, _table_name: &str, _rows: Vec) -> Result<()> { - Err(StorageError::Unimplemented.into()) + Err(DatabaseError::Unimplemented.into()) } async fn update_data(&mut self, _table_name: &str, _rows: Vec<(Value, Row)>) -> Result<()> { - Err(StorageError::Unimplemented.into()) + Err(DatabaseError::Unimplemented.into()) } async fn delete_data(&mut self, _table_name: &str, _keys: Vec) -> Result<()> { - Err(StorageError::Unimplemented.into()) + Err(DatabaseError::Unimplemented.into()) } async fn update_index( @@ -32,10 +32,10 @@ pub trait StoreMut { _table_name: &str, _keys: Vec<(Value, Value)>, ) -> Result<()> { - Err(StorageError::Unimplemented.into()) + Err(DatabaseError::Unimplemented.into()) } async fn alter_table(&mut self, _table_name: &str, _schema_diff: SchemaDiff) -> Result<()> { - Err(StorageError::Unimplemented.into()) + Err(DatabaseError::Unimplemented.into()) } } diff --git a/src/storages/csv_storage/auto_increment.rs b/src/databases/csv/auto_increment.rs similarity index 93% rename from src/storages/csv_storage/auto_increment.rs rename to src/databases/csv/auto_increment.rs index 2823139e..25059c8e 100644 --- a/src/storages/csv_storage/auto_increment.rs +++ b/src/databases/csv/auto_increment.rs @@ -1,12 +1,12 @@ use { - super::CSVStorage, + super::CSVDatabase, crate::{AutoIncrement, Result, WIPError}, async_trait::async_trait, linecount::count_lines, }; #[async_trait(?Send)] -impl AutoIncrement for CSVStorage { +impl AutoIncrement for CSVDatabase { async fn generate_increment_values( &mut self, _table_name: String, diff --git a/src/storages/csv_storage/store.rs b/src/databases/csv/base.rs similarity index 87% rename from src/storages/csv_storage/store.rs rename to src/databases/csv/base.rs index 19f84d09..59deebc1 100644 --- a/src/storages/csv_storage/store.rs +++ b/src/databases/csv/base.rs @@ -1,11 +1,11 @@ use { - super::{utils::csv_reader, CSVStorage}, - crate::{Plane, Result, Row, Schema, Store, Value, WIPError}, + super::{utils::csv_reader, CSVDatabase}, + crate::{DBBase, Plane, Result, Row, Schema, Value, WIPError}, async_trait::async_trait, }; #[async_trait(?Send)] -impl Store for CSVStorage { +impl DBBase for CSVDatabase { async fn fetch_schema(&self, _table_name: &str) -> Result> { Ok(self.schema.clone()) } diff --git a/src/storages/csv_storage/mod.rs b/src/databases/csv/mod.rs similarity index 86% rename from src/storages/csv_storage/mod.rs rename to src/databases/csv/mod.rs index 7229cc5b..340ffc1c 100644 --- a/src/storages/csv_storage/mod.rs +++ b/src/databases/csv/mod.rs @@ -1,10 +1,10 @@ mod auto_increment; -mod store; -mod store_mut; +mod base; +mod mutable; mod utils; use { - crate::{data::Schema, Column, FullStorage, Result, Storage, ValueType, WIPError}, + crate::{data::Schema, Column, DBFull, Database, Result, ValueType, WIPError}, csv::ReaderBuilder, serde::{Deserialize, Serialize}, std::{ @@ -16,12 +16,12 @@ use { }; #[derive(Error, Serialize, Debug, PartialEq)] -pub enum CSVStorageError { +pub enum CSVDatabaseError { #[error("CSV storages only support one table at a time")] OnlyOneTableAllowed, } -pub struct CSVStorage { +pub struct CSVDatabase { schema: Option, path: String, pub csv_settings: CSVSettings, @@ -40,14 +40,14 @@ impl Default for CSVSettings { } } -impl FullStorage for CSVStorage {} +impl DBFull for CSVDatabase {} -impl Storage { - pub fn new_csv(storage: CSVStorage) -> Self { +impl Database { + pub fn new_csv(storage: CSVDatabase) -> Self { Self::new(Box::new(storage)) } } -impl CSVStorage { +impl CSVDatabase { pub fn new(path: &str) -> Result { Self::new_with_settings(path, CSVSettings::default()) } diff --git a/src/storages/csv_storage/store_mut.rs b/src/databases/csv/mutable.rs similarity index 92% rename from src/storages/csv_storage/store_mut.rs rename to src/databases/csv/mutable.rs index 4d7dd1f6..adb3b484 100644 --- a/src/storages/csv_storage/store_mut.rs +++ b/src/databases/csv/mutable.rs @@ -1,16 +1,16 @@ use { - super::{CSVStorage, CSVStorageError}, - crate::{Cast, Result, Row, Schema, StoreMut, WIPError}, + super::{CSVDatabase, CSVDatabaseError}, + crate::{Cast, DBMut, Result, Row, Schema, WIPError}, async_trait::async_trait, csv::WriterBuilder, std::{fs::OpenOptions, io::Write}, }; #[async_trait(?Send)] -impl StoreMut for CSVStorage { +impl DBMut for CSVDatabase { async fn insert_schema(&mut self, schema: &Schema) -> Result<()> { if self.schema.is_some() { - return Err(CSVStorageError::OnlyOneTableAllowed.into()); + return Err(CSVDatabaseError::OnlyOneTableAllowed.into()); } let mut writer = WriterBuilder::new() diff --git a/src/storages/csv_storage/utils.rs b/src/databases/csv/utils.rs similarity index 72% rename from src/storages/csv_storage/utils.rs rename to src/databases/csv/utils.rs index 1c6aa985..463ea305 100644 --- a/src/storages/csv_storage/utils.rs +++ b/src/databases/csv/utils.rs @@ -1,11 +1,11 @@ use { - super::CSVStorage, + super::CSVDatabase, crate::{Result, WIPError}, csv::{Reader, ReaderBuilder}, std::fs::File, }; -pub(crate) fn csv_reader(store: &CSVStorage) -> Result> { +pub(crate) fn csv_reader(store: &CSVDatabase) -> Result> { let reader = ReaderBuilder::new() .delimiter(store.csv_settings.delimiter) .quoting(store.csv_settings.quoting) @@ -15,7 +15,7 @@ pub(crate) fn csv_reader(store: &CSVStorage) -> Result> { Ok(reader) } -/*pub(crate) fn csv_writer(store: &CSVStorage, init: T) -> Result> { +/*pub(crate) fn csv_writer(store: &CSVDatabase, init: T) -> Result> { let writer = WriterBuilder::new().delimiter(store.csv_settings.delimiter).from_writer(init); Ok(writer) diff --git a/src/storages/memory/auto_increment.rs b/src/databases/memory/auto_increment.rs similarity index 86% rename from src/storages/memory/auto_increment.rs rename to src/databases/memory/auto_increment.rs index e015785d..3cfed1db 100644 --- a/src/storages/memory/auto_increment.rs +++ b/src/databases/memory/auto_increment.rs @@ -1,10 +1,10 @@ use { - crate::{AutoIncrement, MemoryStorage, Result}, + crate::{AutoIncrement, MemoryDatabase, Result}, async_trait::async_trait, }; #[async_trait(?Send)] -impl AutoIncrement for MemoryStorage { +impl AutoIncrement for MemoryDatabase { async fn generate_increment_values( &mut self, table_name: String, diff --git a/src/storages/memory/store.rs b/src/databases/memory/base.rs similarity index 91% rename from src/storages/memory/store.rs rename to src/databases/memory/base.rs index 120421b3..2ff0d6b1 100644 --- a/src/storages/memory/store.rs +++ b/src/databases/memory/base.rs @@ -3,12 +3,14 @@ use std::collections::{BTreeMap, HashMap}; use crate::{join_iters, JoinType, Row}; use { - crate::{IndexFilter, MemoryStorage, MemoryStorageError, Plane, Result, Schema, Store, Value}, + crate::{ + DBBase, IndexFilter, MemoryDatabase, MemoryDatabaseError, Plane, Result, Schema, Value, + }, async_trait::async_trait, }; #[async_trait(?Send)] -impl Store for MemoryStorage { +impl DBBase for MemoryDatabase { async fn fetch_schema(&self, table_name: &str) -> Result> { Ok(self.tables.get(&table_name.to_string()).cloned()) } @@ -20,7 +22,7 @@ impl Store for MemoryStorage { self.data .get(&table_name.to_string()) .cloned() - .ok_or(MemoryStorageError::TableNotFound.into()) + .ok_or(MemoryDatabaseError::TableNotFound.into()) .map(|rows| rows.into_iter().collect()) } diff --git a/src/storages/memory/mod.rs b/src/databases/memory/mod.rs similarity index 71% rename from src/storages/memory/mod.rs rename to src/databases/memory/mod.rs index 27116413..a9727962 100644 --- a/src/storages/memory/mod.rs +++ b/src/databases/memory/mod.rs @@ -1,9 +1,9 @@ mod auto_increment; -mod store; -mod store_mut; +mod base; +mod mutable; use { - crate::{store::*, Row, Schema, Value}, + crate::{database::*, Row, Schema, Value}, serde::Serialize, std::{ collections::{BTreeMap, HashMap}, @@ -13,21 +13,21 @@ use { }; #[derive(Error, Serialize, Debug, PartialEq)] -pub enum MemoryStorageError { +pub enum MemoryDatabaseError { #[error("table not found")] TableNotFound, } #[derive(Default, Clone)] -pub struct MemoryStorage { +pub struct MemoryDatabase { tables: HashMap, data: HashMap>, indexes: HashMap>>, } -impl FullStorage for MemoryStorage {} +impl DBFull for MemoryDatabase {} -impl MemoryStorage { +impl MemoryDatabase { pub fn new() -> Self { Self::default() } diff --git a/src/storages/memory/store_mut.rs b/src/databases/memory/mutable.rs similarity index 93% rename from src/storages/memory/store_mut.rs rename to src/databases/memory/mutable.rs index 21398eec..6e649f8d 100644 --- a/src/storages/memory/store_mut.rs +++ b/src/databases/memory/mutable.rs @@ -1,12 +1,12 @@ use std::collections::HashMap; use { - crate::{MemoryStorage, Result, Row, Schema, StoreMut, Value}, + crate::{DBMut, MemoryDatabase, Result, Row, Schema, Value}, async_trait::async_trait, }; #[async_trait(?Send)] -impl StoreMut for MemoryStorage { +impl DBMut for MemoryDatabase { async fn insert_schema(&mut self, schema: &Schema) -> Result<()> { let table_name = schema.table_name.clone(); self.data.insert(table_name.clone(), HashMap::new()); diff --git a/src/databases/mod.rs b/src/databases/mod.rs new file mode 100644 index 00000000..64a71bf0 --- /dev/null +++ b/src/databases/mod.rs @@ -0,0 +1,19 @@ +#[cfg(feature = "sled-database")] +mod sled; +#[cfg(feature = "sled-database")] +pub use self::sled::SledDatabase; + +#[cfg(feature = "csv-database")] +mod csv; +#[cfg(feature = "csv-database")] +pub use self::csv::{CSVDatabase, CSVDatabaseError, CSVSettings}; + +#[cfg(feature = "sheet-database")] +mod sheet; +#[cfg(feature = "sheet-database")] +pub use self::sheet::{SheetDatabase, SheetDatabaseError}; + +#[cfg(feature = "memory-database")] +mod memory; +#[cfg(feature = "memory-database")] +pub use self::memory::{MemoryDatabase, MemoryDatabaseError}; diff --git a/src/storages/sheet_storage/auto_increment.rs b/src/databases/sheet/auto_increment.rs similarity index 77% rename from src/storages/sheet_storage/auto_increment.rs rename to src/databases/sheet/auto_increment.rs index c21e3de2..00860218 100644 --- a/src/storages/sheet_storage/auto_increment.rs +++ b/src/databases/sheet/auto_increment.rs @@ -1,10 +1,10 @@ use { - crate::{store::*, Result, SheetStorage, SheetStorageError}, + crate::{AutoIncrement, Result, SheetDatabase, SheetDatabaseError}, async_trait::async_trait, }; #[async_trait(?Send)] -impl AutoIncrement for SheetStorage { +impl AutoIncrement for SheetDatabase { async fn generate_increment_values( &mut self, sheet_name: String, @@ -13,7 +13,7 @@ impl AutoIncrement for SheetStorage { let sheet = self .book .get_sheet_by_name_mut(&sheet_name) - .map_err(|_| SheetStorageError::FailedToGetSheet)?; + .map_err(|_| SheetDatabaseError::FailedToGetSheet)?; let row_init = sheet.get_row_dimensions().len(); Ok(columns .into_iter() diff --git a/src/storages/sheet_storage/store.rs b/src/databases/sheet/base.rs similarity index 93% rename from src/storages/sheet_storage/store.rs rename to src/databases/sheet/base.rs index 37e2295e..2951f2d4 100644 --- a/src/storages/sheet_storage/store.rs +++ b/src/databases/sheet/base.rs @@ -1,13 +1,13 @@ -use crate::StorageError; +use crate::DatabaseError; use { - crate::{Cast, Column, Plane, Result, Row, Schema, SheetStorage, Store, Value}, + crate::{Cast, Column, DBBase, Plane, Result, Row, Schema, SheetDatabase, Value}, async_trait::async_trait, std::convert::TryFrom, umya_spreadsheet::{Cell, Worksheet}, }; #[async_trait(?Send)] -impl Store for SheetStorage { +impl DBBase for SheetDatabase { async fn fetch_schema(&self, sheet_name: &str) -> Result> { if let Ok(sheet) = self.book.get_sheet_by_name(sheet_name) { schema_from_sheet(sheet).map(Some) @@ -71,7 +71,7 @@ impl TryFrom for Value { Cell::TYPE_BOOL => Value::Bool(Value::Str(cell.get_value().to_string()).cast()?), Cell::TYPE_NUMERIC => Value::F64(Value::Str(cell.get_value().to_string()).cast()?), Cell::TYPE_NULL => Value::Null, - _ => return Err(StorageError::Unimplemented.into()), + _ => return Err(DatabaseError::Unimplemented.into()), }) } } diff --git a/src/storages/sheet_storage/mod.rs b/src/databases/sheet/mod.rs similarity index 77% rename from src/storages/sheet_storage/mod.rs rename to src/databases/sheet/mod.rs index dedbfe1a..da6ce600 100644 --- a/src/storages/sheet_storage/mod.rs +++ b/src/databases/sheet/mod.rs @@ -1,9 +1,9 @@ mod auto_increment; -mod store; -mod store_mut; +mod base; +mod mutable; use { - crate::{store::*, Result}, + crate::{database::*, Result}, serde::Serialize, std::{fmt::Debug, path::Path}, thiserror::Error, @@ -11,7 +11,7 @@ use { }; #[derive(Error, Serialize, Debug, PartialEq)] -pub enum SheetStorageError { +pub enum SheetDatabaseError { #[error("FSError")] FSError, #[error("failed to parse column information")] @@ -22,14 +22,14 @@ pub enum SheetStorageError { FailedToGetSheet, } -pub struct SheetStorage { +pub struct SheetDatabase { book: Spreadsheet, path: String, } -impl FullStorage for SheetStorage {} +impl DBFull for SheetDatabase {} -impl SheetStorage { +impl SheetDatabase { pub fn new(path: &str) -> Result { let book = reader::xlsx::read(Path::new(path)).unwrap_or_else(|_| new_file_empty_worksheet()); @@ -38,12 +38,12 @@ impl SheetStorage { } pub(crate) fn save(&self) -> Result<()> { writer::xlsx::write(&self.book, Path::new(&self.path)) - .map_err(|_| SheetStorageError::FSError.into()) + .map_err(|_| SheetDatabaseError::FSError.into()) } pub(crate) fn get_sheet_mut(&mut self, sheet_name: &str) -> Result<&mut Worksheet> { self.book .get_sheet_by_name_mut(sheet_name) - .map_err(|_| SheetStorageError::FailedToGetSheet.into()) + .map_err(|_| SheetDatabaseError::FailedToGetSheet.into()) } } diff --git a/src/storages/sheet_storage/store_mut.rs b/src/databases/sheet/mutable.rs similarity index 89% rename from src/storages/sheet_storage/store_mut.rs rename to src/databases/sheet/mutable.rs index 5643906d..f5a7a70d 100644 --- a/src/storages/sheet_storage/store_mut.rs +++ b/src/databases/sheet/mutable.rs @@ -1,14 +1,14 @@ use umya_spreadsheet::{Border, Comment, PatternValues, RichText, Style, TextElement}; use { crate::{ - Cast, Result, Row, Schema, SchemaChange, SchemaDiff, SheetStorage, SheetStorageError, - StorageError, StoreMut, Value, + Cast, DBMut, DatabaseError, Result, Row, Schema, SchemaChange, SchemaDiff, SheetDatabase, + SheetDatabaseError, Value, }, async_trait::async_trait, }; #[async_trait(?Send)] -impl StoreMut for SheetStorage { +impl DBMut for SheetDatabase { async fn insert_schema(&mut self, schema: &Schema) -> Result<()> { let mut style = Style::default(); style @@ -36,7 +36,7 @@ impl StoreMut for SheetStorage { let sheet = self .book .new_sheet(sheet_name) - .map_err(|_| SheetStorageError::FailedToCreateSheet)?; + .map_err(|_| SheetDatabaseError::FailedToCreateSheet)?; column_defs .iter() .enumerate() @@ -50,7 +50,7 @@ impl StoreMut for SheetStorage { let mut comment_text_element = TextElement::default(); comment_text_element.set_text( serde_yaml::to_string(&column_def) - .map_err(|_| SheetStorageError::FailedColumnParse)?, + .map_err(|_| SheetDatabaseError::FailedColumnParse)?, ); let mut comment_text = RichText::default(); comment_text.add_rich_text_elements(comment_text_element); @@ -86,7 +86,7 @@ impl StoreMut for SheetStorage { async fn delete_schema(&mut self, sheet_name: &str) -> Result<()> { self.book .remove_sheet_by_name(sheet_name) - .map_err(|_| SheetStorageError::FailedToGetSheet)?; + .map_err(|_| SheetDatabaseError::FailedToGetSheet)?; self.save() } @@ -124,7 +124,7 @@ impl StoreMut for SheetStorage { RenameTable(new_name) => { sheet.set_name(new_name); } - _ => return Err(StorageError::Unimplemented.into()), + _ => return Err(DatabaseError::Unimplemented.into()), // TODO }; } diff --git a/src/storages/sled_storage/auto_increment.rs b/src/databases/sled/auto_increment.rs similarity index 95% rename from src/storages/sled_storage/auto_increment.rs rename to src/databases/sled/auto_increment.rs index a84195a9..4bed1640 100644 --- a/src/storages/sled_storage/auto_increment.rs +++ b/src/databases/sled/auto_increment.rs @@ -1,6 +1,6 @@ #![cfg(feature = "auto-increment")] use { - super::{error::err_into, SledStorage}, + super::{error::err_into, SledDatabase}, crate::{AutoIncrement, Error, Result}, async_trait::async_trait, fstrings::*, @@ -8,7 +8,7 @@ use { }; #[async_trait(?Send)] -impl AutoIncrement for SledStorage { +impl AutoIncrement for SledDatabase { async fn generate_increment_values( &mut self, table_name: String, diff --git a/src/storages/sled_storage/store.rs b/src/databases/sled/base.rs similarity index 94% rename from src/storages/sled_storage/store.rs rename to src/databases/sled/base.rs index c085878e..89a93263 100644 --- a/src/storages/sled_storage/store.rs +++ b/src/databases/sled/base.rs @@ -1,10 +1,12 @@ use { super::{ err_into, fetch_schema, - store_mut::{index_prefix, indexed_key}, - SledStorage, + mutable::{index_prefix, indexed_key}, + SledDatabase, + }, + crate::{ + join_iters, DBBase, IndexFilter, JoinType, NullOrd, Plane, Result, Row, Schema, Value, }, - crate::{join_iters, IndexFilter, JoinType, NullOrd, Plane, Result, Row, Schema, Store, Value}, async_trait::async_trait, rayon::slice::ParallelSliceMut, sled::IVec, @@ -12,7 +14,7 @@ use { }; #[async_trait(?Send)] -impl Store for SledStorage { +impl DBBase for SledDatabase { async fn fetch_schema(&self, table_name: &str) -> Result> { fetch_schema(&self.tree, table_name).map(|(_, schema)| schema) } diff --git a/src/storages/sled_storage/error.rs b/src/databases/sled/error.rs similarity index 62% rename from src/storages/sled_storage/error.rs rename to src/databases/sled/error.rs index f243e2ec..19b202c4 100644 --- a/src/storages/sled_storage/error.rs +++ b/src/databases/sled/error.rs @@ -1,7 +1,7 @@ use {crate::Error, sled::transaction::TransactionError, std::str, thiserror::Error as ThisError}; #[derive(ThisError, Debug)] -pub enum StorageError { +pub enum DatabaseError { #[error(transparent)] Sled(#[from] sled::Error), #[error(transparent)] @@ -10,31 +10,31 @@ pub enum StorageError { Str(#[from] str::Utf8Error), } -impl From for Error { - fn from(e: StorageError) -> Error { - use StorageError::*; +impl From for Error { + fn from(e: DatabaseError) -> Error { + use DatabaseError::*; match e { - Sled(e) => Error::Storage(Box::new(e)), - Bincode(e) => Error::Storage(e), - Str(e) => Error::Storage(Box::new(e)), + Sled(e) => Error::Database(Box::new(e)), + Bincode(e) => Error::Database(e), + Str(e) => Error::Database(Box::new(e)), } } } impl From for Error { fn from(e: sled::Error) -> Error { - Error::Storage(Box::new(e)) + Error::Database(Box::new(e)) } } impl From for Error { fn from(e: bincode::Error) -> Error { - Error::Storage(Box::new(e)) + Error::Database(Box::new(e)) } } impl From for Error { fn from(e: str::Utf8Error) -> Error { - Error::Storage(Box::new(e)) + Error::Database(Box::new(e)) } } @@ -42,16 +42,16 @@ impl From> for Error { fn from(error: TransactionError) -> Error { match error { TransactionError::Abort(error) => error, - TransactionError::Storage(error) => StorageError::Sled(error).into(), + TransactionError::Storage(error) => DatabaseError::Sled(error).into(), } } } pub fn err_into(error: E) -> Error where - E: Into, + E: Into, { - let error: StorageError = error.into(); + let error: DatabaseError = error.into(); let error: Error = error.into(); error diff --git a/src/storages/sled_storage/mod.rs b/src/databases/sled/mod.rs similarity index 70% rename from src/storages/sled_storage/mod.rs rename to src/databases/sled/mod.rs index 720054a2..99517913 100644 --- a/src/storages/sled_storage/mod.rs +++ b/src/databases/sled/mod.rs @@ -1,39 +1,39 @@ mod auto_increment; +mod base; mod error; -mod store; -mod store_mut; +mod mutable; mod util; #[cfg(not(feature = "alter-table"))] -impl crate::AlterTable for SledStorage {} +impl crate::AlterTable for SledDatabase {} #[cfg(not(feature = "auto-increment"))] -impl crate::AutoIncrement for SledStorage {} +impl crate::AutoIncrement for SledDatabase {} use { - crate::{Error, FullStorage, Result, Schema, Storage}, + crate::{DBFull, Database, Error, Result, Schema}, error::err_into, sled::{self, Config, Db}, std::convert::TryFrom, }; #[derive(Debug, Clone)] -pub struct SledStorage { +pub struct SledDatabase { tree: Db, } -impl FullStorage for SledStorage {} -impl SledStorage { +impl DBFull for SledDatabase {} +impl SledDatabase { pub fn new(filename: &str) -> Result { let tree = sled::open(filename).map_err(err_into)?; Ok(Self { tree }) } } -impl Storage { - pub fn new_sled(sled: SledStorage) -> Self { +impl Database { + pub fn new_sled(sled: SledDatabase) -> Self { Self::new(Box::new(sled)) } } -impl TryFrom for SledStorage { +impl TryFrom for SledDatabase { type Error = Error; fn try_from(config: Config) -> Result { diff --git a/src/storages/sled_storage/store_mut.rs b/src/databases/sled/mutable.rs similarity index 92% rename from src/storages/sled_storage/store_mut.rs rename to src/databases/sled/mutable.rs index 32af8dfa..37ec8a06 100644 --- a/src/storages/sled_storage/store_mut.rs +++ b/src/databases/sled/mutable.rs @@ -1,7 +1,7 @@ use { - super::{err_into, fetch_schema, SledStorage}, + super::{err_into, fetch_schema, SledDatabase}, crate::{ - BigEndian, Column, Result, Row, Schema, SchemaChange, SchemaDiff, StorageError, StoreMut, + BigEndian, Column, DBMut, DatabaseError, Result, Row, Schema, SchemaChange, SchemaDiff, Value, }, async_trait::async_trait, @@ -11,7 +11,7 @@ use { }; #[async_trait(?Send)] -impl StoreMut for SledStorage { +impl DBMut for SledDatabase { async fn insert_schema(&mut self, schema: &Schema) -> Result<()> { let key = format!("schema/{}", schema.table_name); let key = key.as_bytes(); @@ -147,7 +147,7 @@ impl StoreMut for SledStorage { IndexRemove(index) => { let schema = fetch_schema(&self.tree, table_name)? .1 - .ok_or(StorageError::TableNotFound)?; + .ok_or(DatabaseError::TableNotFound)?; if let Some(index) = schema.indexes.get(index) { self.remove_index(table_name, &index.name) } else { @@ -155,14 +155,14 @@ impl StoreMut for SledStorage { } } ColumnUpdate(..) | IndexAdd(..) => Ok(()), - _ => Err(StorageError::Unimplemented.into()), + _ => Err(DatabaseError::Unimplemented.into()), // TODO: Column remove & add: manipulate all rows // TODO: Index remove, add and update: rebuild }?; } let (key, schema) = fetch_schema(&self.tree, table_name)?; - let schema = schema.ok_or(StorageError::TableNotFound)?; + let schema = schema.ok_or(DatabaseError::TableNotFound)?; let schema = schema_diff.merge(schema); let schema_value = bincode::serialize(&schema)?; self.tree.insert(key, schema_value)?; @@ -171,10 +171,10 @@ impl StoreMut for SledStorage { } } -impl SledStorage { +impl SledDatabase { pub fn rename_table(&mut self, old_name: &str, new_name: String) -> Result<()> { let (key, schema) = fetch_schema(&self.tree, old_name)?; - let schema = schema.ok_or(StorageError::TableNotFound)?; + let schema = schema.ok_or(DatabaseError::TableNotFound)?; self.tree.remove(key)?; let value = bincode::serialize(&schema)?; @@ -198,9 +198,9 @@ impl SledStorage { } pub fn add_column(&mut self, table_name: &str, column: Column) -> Result<()> { let value = match (&column.default, &column.is_nullable) { - (Some(_expr), _) => Err(StorageError::Unimplemented), // TODO + (Some(_expr), _) => Err(DatabaseError::Unimplemented), // TODO (None, true) => Ok(Value::Null), - (None, false) => Err(StorageError::Unimplemented), + (None, false) => Err(DatabaseError::Unimplemented), }?; let prefix = format!("data/{}/", table_name); diff --git a/src/storages/sled_storage/util.rs b/src/databases/sled/util.rs similarity index 100% rename from src/storages/sled_storage/util.rs rename to src/databases/sled/util.rs diff --git a/src/executor/alter_table/truncate.rs b/src/executor/alter_table/truncate.rs index 97cd8e70..bee18c08 100644 --- a/src/executor/alter_table/truncate.rs +++ b/src/executor/alter_table/truncate.rs @@ -1,5 +1,5 @@ use { - crate::{data::get_name, AlterError, Glue, Result, StorageInner, ValueDefault}, + crate::{data::get_name, AlterError, DatabaseInner, Glue, Result, ValueDefault}, futures::stream::{self, TryStreamExt}, sqlparser::ast::ObjectName, }; @@ -13,7 +13,7 @@ impl Glue { if let Some(schema) = schema { // TODO: We should be deleting the entry #[cfg(feature = "auto-increment")] - let result: Result<&mut StorageInner> = stream::iter(schema.column_defs.iter().map(Ok)) + let result: Result<&mut DatabaseInner> = stream::iter(schema.column_defs.iter().map(Ok)) .try_fold(database, |database, column| async move { if matches!(column.default, Some(ValueDefault::AutoIncrement(_))) { database diff --git a/src/executor/fetch.rs b/src/executor/fetch.rs index 2f80ae2e..c28f9807 100644 --- a/src/executor/fetch.rs +++ b/src/executor/fetch.rs @@ -1,6 +1,6 @@ use { super::types::{ColumnInfo, ComplexTableName}, - crate::{result::Result, Column, StorageInner}, + crate::{result::Result, Column, DatabaseInner}, serde::Serialize, thiserror::Error as ThisError, }; @@ -12,7 +12,7 @@ pub enum FetchError { } pub async fn fetch_columns( - storage: &StorageInner, + storage: &DatabaseInner, table: ComplexTableName, ) -> Result> { let schema = storage diff --git a/src/executor/other/explain.rs b/src/executor/other/explain.rs index 6c69f635..da11764a 100644 --- a/src/executor/other/explain.rs +++ b/src/executor/other/explain.rs @@ -1,4 +1,4 @@ -use crate::{ExecuteError, Payload, Row, Schema, StorageInner, Value}; +use crate::{DatabaseInner, ExecuteError, Payload, Row, Schema, Value}; use crate::{Glue, Result}; use sqlparser::ast::ObjectName; @@ -80,7 +80,7 @@ impl Glue { } } } -impl StorageInner { +impl DatabaseInner { async fn get_tables(&self) -> Result> { Ok(self .scan_schemas() diff --git a/src/executor/query/select/join/execute.rs b/src/executor/query/select/join/execute.rs index 9df01003..62e6fe62 100644 --- a/src/executor/query/select/join/execute.rs +++ b/src/executor/query/select/join/execute.rs @@ -2,8 +2,8 @@ use { super::{JoinError, JoinMethod, JoinPlan, JoinType}, crate::{ executor::types::{ColumnInfo, Row}, - Glue, IndexFilter, Ingredient, MetaRecipe, Method, PlannedRecipe, Recipe, Result, - StorageInner, Value, + DatabaseInner, Glue, IndexFilter, Ingredient, MetaRecipe, Method, PlannedRecipe, Recipe, + Result, Value, }, }; @@ -45,7 +45,7 @@ impl JoinExecute { pub fn set_first_table(&mut self) { self.method = JoinMethod::FirstTable; } - pub async fn get_rows<'a>(&self, storage: &StorageInner) -> Result> { + pub async fn get_rows<'a>(&self, storage: &DatabaseInner) -> Result> { if let Some(index_filter) = self.index_filter.clone() { storage.scan_data_indexed(self.table.as_str(), index_filter) } else { diff --git a/src/glue/database.rs b/src/glue/database.rs index 813f838f..23f13e25 100644 --- a/src/glue/database.rs +++ b/src/glue/database.rs @@ -1,21 +1,21 @@ use { - crate::{Context, Glue, InterfaceError, Result, Storage, StorageInner}, + crate::{Context, Database, DatabaseInner, Glue, InterfaceError, Result}, std::sync::MutexGuard, }; impl Glue { // TODO: None ref should give a primary - pub fn get_database(&self, db_ref: &Option) -> Result>> { + pub fn get_database(&self, db_ref: &Option) -> Result>> { self.databases .get(db_ref.as_ref().unwrap_or(&self.primary)) .ok_or(InterfaceError::DatabaseNotFound.into()) .map(|db| db.get()) } - pub fn get_mut_database(&mut self, db_ref: &Option) -> Result<&mut Box> { + pub fn get_mut_database(&mut self, db_ref: &Option) -> Result<&mut Box> { self.databases .get_mut(db_ref.as_ref().unwrap_or(&self.primary)) .ok_or(InterfaceError::DatabaseNotFound.into()) - .map(Storage::get_mut) + .map(Database::get_mut) } pub fn get_context(&self) -> Result> { self.context diff --git a/src/glue/mod.rs b/src/glue/mod.rs index d7c6e39c..ea18d083 100644 --- a/src/glue/mod.rs +++ b/src/glue/mod.rs @@ -3,7 +3,7 @@ use std::sync::Mutex; use crate::ExecuteError; use { crate::{ - parse, parse_single, CSVSettings, Connection, Payload, Query, Result, Storage, Value, + parse, parse_single, CSVSettings, Connection, Database, Payload, Query, Result, Value, WIPError, }, futures::executor::block_on, @@ -49,21 +49,21 @@ impl Context { /// - [`Glue::select_as_json()`] -- Provides data, only for `SELECT` queries, as one big [String]; generally useful for webby interactions. pub struct Glue { pub primary: String, - databases: HashMap, + databases: HashMap, context: Mutex, } /// ## Creation of new interfaces impl Glue { - /// Creates a [Glue] instance with just one [Storage]. - pub fn new(name: String, database: Storage) -> Self { + /// Creates a [Glue] instance with just one [Database]. + pub fn new(name: String, database: Database) -> Self { let mut databases = HashMap::new(); databases.insert(name, database); Self::new_multi(databases) } /// Creates a [Glue] instance with access to all provided storages. - /// Argument is: [Vec]<(Identifier, [Storage])> - pub fn new_multi(databases: HashMap) -> Self { + /// Argument is: [Vec]<(Identifier, [Database])> + pub fn new_multi(databases: HashMap) -> Self { let context = Mutex::new(Context::default()); let primary = databases.keys().next().cloned().unwrap_or_default(); Self { @@ -85,10 +85,10 @@ impl Glue { /// Merge existing [Glue] with [Vec] of other [Glue]s /// For example: /// ``` - /// use multisql::{SledStorage, Storage, Glue}; - /// let storage = SledStorage::new("data/example_location/example") - /// .map(Storage::new_sled) - /// .expect("Storage Creation Failed"); + /// use multisql::{SledDatabase, Database, Glue}; + /// let storage = SledDatabase::new("data/example_location/example") + /// .map(Database::new_sled) + /// .expect("Database Creation Failed"); /// let mut glue = Glue::new(String::from("main"), storage); /// /// glue.execute_many(" @@ -98,9 +98,9 @@ impl Glue { /// SELECT * FROM test WHERE id > 1; /// "); /// - /// let other_storage = SledStorage::new("data/example_location/example_other") - /// .map(Storage::new_sled) - /// .expect("Storage Creation Failed"); + /// let other_storage = SledDatabase::new("data/example_location/example_other") + /// .map(Database::new_sled) + /// .expect("Database Creation Failed"); /// let mut other_glue = Glue::new(String::from("other"), other_storage); /// /// glue.extend_many_glues(vec![other_glue]); @@ -148,7 +148,7 @@ impl Glue { /// Extend [Glue] by single database /// Returns [bool] of whether action was taken - pub fn extend(&mut self, database_name: String, database: Storage) -> bool { + pub fn extend(&mut self, database_name: String, database: Database) -> bool { let database_present = self.databases.contains_key(&database_name); if !database_present { self.databases.insert(database_name, database); diff --git a/src/lib.rs b/src/lib.rs index 62b3d5dc..80840c2c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -28,17 +28,15 @@ //! - [SledStorage] -- Most common type of storage/backend //! - [Value] -- Value wrapper -pub use sqlparser as parser; - mod data; +mod database; +mod databases; mod executor; mod glue; mod parse_sql; mod result; -mod storages; -mod store; mod utils; -pub use {data::*, executor::*, glue::*, parse_sql::*, result::*, storages::*, store::*}; +pub use {data::*, database::*, databases::*, executor::*, glue::*, parse_sql::*, result::*}; pub(crate) use utils::*; diff --git a/src/result.rs b/src/result.rs index fd671b1f..9d62c48d 100644 --- a/src/result.rs +++ b/src/result.rs @@ -1,8 +1,8 @@ use { crate::{ - AlterError, CSVStorageError, ExecuteError, FetchError, InterfaceError, JoinError, - ManualError, MemoryStorageError, PlanError, QueryError, RecipeError, RowError, SelectError, - SheetStorageError, StorageError, TableError, ValidateError, ValueError, + AlterError, CSVDatabaseError, DatabaseError, ExecuteError, FetchError, InterfaceError, + JoinError, ManualError, MemoryDatabaseError, PlanError, QueryError, RecipeError, RowError, + SelectError, SheetDatabaseError, TableError, ValidateError, ValueError, }, serde::Serialize, std::marker::{Send, Sync}, @@ -21,7 +21,7 @@ pub enum WIPError { pub enum Error { #[error(transparent)] #[serde(with = "stringify")] - Storage(#[from] Box), + Database(#[from] Box), #[error(transparent)] Execute(#[from] ExecuteError), @@ -52,13 +52,13 @@ pub enum Error { #[error(transparent)] WIP(#[from] WIPError), #[error(transparent)] - StorageImplementation(#[from] StorageError), + DatabaseImplementation(#[from] DatabaseError), #[error(transparent)] - CSVStorage(#[from] CSVStorageError), + CSVDatabase(#[from] CSVDatabaseError), #[error(transparent)] - SheetStorage(#[from] SheetStorageError), + SheetDatabase(#[from] SheetDatabaseError), #[error(transparent)] - MemoryStorage(#[from] MemoryStorageError), + MemoryDatabase(#[from] MemoryDatabaseError), #[error(transparent)] Interface(#[from] InterfaceError), } @@ -88,11 +88,11 @@ impl PartialEq for Error { (Query(l), Query(r)) => l == r, (Validate(l), Validate(r)) => l == r, (WIP(l), WIP(r)) => l == r, - (StorageImplementation(l), StorageImplementation(r)) => l == r, - (CSVStorage(l), CSVStorage(r)) => l == r, - (SheetStorage(l), SheetStorage(r)) => l == r, + (DatabaseImplementation(l), DatabaseImplementation(r)) => l == r, + (CSVDatabase(l), CSVDatabase(r)) => l == r, + (SheetDatabase(l), SheetDatabase(r)) => l == r, (Interface(l), Interface(r)) => l == r, - (MemoryStorage(l), MemoryStorage(r)) => l == r, + (MemoryDatabase(l), MemoryDatabase(r)) => l == r, _ => false, } } diff --git a/src/storages/mod.rs b/src/storages/mod.rs deleted file mode 100644 index 92510d40..00000000 --- a/src/storages/mod.rs +++ /dev/null @@ -1,19 +0,0 @@ -#[cfg(feature = "sled-storage")] -mod sled_storage; -#[cfg(feature = "sled-storage")] -pub use sled_storage::SledStorage; - -#[cfg(feature = "csv-storage")] -mod csv_storage; -#[cfg(feature = "csv-storage")] -pub use csv_storage::{CSVSettings, CSVStorage, CSVStorageError}; - -#[cfg(feature = "sheet-storage")] -mod sheet_storage; -#[cfg(feature = "sheet-storage")] -pub use sheet_storage::{SheetStorage, SheetStorageError}; - -#[cfg(feature = "memory-storage")] -mod memory; -#[cfg(feature = "memory-storage")] -pub use memory::{MemoryStorage, MemoryStorageError}; diff --git a/src/store/mod.rs b/src/store/mod.rs deleted file mode 100644 index bfcdbee6..00000000 --- a/src/store/mod.rs +++ /dev/null @@ -1,101 +0,0 @@ -mod auto_increment; -mod store; -mod store_mut; - -pub use auto_increment::AutoIncrement; - -use std::sync::{Mutex, MutexGuard}; -use { - crate::Result, - serde::{Deserialize, Serialize}, - std::fmt::Debug, - thiserror::Error, -}; - -pub use {store::Store, store_mut::StoreMut}; - -#[derive(Error, Serialize, Debug, PartialEq)] -pub enum StorageError { - #[error("this storage has not yet implemented this method")] - Unimplemented, - #[error("tried to connect to an unknown storage")] - UnknownConnection, - #[error("table not found")] - TableNotFound, -} - -#[derive(Serialize, Deserialize)] -pub enum Connection { - Unknown, - #[cfg(feature = "memory-storage")] - Memory, - #[cfg(feature = "sled-storage")] - Sled(String), - #[cfg(feature = "csv-storage")] - CSV(String, crate::CSVSettings), - #[cfg(feature = "sheet-storage")] - Sheet(String), -} -impl Default for Connection { - fn default() -> Self { - Connection::Unknown - } -} -impl TryFrom for Storage { - type Error = crate::Error; - fn try_from(connection: Connection) -> Result { - use { - crate::{CSVStorage, MemoryStorage, SheetStorage, SledStorage}, - Connection::*, - }; - let storage: Mutex> = Mutex::new(match &connection { - #[cfg(feature = "memory-storage")] - Memory => Box::new(MemoryStorage::new()), - #[cfg(feature = "sled-storage")] - Sled(path) => Box::new(SledStorage::new(path)?), - #[cfg(feature = "csv-storage")] - CSV(path, settings) => Box::new(CSVStorage::new_with_settings(path, settings.clone())?), - #[cfg(feature = "sheet-storage")] - Sheet(path) => Box::new(SheetStorage::new(path)?), - Unknown => return Err(StorageError::UnknownConnection.into()), - }); - Ok(Storage { - storage, - source_connection: connection, - }) - } -} - -pub struct Storage { - source_connection: Connection, - storage: Mutex>, -} -impl Storage { - pub fn new(storage: Box) -> Self { - let storage = Mutex::new(storage); - Self { - storage, - source_connection: Connection::default(), - } - } - pub fn get(&self) -> MutexGuard> { - self.storage - .lock() - .expect("Unreachable: Storage wasn't replaced!") - } - pub fn get_mut(&mut self) -> &mut Box { - self.storage - .get_mut() - .expect("Unreachable: Storage wasn't replaced!") - } - pub fn into_source(self) -> Connection { - self.source_connection - } - pub fn from_source(connection: Connection) -> Result { - connection.try_into() - } -} - -pub type StorageInner = dyn FullStorage; - -pub trait FullStorage: Store + StoreMut + AutoIncrement {} diff --git a/tests/functionality/validation/types.rs b/tests/functionality/validation/types.rs index 163ac3cf..5cb84658 100644 --- a/tests/functionality/validation/types.rs +++ b/tests/functionality/validation/types.rs @@ -8,14 +8,14 @@ crate::util_macros::testcase!( crate::util_macros::assert_error!(glue, "INSERT INTO TableB SELECT uid FROM TableC;", multisql::ValueError::IncompatibleDataType { - data_type: multisql::parser::ast::DataType::Boolean.to_string(), + data_type: sqlparser::ast::DataType::Boolean.to_string(), value: format!("{:?}", multisql::Value::I64(1)), } ); crate::util_macros::assert_error!(glue, "INSERT INTO TableC (uid) VALUES (\"A\")", multisql::ValueError::IncompatibleDataType { - data_type: multisql::parser::ast::DataType::Int(None).to_string(), + data_type: sqlparser::ast::DataType::Int(None).to_string(), value: format!("{:?}", multisql::Value::Str(String::from("A"))), } ); @@ -30,7 +30,7 @@ crate::util_macros::testcase!( crate::util_macros::assert_error!(glue, "UPDATE TableC SET uid = TRUE;", multisql::ValueError::IncompatibleDataType { - data_type: multisql::parser::ast::DataType::Int(None).to_string(), + data_type: sqlparser::ast::DataType::Int(None).to_string(), value: format!("{:?}", multisql::Value::Bool(true)), } ); diff --git a/tests/storages/csv.rs b/tests/storages/csv.rs index 8cc0868e..59d250cb 100644 --- a/tests/storages/csv.rs +++ b/tests/storages/csv.rs @@ -1,5 +1,5 @@ #[allow(unused_must_use)] -pub fn csv_storage(name: &str) -> multisql::Glue { +pub fn csv_database(name: &str) -> multisql::Glue { use {fstrings::*, multisql::*}; let path = f!("data/csv_{name}.csv"); @@ -13,13 +13,13 @@ pub fn csv_storage(name: &str) -> multisql::Glue { std::fs::create_dir("data"); - let storage = CSVStorage::new(&path) - .map(Storage::new_csv) - .expect("Create Storage"); + let database = CSVDatabase::new(&path) + .map(Database::new_csv) + .expect("Create Database"); - Glue::new(String::from("main"), storage) + Glue::new(String::from("main"), database) } -crate::util_macros::run!(csv_storage, functionality::statement::create::table); -crate::util_macros::run!(csv_storage, functionality::statement::simple_insert); -crate::util_macros::run!(csv_storage, functionality::statement::data_query); +crate::util_macros::run!(csv_database, functionality::statement::create::table); +crate::util_macros::run!(csv_database, functionality::statement::simple_insert); +crate::util_macros::run!(csv_database, functionality::statement::data_query); diff --git a/tests/storages/memory.rs b/tests/storages/memory.rs index a0065f34..eb07adec 100644 --- a/tests/storages/memory.rs +++ b/tests/storages/memory.rs @@ -1,9 +1,9 @@ pub fn memory(_name: &str) -> multisql::Glue { use multisql::*; - let storage = Connection::Memory.try_into().expect("Create Storage"); + let database = Connection::Memory.try_into().expect("Create Database"); - Glue::new(String::from("main"), storage) + Glue::new(String::from("main"), database) } /*crate::util_macros::run!(memory, functionality); diff --git a/tests/storages/sheet.rs b/tests/storages/sheet.rs index d14da2fd..a1eea6ca 100644 --- a/tests/storages/sheet.rs +++ b/tests/storages/sheet.rs @@ -1,5 +1,5 @@ #[allow(unused_must_use)] -pub fn sheet_storage(name: &str) -> multisql::Glue { +pub fn sheet_database(name: &str) -> multisql::Glue { use {fstrings::*, multisql::*}; let path = f!("data/sheet_{name}.xlsx"); @@ -11,19 +11,19 @@ pub fn sheet_storage(name: &str) -> multisql::Glue { std::fs::create_dir("data"); - let storage = Storage::try_from(Connection::Sheet(path)).expect("Create Storage"); + let database = Database::try_from(Connection::Sheet(path)).expect("Create Database"); - Glue::new(String::from("main"), storage) + Glue::new(String::from("main"), database) } -crate::util_macros::run!(sheet_storage, original); -crate::util_macros::run!(sheet_storage, functionality::statement::create::table); -crate::util_macros::run!(sheet_storage, functionality::statement::simple_insert); -crate::util_macros::run!(sheet_storage, functionality::statement::data_query); -crate::util_macros::run!(sheet_storage, functionality::validation); -crate::util_macros::run!(sheet_storage, functionality::query::join); -crate::util_macros::run!(sheet_storage, functionality::query::aggregate); -crate::util_macros::run!(sheet_storage, functionality::query::function); -//crate::util_macros::run!(sheet_storage, functionality::api); -//crate::util_macros::run!(sheet_storage, functionality::query); -//crate::util_macros::run!(sheet_storage, functionality::column_options); +crate::util_macros::run!(sheet_database, original); +crate::util_macros::run!(sheet_database, functionality::statement::create::table); +crate::util_macros::run!(sheet_database, functionality::statement::simple_insert); +crate::util_macros::run!(sheet_database, functionality::statement::data_query); +crate::util_macros::run!(sheet_database, functionality::validation); +crate::util_macros::run!(sheet_database, functionality::query::join); +crate::util_macros::run!(sheet_database, functionality::query::aggregate); +crate::util_macros::run!(sheet_database, functionality::query::function); +//crate::util_macros::run!(sheet_database, functionality::api); +//crate::util_macros::run!(sheet_database, functionality::query); +//crate::util_macros::run!(sheet_database, functionality::column_options); diff --git a/tests/storages/sled.rs b/tests/storages/sled.rs index da004ebc..7aff9867 100644 --- a/tests/storages/sled.rs +++ b/tests/storages/sled.rs @@ -1,4 +1,4 @@ -pub fn sled_storage(name: &str) -> multisql::Glue { +pub fn sled_database(name: &str) -> multisql::Glue { use {fstrings::*, multisql::*}; let path = f!("data/sled_{name}"); @@ -10,12 +10,12 @@ pub fn sled_storage(name: &str) -> multisql::Glue { } } - let storage = SledStorage::new(&path) - .map(Storage::new_sled) - .expect("Create Storage"); + let database = SledDatabase::new(&path) + .map(Database::new_sled) + .expect("Create Database"); - Glue::new(String::from("main"), storage) + Glue::new(String::from("main"), database) } -crate::util_macros::run!(sled_storage, functionality); -crate::util_macros::run!(sled_storage, original); +crate::util_macros::run!(sled_database, functionality); +crate::util_macros::run!(sled_database, original);