Skip to content

Commit 135d16a

Browse files
authored
Getting current Handle in Drop (#1395)
Signed-off-by: Freyskeyd <[email protected]>
1 parent ad81e35 commit 135d16a

File tree

3 files changed

+18
-4
lines changed

3 files changed

+18
-4
lines changed

sqlx-core/src/pool/connection.rs

+6
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,12 @@ impl<DB: Database> PoolConnection<DB> {
133133
impl<DB: Database> Drop for PoolConnection<DB> {
134134
fn drop(&mut self) {
135135
if self.live.is_some() {
136+
#[cfg(not(feature = "_rt-async-std"))]
137+
if let Ok(handle) = sqlx_rt::Handle::try_current() {
138+
handle.spawn(self.return_to_pool());
139+
}
140+
141+
#[cfg(feature = "_rt-async-std")]
136142
sqlx_rt::spawn(self.return_to_pool());
137143
}
138144
}

sqlx-core/src/postgres/listener.rs

+11-3
Original file line numberDiff line numberDiff line change
@@ -260,15 +260,23 @@ impl PgListener {
260260
impl Drop for PgListener {
261261
fn drop(&mut self) {
262262
if let Some(mut conn) = self.connection.take() {
263-
// Unregister any listeners before returning the connection to the pool.
264-
sqlx_rt::spawn(async move {
263+
let fut = async move {
265264
let _ = conn.execute("UNLISTEN *").await;
266265

267266
// inline the drop handler from `PoolConnection` so it doesn't try to spawn another task
268267
// otherwise, it may trigger a panic if this task is dropped because the runtime is going away:
269268
// https://github.com/launchbadge/sqlx/issues/1389
270269
conn.return_to_pool().await;
271-
});
270+
};
271+
272+
// Unregister any listeners before returning the connection to the pool.
273+
#[cfg(not(feature = "_rt-async-std"))]
274+
if let Ok(handle) = sqlx_rt::Handle::try_current() {
275+
handle.spawn(fut);
276+
}
277+
278+
#[cfg(feature = "_rt-async-std")]
279+
sqlx_rt::spawn(fut);
272280
}
273281
}
274282
}

sqlx-rt/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ pub use native_tls;
3737
))]
3838
pub use tokio::{
3939
self, fs, io::AsyncRead, io::AsyncReadExt, io::AsyncWrite, io::AsyncWriteExt, io::ReadBuf,
40-
net::TcpStream, task::spawn, task::yield_now, time::sleep, time::timeout,
40+
net::TcpStream, runtime::Handle, task::spawn, task::yield_now, time::sleep, time::timeout,
4141
};
4242

4343
#[cfg(all(

0 commit comments

Comments
 (0)