Skip to content

Commit 07d9fb2

Browse files
author
zach-com
committed
Support connection validation with timeout
1 parent 8f2ae86 commit 07d9fb2

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

postgres/src/client.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,11 @@ impl Client {
413413
self.connection.block_on(self.client.simple_query(query))
414414
}
415415

416+
/// Validates connection, timing out after specified duration.
417+
pub fn is_valid(&mut self, timeout: std::time::Duration) -> Result<(), Error> {
418+
self.connection.block_on(self.client.is_valid(timeout))
419+
}
420+
416421
/// Executes a sequence of SQL statements using the simple query protocol.
417422
///
418423
/// Statements should be separated by semicolons. If an error occurs, execution of the sequence will stop at that

tokio-postgres/src/client.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,15 @@ impl Client {
450450
self.simple_query_raw(query).await?.try_collect().await
451451
}
452452

453+
/// Validates connection, timing out after specified duration.
454+
pub async fn is_valid(&self, timeout: Duration) -> Result<(), Error> {
455+
type SqmResult = Result<Vec<SimpleQueryMessage>, Error>;
456+
type SqmTimeout = Result<SqmResult, tokio::time::error::Elapsed>;
457+
let sqm_future = self.simple_query_raw("").await?.try_collect();
458+
let sqm_timeout: SqmTimeout = tokio::time::timeout(timeout, sqm_future).await;
459+
sqm_timeout.map_err(|_| Error::timeout())?.map(|_| ())
460+
}
461+
453462
pub(crate) async fn simple_query_raw(&self, query: &str) -> Result<SimpleQueryStream, Error> {
454463
simple_query::simple_query(self.inner(), query).await
455464
}

tokio-postgres/src/error/mod.rs

Lines changed: 6 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,8 @@ impl Error {
491493
pub(crate) fn connect(e: io::Error) -> Error {
492494
Error::new(Kind::Connect, Some(Box::new(e)))
493495
}
496+
497+
pub(crate) fn timeout() -> Error {
498+
Error::new(Kind::Timeout, None)
499+
}
494500
}

0 commit comments

Comments
 (0)