From 99e84d8f775be373e42926b5a34adfca2217592f Mon Sep 17 00:00:00 2001 From: Rushmore Mushambi Date: Sat, 2 Sep 2023 08:40:49 +0200 Subject: [PATCH] Return an error when `db.connect()` is called multiple times (#2576) --- lib/src/api/err/mod.rs | 4 ++++ lib/src/api/mod.rs | 15 +++++++++------ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/lib/src/api/err/mod.rs b/lib/src/api/err/mod.rs index 55026e3a..328b8094 100644 --- a/lib/src/api/err/mod.rs +++ b/lib/src/api/err/mod.rs @@ -33,6 +33,10 @@ pub enum Error { #[error("Connection uninitialised")] ConnectionUninitialised, + /// Tried to call `connect` on an instance already connected + #[error("Already connected")] + AlreadyConnected, + /// `Query::bind` not called with an object nor a key/value tuple #[error("Invalid bindings: {0}")] InvalidBindings(Value), diff --git a/lib/src/api/mod.rs b/lib/src/api/mod.rs index 7ac4db96..1b589654 100644 --- a/lib/src/api/mod.rs +++ b/lib/src/api/mod.rs @@ -103,15 +103,18 @@ where fn into_future(self) -> Self::IntoFuture { Box::pin(async move { + // Avoid establising another connection if already connected + if self.router.get().is_some() { + return Err(Error::AlreadyConnected.into()); + } let arc = Client::connect(self.address?, self.capacity).await?.router; let cell = Arc::into_inner(arc).expect("new connection to have no references"); let router = cell.into_inner().expect("router to be set"); - if self.router.set(router).is_ok() { - let client = Surreal { - router: self.router, - }; - client.check_server_version().await?; - } + self.router.set(router).map_err(|_| Error::AlreadyConnected)?; + let client = Surreal { + router: self.router, + }; + client.check_server_version().await?; Ok(()) }) }