diff --git a/src/connection.rs b/src/connection.rs index 36bfe4c5..b929d377 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -8,6 +8,7 @@ use crate::{ use crossbeam_queue::SegQueue; use crossbeam_utils::atomic::AtomicCell; use futures_channel::oneshot::{channel, Sender}; +use futures_util::TryFutureExt; use futures_core::{future::BoxFuture, stream::BoxStream}; use futures_util::stream::StreamExt; use std::{ @@ -38,6 +39,11 @@ pub trait RawConnection: Send { /// and clean up not fully closed connections. fn finalize<'c>(&'c mut self) -> BoxFuture<'c, Result<(), Error>>; + /// Verifies a connection to the database is still alive. + fn ping<'c>(&'c mut self) -> BoxFuture<'c, Result<(), Error>> { + Box::pin(self.execute("SELECT 1", ::QueryParameters::new()).map_ok(|_| ())) + } + fn execute<'c>( &'c mut self, query: &str, @@ -89,6 +95,12 @@ where async fn get(&self) -> ConnectionFairy<'_, DB> { ConnectionFairy::new(&self.0, self.0.acquire().await) } + + /// Verifies a connection to the database is still alive. + pub async fn ping(&mut self) -> crate::Result<()> { + let mut conn = self.get().await; + conn.ping().await + } } impl Executor for Connection diff --git a/src/postgres/mod.rs b/src/postgres/mod.rs index 181ab391..ee9071d4 100644 --- a/src/postgres/mod.rs +++ b/src/postgres/mod.rs @@ -13,24 +13,31 @@ pub use self::{ #[cfg(test)] mod tests { - use super::{Postgres, PostgresRawConnection}; - use crate::connection::{Connection, RawConnection}; + use super::Postgres; + use crate::connection::Connection; use futures_util::TryStreamExt; const DATABASE_URL: &str = "postgres://postgres@127.0.0.1:5432/"; #[tokio::test] async fn it_connects() { - let mut conn = PostgresRawConnection::establish(DATABASE_URL) + let _conn = Connection::::establish(DATABASE_URL) + .await + .unwrap(); + } + + #[tokio::test] + async fn it_pings() { + let mut conn = Connection::::establish(DATABASE_URL) .await .unwrap(); - conn.finalize().await.unwrap(); + conn.ping().await.unwrap(); } #[tokio::test] async fn it_fails_on_connect_with_an_unknown_user() { - let res = PostgresRawConnection::establish("postgres://not_a_user@127.0.0.1:5432/").await; + let res = Connection::::establish("postgres://not_a_user@127.0.0.1:5432/").await; match res { Err(crate::Error::Database(err)) => { @@ -44,7 +51,7 @@ mod tests { #[tokio::test] async fn it_fails_on_connect_with_an_unknown_database() { let res = - PostgresRawConnection::establish("postgres://postgres@127.0.0.1:5432/fdggsdfgsdaf") + Connection::::establish("postgres://postgres@127.0.0.1:5432/fdggsdfgsdaf") .await; match res {