Compare commits

...

19 Commits

Author SHA1 Message Date
2e73bddbab Return to orignal label.
Some checks failed
MoreThanText build / Build-MoreThanText (push) Failing after 1m52s
2024-02-09 23:46:50 -05:00
800cad7ca3 Updated pipenv.
Some checks failed
MoreThanText build / Build-MoreThanText (push) Has been cancelled
2024-02-07 10:36:37 -05:00
95b2763442 Changed to fedora image.
Some checks failed
MoreThanText build / Build-MoreThanText (push) Has been cancelled
2024-02-01 20:59:52 -05:00
460ca4b5a7 Switching from jenkins.
Some checks failed
MoreThanText build / Build-MoreThanText (push) Failing after 1m50s
2024-02-01 20:49:39 -05:00
45522660bb Where I left off. 2024-02-01 20:40:29 -05:00
829b7242bd Added a table. 2023-07-21 18:10:38 -04:00
49b0eaf2ec Made sure that cache did not over write itself. 2023-07-18 11:44:49 -04:00
e49d6f5e46 Completed duplicate database in multiple sessions. 2023-07-13 09:39:25 -04:00
ea7dec2f4e Cache only stores references. 2023-07-06 17:28:10 -04:00
4dad6f7a05 Database is now stored as an entry. 2023-07-01 15:56:12 -04:00
de93ee1f2c Added random id generator. 2023-07-01 13:26:36 -04:00
c70c006abd Now returning duplicate database errors. 2023-06-30 22:38:18 -04:00
e73fdbff75 Commit adds db from each session. 2023-06-30 12:23:28 -04:00
05d445c58b Added a basic commit function. 2023-06-29 00:17:49 -04:00
933d48a47c Make store list work. 2023-06-25 10:39:14 -04:00
c26089caed Protect against duplicate databases. 2023-06-24 10:48:35 -04:00
d90dc3b9fc Can now add database to store. 2023-06-23 08:30:49 -04:00
a23b5d467e Setup store to hold databases. 2023-06-22 11:08:40 -04:00
c8b93d9922 Moved old database code. 2023-06-22 10:35:05 -04:00
16 changed files with 1706 additions and 53 deletions

View File

@ -0,0 +1,11 @@
---
name: MoreThanText build
run-name: ${{ gitea.actor }} runner
on: push
jobs:
Build-MoreThanText:
runs-on: ubuntu-latest
steps:
- run: cargo test
- run: cargo build --release

View File

@ -11,4 +11,4 @@ black = "*"
pylint = "*" pylint = "*"
[requires] [requires]
python_version = "3.9" python_version = "3"

View File

@ -1,21 +1,124 @@
use super::{ErrorCode, FromCache, MTTError, Store, ToCache, ENTRY}; use super::{Database, ErrorCode, FromCache, MTTError, Store, ToCache, ENTRY};
use async_std::{channel::Receiver, path::PathBuf}; use async_std::{channel::Receiver, path::PathBuf};
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use std::{
collections::{HashMap, VecDeque},
iter::Iterator,
};
pub struct Cache; struct IDGenerator {
ids: Option<VecDeque<String>>,
}
impl IDGenerator {
fn new() -> Self {
Self { ids: None }
}
fn with_ids<T, D>(ids: T) -> Self
where
T: Into<Vec<D>>,
D: Into<String>,
{
let id_list = ids.into();
let mut data = VecDeque::new();
for id in id_list {
data.push_back(id.into());
}
Self { ids: Some(data) }
}
}
impl Iterator for IDGenerator {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
match &self.ids {
Some(id_list) => {
let mut ids = id_list.clone();
let output = ids.pop_front();
self.ids = Some(ids);
output
}
None => Some(thread_rng().sample_iter(&Alphanumeric).take(64).collect()),
}
}
}
#[cfg(test)]
mod genid {
use super::*;
#[test]
fn unique_ids() {
let mut gen = IDGenerator::new();
let mut output: Vec<String> = Vec::new();
for _ in 0..10 {
let id = gen.next().unwrap();
assert!(!output.contains(&id), "{} found in {:?}", id, output);
output.push(id);
}
}
#[test]
fn controlled_ids() {
let ids = ["one", "two", "three"];
let mut gen = IDGenerator::with_ids(ids.clone());
for id in ids {
assert_eq!(id, gen.next().unwrap());
}
}
}
pub struct Cache {
data: HashMap<String, FromCache>,
ids: IDGenerator,
}
impl Cache { impl Cache {
pub async fn new<P>(_dir: P) -> Self pub async fn new<P>(_dir: P) -> Self
where where
P: Into<PathBuf>, P: Into<PathBuf>,
{ {
Self {} let mut data = HashMap::new();
data.insert(ENTRY.to_string(), FromCache::Str(Store::new()));
Self {
data: data,
ids: IDGenerator::new(),
}
} }
pub async fn listen(&self, listener: Receiver<ToCache>) { async fn with_ids<P, T, D>(dir: P, ids: T) -> Self
where
P: Into<PathBuf>,
T: Into<Vec<D>>,
D: Into<String>,
{
let mut output = Self::new(dir).await;
output.ids = IDGenerator::with_ids(ids);
output
}
fn next_id(&mut self) -> String {
let mut id: String;
loop {
id = self.ids.next().unwrap();
match self.get(&id) {
FromCache::Error(_) => break,
_ => (),
}
}
id
}
pub async fn listen(&mut self, listener: Receiver<ToCache>) {
loop { loop {
match listener.recv().await.unwrap() { match listener.recv().await.unwrap() {
ToCache::Get(data) => { ToCache::Get(data) => {
data.result.send(self.get(data.id)).await.unwrap(); data.result.send(self.get(data.data)).await.unwrap();
}
ToCache::Commit(data) => {
data.result.send(self.commit(data.data)).await.unwrap();
} }
} }
} }
@ -26,12 +129,34 @@ impl Cache {
S: Into<String>, S: Into<String>,
{ {
let idd = id.into(); let idd = id.into();
if idd == ENTRY { match self.data.get(&idd) {
FromCache::Str(Store::new()) Some(data) => data.clone(),
} else { None => FromCache::Error(MTTError::from_code(ErrorCode::IDNotFound(idd))),
FromCache::Error(MTTError::from_code(ErrorCode::IDNotFound(idd)))
} }
} }
pub fn commit(&mut self, data: Store) -> FromCache {
let entry_data = self.data.get(ENTRY).unwrap();
let mut store = match entry_data {
FromCache::Str(ep) => ep.clone(),
_ => {
unreachable!()
}
};
for name in data.list() {
let id = self.next_id();
match store.add_by_id(name, &id) {
Ok(_) => {
self.data.insert(id, FromCache::DB(Database::new()));
}
Err(err) => return FromCache::Error(err),
}
}
self.data
.insert(ENTRY.to_string(), FromCache::Str(store))
.unwrap();
FromCache::Ok
}
} }
#[cfg(test)] #[cfg(test)]
@ -80,12 +205,94 @@ mod engine {
} }
Ok(()) Ok(())
} }
#[async_std::test]
async fn commit_database() {
// remove this one for the one below, maybe.
let dir = tempdir().unwrap();
let mut cache = Cache::new(dir.path()).await;
let mut store = Store::new();
let db = "garfield";
store.add(db).unwrap();
cache.commit(store.clone());
let output = cache.get(ENTRY);
match output {
FromCache::Str(result) => assert_eq!(result.list(), store.list()),
_ => assert!(false, "{:?} is not FromCache::Str", output),
}
}
#[async_std::test]
async fn add_database_entry() {
let id = "an_id";
let name = "garfield";
let dir = tempdir().unwrap();
let mut cache = Cache::with_ids(dir.path(), [id]).await;
let mut store = Store::new();
store.add(name).unwrap();
cache.commit(store.clone());
let db_out = cache.get(id);
match db_out {
FromCache::DB(_) => (),
_ => assert!(
false,
"{:?} is not FromCache::DB -- cache is {:?}",
db_out, cache.data
),
}
let store_out = cache.get(ENTRY);
match store_out {
FromCache::Str(updated_store) => match updated_store.get(name) {
Some(output) => {
assert_eq!(output.id, Some(id.to_string()));
assert!(output.data.is_none(), "Should have removed the database.");
}
None => assert!(true, "Store should have stored the database."),
},
_ => assert!(
false,
"{:?} is not FromCache::Str -- cache is {:?}",
db_out, cache.data
),
}
}
#[async_std::test]
async fn ids_are_not_overwritten() {
let ids = ["first", "first", "second"];
let names = ["barney", "fred"];
let dir = tempdir().unwrap();
let mut cache = Cache::with_ids(dir.path(), ids).await;
let mut store1 = Store::new();
store1.add(names[0]).unwrap();
let mut store2 = Store::new();
store2.add(names[1]).unwrap();
cache.commit(store1);
cache.commit(store2);
assert_eq!(
cache.data.len(),
3,
"cache.data had the following entries {:?}",
cache.data.keys()
);
}
#[async_std::test]
async fn no_duplicate_ids() {
let ids = ["one", "two"];
let dir = tempdir().unwrap();
let mut cache = Cache::with_ids(dir.path(), ids).await;
cache
.data
.insert(ids[0].to_string(), FromCache::DB(Database::new()));
assert_eq!(cache.next_id(), ids[1]);
}
} }
#[cfg(test)] #[cfg(test)]
mod messages { mod messages {
use super::{ use super::{
super::{start_db, CacheGet}, super::{start_db, ToCacheMsg},
*, *,
}; };
use async_std::channel::unbounded; use async_std::channel::unbounded;
@ -97,8 +304,8 @@ mod messages {
let mtt = start_db(dir.path()).await.unwrap(); let mtt = start_db(dir.path()).await.unwrap();
let in_s = mtt.to_cache.clone(); let in_s = mtt.to_cache.clone();
let (out_s, out_r) = unbounded(); let (out_s, out_r) = unbounded();
let msg = CacheGet { let msg = ToCacheMsg {
id: ENTRY.to_string(), data: ENTRY.to_string(),
result: out_s, result: out_s,
}; };
in_s.send(ToCache::Get(msg)).await.unwrap(); in_s.send(ToCache::Get(msg)).await.unwrap();
@ -115,8 +322,8 @@ mod messages {
let mtt = start_db(dir.path()).await.unwrap(); let mtt = start_db(dir.path()).await.unwrap();
let in_s = mtt.to_cache.clone(); let in_s = mtt.to_cache.clone();
let (out_s, out_r) = unbounded(); let (out_s, out_r) = unbounded();
let msg = CacheGet { let msg = ToCacheMsg {
id: "bad_id!".to_string(), data: "bad_id!".to_string(),
result: out_s, result: out_s,
}; };
in_s.send(ToCache::Get(msg)).await.unwrap(); in_s.send(ToCache::Get(msg)).await.unwrap();

View File

@ -0,0 +1,36 @@
use super::{DBError, FileData, SessionData};
use std::slice;
#[derive(Clone)]
pub struct Database;
impl Database {
pub fn new() -> Self {
Self
}
}
impl FileData<Self> for Database {
fn to_bytes(&self) -> Vec<u8> {
let output = Vec::new();
output
}
fn from_bytes(_data: &mut slice::Iter<u8>) -> Result<Self, DBError> {
Ok(Self {})
}
}
impl SessionData for Database {
fn add(&mut self, _key: &str, _value: &str, _data: &str) -> Result<Vec<String>, DBError> {
Ok(Vec::new())
}
fn eq(&self, _key: &str, _value: &str) -> Result<Vec<String>, DBError> {
Ok(Vec::new())
}
fn list(&self, _keys: Vec<&str>) -> Result<Vec<String>, DBError> {
Ok(Vec::new())
}
}

View File

@ -1,36 +1,171 @@
use super::{DBError, FileData, SessionData}; use super::{Data, ErrorCode, MTTError, Table};
use std::slice; use std::collections::HashMap;
#[derive(Clone)] #[derive(Clone, Debug)]
pub struct Database; pub struct Database {
data: HashMap<String, Data<Table>>,
}
impl Database { impl Database {
pub fn new() -> Self { pub fn new() -> Self {
Self Self {
data: HashMap::new(),
}
}
pub fn add<S>(&mut self, name: S) -> Result<(), MTTError>
where
S: Into<String>,
{
let db_name = name.into();
match self.get(&db_name) {
Some(_) => Err(MTTError::from_code(ErrorCode::DuplicateTable(db_name))),
None => {
self.data.insert(db_name, Data::from_data(Table::new()));
Ok(())
}
}
}
pub fn add_by_id<S, D>(&mut self, name: S, id: D) -> Result<(), MTTError>
where
S: Into<String>,
D: Into<String>,
{
let db_name = name.into();
match self.get(&db_name) {
Some(_) => Err(MTTError::from_code(ErrorCode::DuplicateTable(db_name))),
None => {
self.data.insert(db_name, Data::from_id(id.into()));
Ok(())
}
}
}
pub fn get(&self, name: &str) -> Option<&Data<Table>> {
self.data.get(name)
}
pub fn list(&self) -> Vec<String> {
let mut names = Vec::new();
for name in self.data.keys() {
names.push(name.to_string());
}
names.sort();
names
} }
} }
impl FileData<Self> for Database { #[cfg(test)]
fn to_bytes(&self) -> Vec<u8> { mod databases {
let output = Vec::new(); use super::*;
output
#[test]
fn create_new() {
let db = Database::new();
let expected: Vec<String> = Vec::new();
assert_eq!(db.list(), expected);
} }
fn from_bytes(_data: &mut slice::Iter<u8>) -> Result<Self, DBError> { #[test]
Ok(Self {}) fn add_db_by_str() {
} let mut db = Database::new();
} let name = "Melvin";
db.add(name).unwrap();
impl SessionData for Database { let output = db.get(name);
fn add(&mut self, _key: &str, _value: &str, _data: &str) -> Result<Vec<String>, DBError> { assert!(output.is_some(), "Get returned none.");
Ok(Vec::new()) }
}
#[test]
fn eq(&self, _key: &str, _value: &str) -> Result<Vec<String>, DBError> { fn add_db_by_string() {
Ok(Vec::new()) let mut db = Database::new();
} let name = "Marvin";
db.add(name.to_string()).unwrap();
fn list(&self, _keys: Vec<&str>) -> Result<Vec<String>, DBError> { let output = db.get(name);
Ok(Vec::new()) assert!(output.is_some(), "Get returned none.");
}
#[test]
fn fail_on_duplicates() -> Result<(), MTTError> {
let mut db = Database::new();
let name = "Mickie";
db.add(name).unwrap();
match db.add(name) {
Ok(_) => Err(MTTError::new("duplicates should error")),
Err(err) => match err.code {
ErrorCode::DuplicateTable(db_name) => {
assert_eq!(db_name, name);
Ok(())
}
_ => Err(MTTError::new(format!("{:?} is not DuplicateTable", err))),
},
}
}
#[test]
fn add_using_cache_id() {
let mut db = Database::new();
let name = "fred";
let id = "12345";
db.add_by_id(name, id).unwrap();
let output = db.get(name).unwrap();
assert!(output.data.is_none(), "there should be no data");
assert_eq!(output.id, Some(id.to_string()));
}
#[test]
fn add_by_cache_id_name_string() {
let mut db = Database::new();
let name = "barney";
let id = "67890";
db.add_by_id(name.to_string(), id).unwrap();
let output = db.get(name).unwrap();
assert!(output.data.is_none(), "there should be no data");
assert_eq!(output.id, Some(id.to_string()));
}
#[test]
fn no_duplicate_databases_for_add_by_id() {
let mut db = Database::new();
let name = "betty";
db.add_by_id(name, "fghij").unwrap();
match db.add_by_id(name, "klmno") {
Ok(_) => assert!(false, "Duplicates should error."),
Err(err) => match err.code {
ErrorCode::DuplicateTable(db_name) => assert_eq!(db_name, name),
_ => assert!(false, "{:?} is not DuplicateTable", err),
},
}
}
#[test]
fn add_by_cache_id_string() {
let mut db = Database::new();
let name = "wilma";
let id = "abcdef";
db.add_by_id(name, id.to_string()).unwrap();
let output = db.get(name).unwrap();
assert!(output.data.is_none(), "there should be no data");
assert_eq!(output.id, Some(id.to_string()));
}
#[test]
fn get_bad_database() -> Result<(), MTTError> {
let db = Database::new();
match db.get("missing") {
Some(_) => Err(MTTError::new("Should have returned None.")),
None => Ok(()),
}
}
#[test]
fn get_list() {
let mut db = Database::new();
let mut ids = ["one", "two", "three", "four", "five"];
for name in ids {
db.add(name.to_string()).unwrap();
}
ids.sort();
assert_eq!(db.list(), ids);
} }
} }

View File

@ -1,11 +1,15 @@
use std::{error::Error, fmt}; use std::{error::Error, fmt};
#[derive(Debug)] #[derive(Clone, Debug)]
pub enum ErrorCode { pub enum ErrorCode {
// General // General
Undefined(String), Undefined(String),
// Cache // Cache
IDNotFound(String), IDNotFound(String),
// Store
DuplicateDatabase(String),
// Database
DuplicateTable(String),
} }
impl fmt::Display for ErrorCode { impl fmt::Display for ErrorCode {
@ -13,6 +17,8 @@ impl fmt::Display for ErrorCode {
match self { match self {
ErrorCode::Undefined(msg) => write!(f, "{}", msg), ErrorCode::Undefined(msg) => write!(f, "{}", msg),
ErrorCode::IDNotFound(id) => write!(f, "ID '{}' not found", id), ErrorCode::IDNotFound(id) => write!(f, "ID '{}' not found", id),
ErrorCode::DuplicateDatabase(name) => write!(f, "database '{}' already exists", name),
ErrorCode::DuplicateTable(name) => write!(f, "table '{}' already exists", name),
} }
} }
} }
@ -37,9 +43,28 @@ mod errorcodes {
assert_eq!(err.to_string(), format!("ID '{}' not found", item)); assert_eq!(err.to_string(), format!("ID '{}' not found", item));
} }
} }
#[test]
fn duplicate_database() {
for item in ITEMS {
let err = ErrorCode::DuplicateDatabase(item.to_string());
assert_eq!(
err.to_string(),
format!("database '{}' already exists", item)
);
}
}
#[test]
fn duplicate_table() {
for item in ITEMS {
let err = ErrorCode::DuplicateTable(item.to_string());
assert_eq!(err.to_string(), format!("table '{}' already exists", item));
}
}
} }
#[derive(Debug)] #[derive(Clone, Debug)]
pub struct MTTError { pub struct MTTError {
pub code: ErrorCode, pub code: ErrorCode,
} }

View File

@ -0,0 +1,89 @@
mod static_string;
use crate::morethantext::error::MTTError;
use static_string::StaticString;
use std::fmt;
pub enum FieldType {
StaticString(StaticString),
}
impl FieldType {
fn new(ftype: &str, data: &str) -> Result<Self, MTTError> {
let field = match ftype {
"StaticString" => StaticString::new(data),
_ => Err(MTTError::new(format!(
"field type {} does not exist",
ftype
))),
};
match field {
Ok(fld) => Ok(fld.into()),
Err(e) => Err(e),
}
}
}
impl fmt::Display for FieldType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FieldType::StaticString(data) => write!(f, "{}", data),
}
}
}
impl From<StaticString> for FieldType {
fn from(data: StaticString) -> Self {
FieldType::StaticString(data)
}
}
#[cfg(test)]
mod converstion {
use super::*;
#[test]
fn from_static_string() {
let data = "a static string";
let field = StaticString::new(data).unwrap();
let ftype: FieldType = field.into();
assert!(
ftype.to_string() == data,
"\n\nGot: {}\nWant: {}",
ftype.to_string(),
data
);
}
#[test]
fn bad_field_type() -> Result<(), String> {
let field_type = "dragon";
let err_msg = format!("field type {} does not exist", field_type);
match FieldType::new(field_type, "marmalade") {
Ok(_) => Err("Should have returned an error.".to_string()),
Err(err) => {
if err.to_string() == err_msg {
Ok(())
} else {
Err(format!(
"Error message is incorrect: Got: '{}' Want: '{}'",
err.to_string(),
err_msg
))
}
}
}
}
#[test]
fn new_static_string() {
let data = "This is a test.";
let field = FieldType::new("StaticString", data).unwrap();
assert!(
field.to_string() == data,
"\n\nGot: {}\nWant: {}\n\n",
field.to_string(),
data
);
}
}

View File

@ -0,0 +1,50 @@
use crate::morethantext::error::MTTError;
use std::fmt;
pub struct StaticString {
data: String,
}
impl StaticString {
pub fn new<S>(name: S) -> Result<Self, MTTError>
where
S: Into<String>,
{
Ok(Self { data: name.into() })
}
}
impl fmt::Display for StaticString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", &self.data)
}
}
#[cfg(test)]
mod creation {
use super::*;
#[test]
fn new_accepts_str() {
let data = "some data";
let field = StaticString::new(data).unwrap();
assert!(
field.to_string() == data,
"\n\nGot: {}\nWant: {}",
field.to_string(),
data
);
}
#[test]
fn new_accepts_string() {
let data = "actual string";
let field = StaticString::new(data.to_string()).unwrap();
assert!(
field.to_string() == data,
"\n\nGot: {}\nWant: {}",
field.to_string(),
data
);
}
}

179
src/morethantext/graphql.rs Normal file
View File

@ -0,0 +1,179 @@
use async_graphql::{Context, EmptySubscription, Error, Object, Result, Schema};
use async_std::sync::RwLock;
use serde_json;
mod database;
#[derive(Clone)]
struct Table {
name: String,
}
impl Table {
async fn new(name: String) -> Self {
Self { name: name }
}
}
#[Object]
impl Table {
async fn name(&self) -> String {
self.name.to_string()
}
async fn describe(&self) -> Vec<u64> {
Vec::new()
}
}
struct Query;
#[Object]
impl Query {
async fn table(&self, ctx: &Context<'_>, name: String) -> Result<Option<Table>> {
let tbls = ctx
.data::<RwLock<Vec<Table>>>()
.unwrap()
.read()
.await
.to_vec();
match tbls.binary_search_by(|t| t.name.cmp(&name)) {
Ok(idx) => Ok(Some(tbls[idx].clone())),
Err(_) => Ok(None),
}
}
async fn tables(&self, ctx: &Context<'_>) -> Vec<Table> {
ctx.data::<RwLock<Vec<Table>>>()
.unwrap()
.read()
.await
.to_vec()
}
}
struct Mutation;
#[Object]
impl Mutation {
async fn create_table(&self, ctx: &Context<'_>, name: String) -> Result<Option<Table>> {
let mut tables = ctx.data::<RwLock<Vec<Table>>>().unwrap().write().await;
match tables.binary_search_by(|t| t.name.cmp(&name)) {
Ok(_) => Err(Error::new(format!("Table {} already exists.", &name))),
Err(_) => {
let output = Table::new(name).await;
tables.push(output.clone());
tables.sort_by_key(|k| k.name.clone());
Ok(Some(output))
}
}
}
}
#[derive(Clone)]
pub struct MoreThanText {
schema: Schema<Query, Mutation, EmptySubscription>,
}
impl MoreThanText {
pub fn new() -> Self {
let tables: Vec<Table> = Vec::new();
Self {
schema: Schema::build(Query, Mutation, EmptySubscription)
.data(RwLock::new(tables))
.finish(),
}
}
pub async fn execute(&self, qry: &str) -> String {
let res = self.schema.execute(qry).await;
serde_json::to_string(&res).unwrap()
}
}
#[cfg(test)]
mod support {
use super::*;
pub fn compare(db: &MoreThanText, output: &str, expected: &str) {
assert!(
output == expected,
"\n\n{}\nGot: {}\nWant: {}\n\n",
db.schema.sdl(),
output,
expected
);
}
}
#[cfg(test)]
mod queries {
use super::*;
#[async_std::test]
async fn list_table() {
let db = MoreThanText::new();
db.execute(r#"mutation {createTable(name: "wilma"){name}}"#)
.await;
db.execute(r#"mutation {createTable(name: "betty"){name}}"#)
.await;
let output = db.execute(r#"{table(name: "wilma"){name}}"#).await;
let expected = r#"{"data":{"table":{"name":"wilma"}}}"#;
support::compare(&db, &output, &expected);
}
#[async_std::test]
async fn list_no_table() {
let db = MoreThanText::new();
let output = db.execute(r#"{table(name: "slade"){name}}"#).await;
let expected = r#"{"data":{"table":null}}"#;
support::compare(&db, &output, &expected);
}
#[async_std::test]
async fn list_tables() {
let db = MoreThanText::new();
db.execute(r#"mutation {createTable(name: "fred"){name}}"#)
.await;
db.execute(r#"mutation {createTable(name: "barney"){name}}"#)
.await;
let output = db.execute(r#"{tables{name}}"#).await;
let expected = r#"{"data":{"tables":[{"name":"barney"},{"name":"fred"}]}}"#;
support::compare(&db, &output, &expected);
}
#[async_std::test]
async fn empty_table_description() {
let db = MoreThanText::new();
let output = db
.execute(r#"mutation {createTable(name: "pebbles"){name describe}}"#)
.await;
let expected = r#"{"data":{"createTable":{"name":"pebbles","describe":[]}}}"#;
support::compare(&db, &output, &expected);
}
}
#[cfg(test)]
mod mutations {
use super::*;
#[async_std::test]
async fn add_table() {
let db = MoreThanText::new();
let output = db
.execute(r#"mutation {createTable(name: "william"){name}}"#)
.await;
let expected = r#"{"data":{"createTable":{"name":"william"}}}"#;
support::compare(&db, &output, &expected);
}
#[async_std::test]
async fn cannot_add_duplicate_table() {
let db = MoreThanText::new();
let qry = r#"mutation {createTable(name: "gadzoo"){name}}"#;
db.execute(&qry).await;
let output = db.execute(qry).await;
let expected = r#"{"data":null,"errors":[{"message":"Table gadzoo already exists.","locations":[{"line":1,"column":11}],"path":["createTable"]}]}"#;
support::compare(&db, &output, &expected);
}
}

View File

@ -1,6 +1,8 @@
mod cache; mod cache;
mod database;
mod error; mod error;
mod store; mod store;
mod table;
use async_std::{ use async_std::{
channel::{unbounded, Sender}, channel::{unbounded, Sender},
@ -8,30 +10,35 @@ use async_std::{
task::spawn, task::spawn,
}; };
use cache::Cache; use cache::Cache;
use database::Database;
use error::{ErrorCode, MTTError}; use error::{ErrorCode, MTTError};
use store::Store; use store::Store;
use table::Table;
const ENTRY: &str = "EntryPoint"; const ENTRY: &str = "EntryPoint";
#[derive(Debug)] #[derive(Debug)]
pub struct CacheGet { pub struct ToCacheMsg<D> {
id: String, data: D,
result: Sender<FromCache>, result: Sender<FromCache>,
} }
#[derive(Debug)] #[derive(Debug)]
pub enum ToCache { pub enum ToCache {
Get(CacheGet), Get(ToCacheMsg<String>),
Commit(ToCacheMsg<Store>),
} }
#[derive(Debug)] #[derive(Clone, Debug)]
pub enum FromCache { pub enum FromCache {
Ok,
Str(Store), Str(Store),
DB(Database),
Error(MTTError), Error(MTTError),
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
struct Data<D> { pub struct Data<D> {
id: Option<String>, id: Option<String>,
data: Option<D>, data: Option<D>,
} }
@ -46,6 +53,13 @@ impl<D> Data<D> {
data: None, data: None,
} }
} }
fn from_data(data: D) -> Self {
Self {
id: None,
data: Some(data),
}
}
} }
#[derive(Clone)] #[derive(Clone)]
@ -64,14 +78,29 @@ impl MoreThanText {
async fn session(&self) -> Result<Store, MTTError> { async fn session(&self) -> Result<Store, MTTError> {
let (s, r) = unbounded(); let (s, r) = unbounded();
let msg = CacheGet { let msg = ToCacheMsg {
id: ENTRY.to_string(), data: ENTRY.to_string(),
result: s, result: s,
}; };
self.to_cache.send(ToCache::Get(msg)).await.unwrap(); self.to_cache.send(ToCache::Get(msg)).await.unwrap();
match r.recv().await.unwrap() { match r.recv().await.unwrap() {
FromCache::Str(store) => Ok(store), FromCache::Str(store) => Ok(store),
FromCache::Error(err) => Err(err), FromCache::Error(err) => Err(err),
_ => unreachable!(),
}
}
async fn commit(&self, store: Store) -> Result<(), MTTError> {
let (s, r) = unbounded();
let msg = ToCacheMsg {
data: store,
result: s,
};
self.to_cache.send(ToCache::Commit(msg)).await.unwrap();
match r.recv().await.unwrap() {
FromCache::Ok => Ok(()),
FromCache::Error(err) => Err(err),
_ => unreachable!(),
} }
} }
} }
@ -91,6 +120,56 @@ mod mtt {
let expected: Vec<String> = Vec::new(); let expected: Vec<String> = Vec::new();
assert_eq!(store.list(), expected); assert_eq!(store.list(), expected);
} }
#[async_std::test]
async fn commit_db() {
let dir = tempdir().unwrap();
let db = "fred";
let mtt = start_db(dir.path()).await.unwrap();
let mut store = mtt.session().await.unwrap();
store.add(db).unwrap();
mtt.commit(store).await.unwrap();
let store2 = mtt.session().await.unwrap();
assert_eq!(store2.list(), [db]);
}
#[async_std::test]
async fn commit_from_multiple_sources() {
let dir = tempdir().unwrap();
let mtt1 = start_db(dir.path()).await.unwrap();
let mtt2 = mtt1.clone();
let db1 = "first";
let db2 = "second";
let mut store1 = mtt1.session().await.unwrap();
let mut store2 = mtt2.session().await.unwrap();
store1.add(db1).unwrap();
store2.add(db2).unwrap();
mtt1.commit(store1).await.unwrap();
mtt2.commit(store2).await.unwrap();
let output = mtt1.session().await.unwrap();
assert_eq!(output.list(), [db1, db2]);
}
#[async_std::test]
async fn fail_on_duplicates() {
let dir = tempdir().unwrap();
let mtt1 = start_db(dir.path()).await.unwrap();
let mtt2 = mtt1.clone();
let name = "unique_only";
let mut store1 = mtt1.session().await.unwrap();
let mut store2 = mtt2.session().await.unwrap();
store1.add(name).unwrap();
store2.add(name).unwrap();
mtt1.commit(store1).await.unwrap();
let output = mtt2.commit(store2).await;
match output {
Ok(_) => assert!(false, "Should have returned an error"),
Err(err) => match err.code {
ErrorCode::DuplicateDatabase(_) => (),
_ => assert!(false, "{:?} is not ErrorCode::DuplicateDatabase", err.code),
},
}
}
} }
pub async fn start_db<P>(dir: P) -> Result<MoreThanText, MTTError> pub async fn start_db<P>(dir: P) -> Result<MoreThanText, MTTError>
@ -100,7 +179,7 @@ where
let path = dir.into(); let path = dir.into();
let (s, r) = unbounded(); let (s, r) = unbounded();
spawn(async move { spawn(async move {
let cache = Cache::new(path).await; let mut cache = Cache::new(path).await;
cache.listen(r).await; cache.listen(r).await;
}); });
Ok(MoreThanText::new(s)) Ok(MoreThanText::new(s))

View File

@ -0,0 +1,6 @@
char = _{ ASCII_ALPHANUMERIC | "_" }
whitespace = _{" " | "\t" | "\r" | "\n"}
name = {char+}
command = {"create database" ~ whitespace+ ~ name ~ ";"}
script = {command+}

398
src/morethantext/old-mod.rs Normal file
View File

@ -0,0 +1,398 @@
/*
use async_std::sync::{Arc, RwLock};
use std::{collections::HashMap, error::Error, fmt, str::FromStr};
#[derive(Debug)]
pub struct DBError {
detail: String,
source: Option<Box<DBError>>,
}
impl DBError {
fn new(detail: String) -> Self {
Self {
detail: detail.to_string(),
source: None,
}
}
}
impl fmt::Display for DBError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", &self.detail)
}
}
impl Error for DBError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match &self.source {
Some(err) => Some(err),
None => None,
}
}
}
#[derive(Clone, PartialEq)]
pub enum FieldType {
Table,
}
impl fmt::Display for FieldType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
FieldType::Table => write!(f, "table"),
}
}
}
impl FromStr for FieldType {
type Err = DBError;
fn from_str(input: &str) -> Result<FieldType, Self::Err> {
match input {
"table" => Ok(FieldType::Table),
_ => Err(DBError::new(format!("field type {} does not exist", input))),
}
}
}
pub struct Table {
fields: Arc<RwLock<HashMap<String, FieldType>>>,
}
impl Table {
pub async fn new() -> Self {
Self {
fields: Arc::new(RwLock::new(HashMap::new())),
}
}
pub async fn update_field(&self, name: &str, ftype: &str) -> Result<(), Box<dyn Error>> {
let ftype = match FieldType::from_str(ftype) {
Ok(field) => field,
Err(err) => {
let mut error = DBError::new(format!("failed to add field {}", name));
error.source = Some(Box::new(err));
return Err(Box::new(error));
}
};
let mut fmap = self.fields.write().await;
match fmap.get(name) {
Some(_) => Err(Box::new(DBError::new(format!(
"field {} already exists",
name
)))),
None => {
fmap.insert(name.to_string(), ftype);
Ok(())
}
}
}
pub async fn fields(&self) -> HashMap<String, FieldType> {
let fmap = self.fields.read().await;
fmap.clone()
}
}
*/
use async_std::sync::{Arc, RwLock};
use std::collections::HashMap;
pub mod error;
mod fieldtype;
use error::MTTError;
use fieldtype::FieldType;
#[derive(Clone)]
pub struct MoreThanText;
impl MoreThanText {
pub async fn new() -> Self {
Self {}
}
pub async fn add_table(&self, name: &str) -> Table {
Table::new()
}
pub async fn get_table(&self, name: &str) -> Table {
Table::new()
}
}
#[derive(Clone, PartialEq)]
struct FieldDef;
pub struct Table {
fields: Arc<RwLock<HashMap<String, FieldDef>>>,
}
impl Table {
fn new() -> Self {
Self {
fields: Arc::new(RwLock::new(HashMap::new())),
}
}
async fn add_field(&self, name: &str) {
let mut field_defs = self.fields.write().await;
field_defs.insert(name.to_string(), FieldDef {});
}
async fn get_field(&self, name: &str) -> Option<FieldDef> {
let field_defs = self.fields.read().await;
match field_defs.get(name) {
Some(def) => Some(def.clone()),
None => None,
}
}
async fn new_record(&self) -> Record {
Record::new()
}
}
struct Record {
data: Arc<RwLock<HashMap<String, FieldType>>>,
}
impl Record {
fn new() -> Self {
Self {
data: Arc::new(RwLock::new(HashMap::new())),
}
}
/*
async fn update_field(&self, name: String, data: FieldType) {
let mut map = self.data.write().await;
map.insert(name, data);
}
async fn get_field(&self, name: &str) -> Option<FieldType> {
let map = self.data.read().await;
match map.get(name) {
Some(field) => Some(field.clone()),
None => None,
}
}
*/
}
#[cfg(test)]
mod databases {
use super::*;
#[async_std::test]
async fn new_database() {
MoreThanText::new().await;
}
async fn add_table() {
let db = MoreThanText::new().await;
let name = "table";
db.add_table(name).await;
db.get_table(name).await;
}
}
#[cfg(test)]
mod tables {
use super::*;
#[test]
fn new_table() {
Table::new();
}
#[async_std::test]
async fn add_field_definition() {
let tbl = Table::new();
let name = "field";
let expected = FieldDef {};
tbl.add_field(name).await;
let output = tbl.get_field(name).await.unwrap();
assert!(output == expected, "Did not return a field definition.");
}
#[async_std::test]
async fn missing_field_definition() {
let tbl = Table::new();
let output = tbl.get_field("missing").await;
assert!(
output == None,
"Should return None if field does not exist."
);
}
#[async_std::test]
async fn get_empty_record() {
let tbl = Table::new();
tbl.new_record().await;
}
}
#[cfg(test)]
mod records {
use super::*;
/*
#[async_std::test]
async fn update_fields() {
let rec = Record::new();
let name = "elephant";
let data = "";
let sstr = StaticString::new();
rec.update_field(name.to_string(), sstr).await;
let output = rec.get_field(name).await.unwrap();
assert!(
output.to_string() == data,
"\n\nGot: {}\nWant: {}\n\n",
output.to_string(),
data
)
}
#[async_std::test]
async fn empty_field() {
let rec = Record::new();
let name = "mull";
let output = rec.get_field(name).await;
assert!(output == None, "Should return an option.");
}
*/
}
/*
#[cfg(test)]
mod tables {
use super::*;
#[async_std::test]
async fn new_table() {
Table::new().await;
}
#[async_std::test]
async fn update_field() {
let table = Table::new().await;
let mut expected: HashMap<String, FieldType> = HashMap::new();
expected.insert("stan".to_string(), FieldType::Table);
expected.insert("lee".to_string(), FieldType::Table);
table.update_field("stan", "table").await.unwrap();
table.update_field("lee", "table").await.unwrap();
let output = table.fields().await;
assert!(output == expected, "Table did not get the fields added.");
}
#[async_std::test]
async fn add_bad_field() -> Result<(), String> {
let table = Table::new().await;
let name = "failure";
let bad_type = "ljksdbtt";
let expected = format!("failed to add field {}", name);
let source = format!("field type {} does not exist", bad_type);
match table.update_field(name, bad_type).await {
Ok(_) => Err("A bad field type should not return successfully".to_string()),
Err(err) => {
if format!("{}", err) != expected {
Err(format!("Got: '{}' - Want: '{}'", err, expected))
} else if format!("{}", err.source().unwrap()) != source {
Err(format!(
"Got: '{}' - Want: '{}'",
err.source().unwrap(),
source
))
} else {
Ok(())
}
}
}
}
#[async_std::test]
async fn add_duplicate_field() -> Result<(), String> {
let table = Table::new().await;
let name = "twice";
let expected = format!("field {} already exists", name);
table.update_field(name, "table").await.unwrap();
match table.update_field(name, "table").await {
Ok(_) => Err(format!("Cannot have two fields with named '{}'", name)),
Err(err) => {
if format!("{}", err) == expected {
Ok(())
} else {
Err(format!("Got: '{}' - Want: '{}'", err, expected))
}
}
}
}
}
#[cfg(test)]
mod databases {
use super::*;
#[async_std::test]
async fn new_database() {
MoreThanText::new().await;
}
#[async_std::test]
async fn add_table() {
let db = MoreThanText::new().await;
db.add_table("fred".to_string()).await;
}
}
#[cfg(test)]
mod fieldtypes {
use super::*;
fn get_field_map() -> HashMap<String, FieldType> {
let mut fields: HashMap<String, FieldType> = HashMap::new();
fields.insert("table".to_string(), FieldType::Table);
return fields;
}
#[test]
fn convert_to_string() {
for (key, value) in get_field_map().iter() {
assert!(
key == &value.to_string(),
"\n\nGot: {}\nWant: {}\n\n",
value.to_string(),
key
);
}
}
#[test]
fn convert_from_string() {
for (key, value) in get_field_map().iter() {
assert!(
&FieldType::from_str(key).unwrap() == value,
"\n\nDid not return a FieldType::{}",
key
);
}
}
#[test]
fn convert_from_string_error() -> Result<(), String> {
let ftype = "lkjsdfh";
let expected = format!("field type {} does not exist", ftype);
match FieldType::from_str(ftype) {
Ok(_) => Err(format!("Found field type {}", ftype)),
Err(err) => {
if format!("{}", err) == expected {
Ok(())
} else {
Err(format!("Got: '{}' - Want: '{}'", err, expected))
}
}
}
}
}
*/

View File

@ -0,0 +1,120 @@
pub mod error;
pub mod fieldtype;
use async_std::sync::{Arc, RwLock};
use error::MTTError;
use std::collections::HashMap;
#[derive(Clone)]
pub struct MoreThanText {
tables: Arc<RwLock<HashMap<String, Table>>>,
}
impl MoreThanText {
pub async fn new() -> Self {
Self {
tables: Arc::new(RwLock::new(HashMap::new())),
}
}
pub async fn new_table<S>(&self, tname: S) -> Result<Table, MTTError>
where
S: Into<String>,
{
let mut tables = self.tables.write().await;
let name = tname.into();
match tables.get(&name) {
Some(_) => Err(MTTError::new(format!("table {} already exists", name))),
None => {
let table = Table::new().await;
tables.insert(name, table.clone());
Ok(table)
}
}
}
pub async fn get_table(&self, name: &str) -> Option<Table> {
let tables = self.tables.read().await;
match tables.get(name) {
Some(tbl) => Some(tbl.clone()),
None => None,
}
}
}
#[derive(Clone)]
pub struct Table;
impl Table {
pub async fn new() -> Self {
Self {}
}
async fn new_column(&self, _name: &str, _type: &str) {}
}
#[cfg(test)]
mod database {
use super::*;
#[async_std::test]
async fn create_table_with_str() {
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();
}
#[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
))
}
}
}
}
#[async_std::test]
async fn get_non_existant_table() {
let db = MoreThanText::new().await;
let table = db.get_table("missing").await;
assert!(table.is_none(), "There should be no table.");
}
#[async_std::test]
async fn get_a_table() {
let db = MoreThanText::new().await;
let name = "here";
db.new_table(name).await.unwrap();
let table = db.get_table(name).await;
assert!(table.is_some(), "Table should be found.");
}
}
#[cfg(test)]
mod table {
use super::*;
#[async_std::test]
async fn add_column() {
let tbl = Table::new().await;
tbl.new_column("fred", "StaticString").await;
}
}

View File

@ -0,0 +1,153 @@
pub mod error;
use async_std::sync::{Arc, RwLock};
use error::DBError;
use std::collections::HashMap;
#[derive(Clone)]
pub struct MoreThanText {
databases: Arc<RwLock<HashMap<String, Database>>>,
}
impl MoreThanText {
pub async fn new() -> Self {
Self {
databases: Arc::new(RwLock::new(HashMap::new())),
}
}
async fn create_database(&self, name: &str) -> Result<(), DBError> {
let mut databases = self.databases.write().await;
match databases.get(name) {
Some(_) => Err(DBError::new("duplicate database name")),
None => {
let db = Database::new().await;
databases.insert(name.to_string(), db);
Ok(())
}
}
}
async fn use_database(&self, name: &str) -> Result<Database, DBError> {
let databases = self.databases.read().await;
match databases.get(name) {
Some(db) => Ok(db.clone()),
None => Err(DBError::new("database name not found")),
}
}
}
#[derive(Clone)]
struct Database;
impl Database {
async fn new() -> Self {
Self {}
}
async fn add_table(&self, _name: &str) {}
}
struct Table;
impl Table {
async fn new() -> Self {
Self {}
}
}
#[cfg(test)]
mod engine_functions {
use super::*;
#[async_std::test]
async fn create_database() {
let mtt = MoreThanText::new().await;
mtt.create_database("smith").await.unwrap();
}
#[async_std::test]
async fn database_names_must_be_unique() -> Result<(), DBError> {
let mtt = MoreThanText::new().await;
let msg = "duplicate database name";
mtt.create_database("john").await.unwrap();
match mtt.create_database("john").await {
Ok(_) => Err(DBError::new("Duplicate names should cause error")),
Err(err) => {
if err.to_string() == msg {
Ok(())
} else {
Err(DBError::new(format!(
"incorrect err message: got: '{}' want: '{}'",
err.to_string(),
msg
)))
}
}
}
}
#[async_std::test]
async fn use_database() -> Result<(), DBError> {
let mtt = MoreThanText::new().await;
let dbname = "Johnson";
mtt.create_database(dbname).await.unwrap();
mtt.use_database(dbname).await.unwrap();
Ok(())
}
#[async_std::test]
async fn use_missing_database() -> Result<(), DBError> {
let error = "database name not found";
let mtt = MoreThanText::new().await;
match mtt.use_database("ssmith").await {
Ok(_) => Err(DBError::new("Should raise database missing error")),
Err(err) => {
if err.to_string() == error {
Ok(())
} else {
Err(DBError::new(format!(
"Incorrect error message: Got '{}' Want '{}'",
err.to_string(),
error
)))
}
}
}
}
#[async_std::test]
async fn create_get_table() {
let db = "thedatabase";
let mtt = MoreThanText::new().await;
mtt.create_database(db).await.unwrap();
let dbase = mtt.use_database(db).await.unwrap();
dbase.add_table("melvin").await;
}
}
#[cfg(test)]
mod database_functions {
use super::*;
#[async_std::test]
async fn new_database() {
Database::new().await;
}
#[async_std::test]
async fn new_table() {
let db = Database::new().await;
db.add_table("fred").await;
}
}
#[cfg(test)]
mod table_functions {
use super::*;
#[async_std::test]
async fn new_table() {
Table::new().await;
}
}

View File

@ -1,13 +1,58 @@
use super::{Data, Database, ErrorCode, MTTError};
use std::collections::HashMap;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Store; pub struct Store {
data: HashMap<String, Data<Database>>,
}
impl Store { impl Store {
pub fn new() -> Self { pub fn new() -> Self {
Self {} Self {
data: HashMap::new(),
}
}
pub fn add<S>(&mut self, name: S) -> Result<(), MTTError>
where
S: Into<String>,
{
let db_name = name.into();
match self.get(&db_name) {
Some(_) => Err(MTTError::from_code(ErrorCode::DuplicateDatabase(db_name))),
None => {
self.data.insert(db_name, Data::from_data(Database::new()));
Ok(())
}
}
}
pub fn add_by_id<S, D>(&mut self, name: S, id: D) -> Result<(), MTTError>
where
S: Into<String>,
D: Into<String>,
{
let db_name = name.into();
match self.get(&db_name) {
Some(_) => Err(MTTError::from_code(ErrorCode::DuplicateDatabase(db_name))),
None => {
self.data.insert(db_name, Data::from_id(id.into()));
Ok(())
}
}
}
pub fn get(&self, name: &str) -> Option<&Data<Database>> {
self.data.get(name)
} }
pub fn list(&self) -> Vec<String> { pub fn list(&self) -> Vec<String> {
Vec::new() let mut names = Vec::new();
for name in self.data.keys() {
names.push(name.to_string());
}
names.sort();
names
} }
} }
@ -21,4 +66,106 @@ mod storage {
let expected: Vec<String> = Vec::new(); let expected: Vec<String> = Vec::new();
assert_eq!(store.list(), expected); assert_eq!(store.list(), expected);
} }
#[test]
fn add_db_by_str() {
let mut store = Store::new();
let name = "Melvin";
store.add(name).unwrap();
let output = store.get(name);
assert!(output.is_some(), "Get returned none.");
}
#[test]
fn add_db_by_string() {
let mut store = Store::new();
let name = "Marvin";
store.add(name.to_string()).unwrap();
let output = store.get(name);
assert!(output.is_some(), "Get returned none.");
}
#[test]
fn fail_on_duplicates() -> Result<(), MTTError> {
let mut store = Store::new();
let name = "Mickie";
store.add(name).unwrap();
match store.add(name) {
Ok(_) => Err(MTTError::new("duplicates should error")),
Err(err) => match err.code {
ErrorCode::DuplicateDatabase(db_name) => {
assert_eq!(db_name, name);
Ok(())
}
_ => Err(MTTError::new(format!("{:?} is not DuplicateDatabase", err))),
},
}
}
#[test]
fn add_using_cache_id() {
let mut store = Store::new();
let name = "fred";
let id = "12345";
store.add_by_id(name, id).unwrap();
let output = store.get(name).unwrap();
assert!(output.data.is_none(), "there should be no data");
assert_eq!(output.id, Some(id.to_string()));
}
#[test]
fn add_by_cache_id_name_string() {
let mut store = Store::new();
let name = "barney";
let id = "67890";
store.add_by_id(name.to_string(), id).unwrap();
let output = store.get(name).unwrap();
assert!(output.data.is_none(), "there should be no data");
assert_eq!(output.id, Some(id.to_string()));
}
#[test]
fn no_duplicate_databases_for_add_by_id() {
let mut store = Store::new();
let name = "betty";
store.add_by_id(name, "fghij").unwrap();
match store.add_by_id(name, "klmno") {
Ok(_) => assert!(false, "Duplicates should error."),
Err(err) => match err.code {
ErrorCode::DuplicateDatabase(db_name) => assert_eq!(db_name, name),
_ => assert!(false, "{:?} is not DuplicateDatabase", err),
},
}
}
#[test]
fn add_by_cache_id_string() {
let mut store = Store::new();
let name = "wilma";
let id = "abcdef";
store.add_by_id(name, id.to_string()).unwrap();
let output = store.get(name).unwrap();
assert!(output.data.is_none(), "there should be no data");
assert_eq!(output.id, Some(id.to_string()));
}
#[test]
fn get_bad_database() -> Result<(), MTTError> {
let store = Store::new();
match store.get("missing") {
Some(_) => Err(MTTError::new("Should have returned None.")),
None => Ok(()),
}
}
#[test]
fn get_list() {
let mut store = Store::new();
let mut ids = ["one", "two", "three", "four", "five"];
for name in ids {
store.add(name.to_string()).unwrap();
}
ids.sort();
assert_eq!(store.list(), ids);
}
} }

18
src/morethantext/table.rs Normal file
View File

@ -0,0 +1,18 @@
#[derive(Clone, Debug)]
pub struct Table;
impl Table {
pub fn new() -> Self {
Self {}
}
}
#[cfg(test)]
mod tables {
use super::*;
#[test]
fn create_new() {
Table::new();
}
}