Return an error when db.connect() is called multiple times (#2576)

This commit is contained in:
Rushmore Mushambi 2023-09-02 08:40:49 +02:00 committed by GitHub
parent fd73619349
commit 99e84d8f77
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 6 deletions

View file

@ -33,6 +33,10 @@ pub enum Error {
#[error("Connection uninitialised")] #[error("Connection uninitialised")]
ConnectionUninitialised, 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 /// `Query::bind` not called with an object nor a key/value tuple
#[error("Invalid bindings: {0}")] #[error("Invalid bindings: {0}")]
InvalidBindings(Value), InvalidBindings(Value),

View file

@ -103,15 +103,18 @@ where
fn into_future(self) -> Self::IntoFuture { fn into_future(self) -> Self::IntoFuture {
Box::pin(async move { 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 arc = Client::connect(self.address?, self.capacity).await?.router;
let cell = Arc::into_inner(arc).expect("new connection to have no references"); let cell = Arc::into_inner(arc).expect("new connection to have no references");
let router = cell.into_inner().expect("router to be set"); let router = cell.into_inner().expect("router to be set");
if self.router.set(router).is_ok() { self.router.set(router).map_err(|_| Error::AlreadyConnected)?;
let client = Surreal { let client = Surreal {
router: self.router, router: self.router,
}; };
client.check_server_version().await?; client.check_server_version().await?;
}
Ok(()) Ok(())
}) })
} }