From da6667356b4ac046d99e1e5948de1f42337cbdb3 Mon Sep 17 00:00:00 2001 From: SIMRAN MAKHIJA Date: Thu, 2 May 2024 00:17:09 -0400 Subject: [PATCH] rename error handling --- src/handlers/table_handler.rs | 12 ++++++++---- src/repository/table.rs | 15 ++++++++++----- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/src/handlers/table_handler.rs b/src/handlers/table_handler.rs index c9efce0..e42b0b6 100644 --- a/src/handlers/table_handler.rs +++ b/src/handlers/table_handler.rs @@ -108,9 +108,13 @@ pub async fn rename_table( State(repo): State>, request: Json, ) -> Result { - - repo.rename_table(&request) - .map(|_| StatusCode::OK) - .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Error: {}", e))) + match repo.rename_table(&request) { + Ok(_) => Ok(StatusCode::NO_CONTENT), + Err(e) => match e.kind() { + ErrorKind::NotFound => Err((StatusCode::NOT_FOUND, format!("Error: {}", e))), + ErrorKind::AlreadyExists => Err((StatusCode::CONFLICT, format!("Error: {}", e))), + _ => Err((StatusCode::INTERNAL_SERVER_ERROR, format!("Error: {}", e))), + }, + } } diff --git a/src/repository/table.rs b/src/repository/table.rs index c533153..083dc2b 100644 --- a/src/repository/table.rs +++ b/src/repository/table.rs @@ -81,7 +81,7 @@ impl TableRepository { pub fn drop_table(&self, namespace: &NamespaceIdent, table_name: String) -> Result<(), Error> { let db = self.database.lock().unwrap(); let table_id = TableIdent::new(namespace.clone(), table_name.clone()); - + let _ : Table = match db.get::("TableData", &table_id)? { Some(data) => data, None => { @@ -110,15 +110,20 @@ impl TableRepository { let source = rename_request.source.clone(); let destination = rename_request.destination.clone(); let namespace = source.namespace.clone(); + let table = self .load_table(&namespace, source.name.clone())? - .ok_or_else(|| Error::new(ErrorKind::NotFound, "Table not found"))?; - + .ok_or_else(|| Error::new(ErrorKind::NotFound, "Source table not found"))?; + + if self.table_exists(&destination.namespace, destination.name.clone())? { + return Err(Error::new(ErrorKind::AlreadyExists, "Destination table already exists")); + } + let mut new_table = table.clone(); new_table.id = destination.clone(); - self.drop_table(&namespace, source.name.clone())?; - self.create_table(&destination.namespace.clone(), &TableCreation{name: destination.name.clone()}) + self.create_table(&destination.namespace.clone(), &TableCreation{name: destination.name.clone()})?; + self.drop_table(&namespace, source.name.clone()) } }