Add a ping method on Connection to verify the connection is still valid

This commit is contained in:
Ryan Leckey 2019-09-02 17:00:44 -07:00
parent 247dd84420
commit fe697fee1d
2 changed files with 25 additions and 6 deletions

View File

@ -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", <Self::Backend as Backend>::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<DB> Executor for Connection<DB>

View File

@ -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::<Postgres>::establish(DATABASE_URL)
.await
.unwrap();
}
#[tokio::test]
async fn it_pings() {
let mut conn = Connection::<Postgres>::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::<Postgres>::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::<Postgres>::establish("postgres://postgres@127.0.0.1:5432/fdggsdfgsdaf")
.await;
match res {