Skip to content

Pool.close: close all connections before returning #3952

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 3 commits into from
Aug 16, 2025
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
4 changes: 4 additions & 0 deletions examples/postgres/listen/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
}

// The stream is holding one connection. It needs to be dropped to allow the connection to
// return to the pool, otherwise `pool.close()` would never return.
drop(stream);

pool.close().await;

Ok(())
Expand Down
25 changes: 15 additions & 10 deletions sqlx-core/src/pool/inner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,19 +97,24 @@ impl<DB: Database> PoolInner<DB> {
self.mark_closed();

async move {
for permits in 1..=self.options.max_connections {
// Close any currently idle connections in the pool.
while let Some(idle) = self.idle_conns.pop() {
let _ = idle.live.float((*self).clone()).close().await;
}
// For child pools, we need to acquire permits we actually have rather than
// max_connections
let permits_to_acquire = if self.options.parent_pool.is_some() {
// Child pools start with 0 permits, so we acquire based on current size
self.size()
} else {
// Parent pools can acquire all max_connections permits
self.options.max_connections
};

if self.size() == 0 {
break;
}
let _permits = self.semaphore.acquire(permits_to_acquire).await;

// Wait for all permits to be released.
let _permits = self.semaphore.acquire(permits).await;
while let Some(idle) = self.idle_conns.pop() {
let _ = idle.live.raw.close().await;
}

self.num_idle.store(0, Ordering::Release);
self.size.store(0, Ordering::Release);
}
}

Expand Down
Loading