morethantext-web/src/morethantext/mod.rs

91 lines
2.1 KiB
Rust
Raw Normal View History

2022-08-06 12:03:47 -04:00
pub mod error;
use async_std::sync::{Arc, RwLock};
use error::MTTError;
use std::collections::HashMap;
2022-07-18 17:24:45 -04:00
#[derive(Clone)]
2022-08-06 12:03:47 -04:00
pub struct MoreThanText {
tables: Arc<RwLock<HashMap<String, Table>>>,
}
2022-07-18 17:24:45 -04:00
impl MoreThanText {
pub async fn new() -> Self {
2022-08-06 12:03:47 -04:00
Self {
tables: Arc::new(RwLock::new(HashMap::new())),
}
}
pub async fn new_table<S>(&self, tname: S) -> Result<Table, MTTError>
where
S: Into<String>,
{
2022-08-06 12:03:47 -04:00
let mut tables = self.tables.write().await;
let name = tname.into();
match tables.get(&name) {
2022-08-06 12:03:47 -04:00
Some(_) => Err(MTTError::new(format!("table {} already exists", name))),
None => {
tables.insert(name, Table::new().await);
2022-08-06 12:03:47 -04:00
Ok(Table::new().await)
}
}
}
}
2022-08-06 12:03:47 -04:00
pub struct Table;
2022-08-05 16:47:01 -04:00
impl Table {
2022-08-06 12:03:47 -04:00
pub async fn new() -> Self {
2022-08-05 16:47:01 -04:00
Self {}
}
}
#[cfg(test)]
mod database {
use super::*;
#[async_std::test]
async fn create_table_with_str() {
2022-08-06 12:03:47 -04:00
let db = MoreThanText::new().await;
db.new_table("william").await.unwrap();
}
#[async_std::test]
async fn create_table_with_string() {
let db = MoreThanText::new().await;
db.new_table("marvin".to_string()).await.unwrap();
}
2022-08-06 12:03:47 -04:00
#[async_std::test]
async fn table_names_are_unique() -> Result<(), String> {
let db = MoreThanText::new().await;
let name = "alexandar";
let msg = format!("table {} already exists", name);
db.new_table(name).await.unwrap();
match db.new_table(name).await {
Ok(_) => Err("Duplicate table names are not allowed.".to_string()),
Err(err) => {
if err.to_string() == msg {
Ok(())
} else {
Err(format!(
"Error message is incorrect: Got: '{}' Want: '{}'",
err.to_string(),
msg
))
}
}
}
}
}
2022-08-05 16:47:01 -04:00
#[cfg(test)]
mod table {
use super::*;
#[async_std::test]
async fn create() {
Table::new().await;
}
}