Skip to content

Commit 6ed7298

Browse files
authored
Merge pull request #711 from zach-com/is-valid-timeout
Support connection validation with timeout
2 parents d1ac251 + 9856c7b commit 6ed7298

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

postgres/src/client.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use crate::{
44
ToStatement, Transaction, TransactionBuilder,
55
};
66
use std::task::Poll;
7+
use std::time::Duration;
78
use tokio_postgres::tls::{MakeTlsConnect, TlsConnect};
89
use tokio_postgres::types::{BorrowToSql, ToSql, Type};
910
use tokio_postgres::{Error, Row, SimpleQueryMessage, Socket};
@@ -413,6 +414,18 @@ impl Client {
413414
self.connection.block_on(self.client.simple_query(query))
414415
}
415416

417+
/// Validates connection, timing out after specified duration.
418+
pub fn is_valid(&mut self, timeout: Duration) -> Result<(), Error> {
419+
let inner_client = &self.client;
420+
self.connection.block_on(async {
421+
let trivial_query = inner_client.simple_query("");
422+
tokio::time::timeout(timeout, trivial_query)
423+
.await
424+
.map_err(|_| Error::timeout())?
425+
.map(|_| ())
426+
})
427+
}
428+
416429
/// Executes a sequence of SQL statements using the simple query protocol.
417430
///
418431
/// Statements should be separated by semicolons. If an error occurs, execution of the sequence will stop at that

tokio-postgres/src/error/mod.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,7 @@ enum Kind {
354354
RowCount,
355355
#[cfg(feature = "runtime")]
356356
Connect,
357+
Timeout,
357358
}
358359

359360
struct ErrorInner {
@@ -392,6 +393,7 @@ impl fmt::Display for Error {
392393
Kind::RowCount => fmt.write_str("query returned an unexpected number of rows")?,
393394
#[cfg(feature = "runtime")]
394395
Kind::Connect => fmt.write_str("error connecting to server")?,
396+
Kind::Timeout => fmt.write_str("timeout waiting for server")?,
395397
};
396398
if let Some(ref cause) = self.0.cause {
397399
write!(fmt, ": {}", cause)?;
@@ -491,4 +493,9 @@ impl Error {
491493
pub(crate) fn connect(e: io::Error) -> Error {
492494
Error::new(Kind::Connect, Some(Box::new(e)))
493495
}
496+
497+
#[doc(hidden)]
498+
pub fn timeout() -> Error {
499+
Error::new(Kind::Timeout, None)
500+
}
494501
}

0 commit comments

Comments
 (0)