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(()) }) }