Skip to content

Postgres connection : Getting current Handle in Drop #1395

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

Merged
merged 1 commit into from
Aug 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 6 additions & 0 deletions sqlx-core/src/pool/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,12 @@ impl<DB: Database> PoolConnection<DB> {
impl<DB: Database> Drop for PoolConnection<DB> {
fn drop(&mut self) {
if self.live.is_some() {
#[cfg(not(feature = "_rt-async-std"))]
if let Ok(handle) = sqlx_rt::Handle::try_current() {
handle.spawn(self.return_to_pool());
}

#[cfg(feature = "_rt-async-std")]
sqlx_rt::spawn(self.return_to_pool());
}
}
Expand Down
14 changes: 11 additions & 3 deletions sqlx-core/src/postgres/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,15 +260,23 @@ impl PgListener {
impl Drop for PgListener {
fn drop(&mut self) {
if let Some(mut conn) = self.connection.take() {
// Unregister any listeners before returning the connection to the pool.
sqlx_rt::spawn(async move {
let fut = async move {
let _ = conn.execute("UNLISTEN *").await;

// inline the drop handler from `PoolConnection` so it doesn't try to spawn another task
// otherwise, it may trigger a panic if this task is dropped because the runtime is going away:
// https://github.com/launchbadge/sqlx/issues/1389
conn.return_to_pool().await;
});
};

// Unregister any listeners before returning the connection to the pool.
#[cfg(not(feature = "_rt-async-std"))]
if let Ok(handle) = sqlx_rt::Handle::try_current() {
handle.spawn(fut);
}

#[cfg(feature = "_rt-async-std")]
sqlx_rt::spawn(fut);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion sqlx-rt/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ pub use native_tls;
))]
pub use tokio::{
self, fs, io::AsyncRead, io::AsyncReadExt, io::AsyncWrite, io::AsyncWriteExt, io::ReadBuf,
net::TcpStream, task::spawn, task::yield_now, time::sleep, time::timeout,
net::TcpStream, runtime::Handle, task::spawn, task::yield_now, time::sleep, time::timeout,
};

#[cfg(all(
Expand Down