From 3095f019231737e25f8015da18ff70bc7b24872b Mon Sep 17 00:00:00 2001 From: Jeff Baskin Date: Sun, 3 Jul 2022 10:33:50 -0400 Subject: [PATCH] No duplicate tables. --- src/lib.rs | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 1160337..4eb76e2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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> { let mut tables = ctx.data::>>().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); } }