No duplicate tables.

This commit is contained in:
Jeff Baskin 2022-07-03 10:33:50 -04:00
parent c5283cf584
commit 3095f01923
1 changed files with 20 additions and 6 deletions

View File

@ -1,4 +1,4 @@
use async_graphql::{Context, EmptySubscription, Object, Result, Schema};
use async_graphql::{Context, EmptySubscription, Error, Object, Result, Schema};
use async_std::sync::RwLock;
use serde_json;
@ -52,10 +52,15 @@ struct Mutation;
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;
let output = Table::new(name).await;
tables.push(output.clone());
tables.sort_by_key(|k| k.name.clone());
Ok(Some(output))
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))
}
}
}
}
@ -143,7 +148,16 @@ mod mutations {
.execute(r#"mutation {createTable(name: "william"){name}}"#)
.await;
let expected = r#"{"data":{"createTable":{"name":"william"}}}"#;
println!("{}", &db.schema.sdl());
support::compare(&db, &output, &expected);
}
#[async_std::test]
async fn cannot_add_duplicate_table() {
let db = Database::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);
}
}