Skip to content

improve is_closed effectiveness #1229

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat: add support for quick active health checks on connections
  • Loading branch information
conradludgate committed Mar 26, 2025
commit 720897d36dde608087dfde927c1892c46af46888
6 changes: 6 additions & 0 deletions tokio-postgres/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,12 @@ impl Client {
simple_query::batch_execute(self.inner(), query).await
}

/// Check the connection is alive and wait for the confirmation.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/// Check the connection is alive and wait for the confirmation.
/// Check that the connection is alive and wait for the confirmation.

pub async fn check_connection(&self) -> Result<(), Error> {
// sync is a very quick message to test the connection health.
query::sync(self.inner()).await
}

/// Begins a new database transaction.
///
/// The transaction will roll back by default - use the `commit` method to commit it.
Expand Down
10 changes: 10 additions & 0 deletions tokio-postgres/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,3 +323,13 @@ impl RowStream {
self.rows_affected
}
}

pub async fn sync(client: &InnerClient) -> Result<(), Error> {
let buf = Bytes::from_static(b"S\0\0\0\x04");
let mut responses = client.send(RequestMessages::Single(FrontendMessage::Raw(buf)))?;

match responses.next().await? {
Message::ReadyForQuery(_) => Ok(()),
_ => Err(Error::unexpected_message()),
}
}
6 changes: 6 additions & 0 deletions tokio-postgres/tests/test/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,12 @@ async fn scram_password_ok() {
connect("user=scram_user password=password dbname=postgres").await;
}

#[tokio::test]
async fn sync() {
let client = connect("user=postgres").await;
client.check_connection().await.unwrap();
}

#[tokio::test]
async fn pipelined_prepare() {
let client = connect("user=postgres").await;
Expand Down