Skip to content

Added context manager support to ConnectionPool #74

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 9, 2024
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
8 changes: 8 additions & 0 deletions python/psqlpy/_internal/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -1215,6 +1215,14 @@ class ConnectionPool:
- `ca_file`: Loads trusted root certificates from a file.
The file should contain a sequence of PEM-formatted CA certificates.
"""
def __iter__(self: Self) -> Self: ...
def __enter__(self: Self) -> Self: ...
def __exit__(
self: Self,
exception_type: type[BaseException] | None,
exception: BaseException | None,
traceback: types.TracebackType | None,
) -> None: ...
def status(self: Self) -> ConnectionPoolStatus:
"""Return information about connection pool.

Expand Down
12 changes: 12 additions & 0 deletions python/tests/test_connection_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,15 @@ async def test_close_connection_pool() -> None:

with pytest.raises(expected_exception=RustPSQLDriverPyBaseError):
await pg_pool.execute("SELECT 1")


async def test_connection_pool_as_context_manager() -> None:
"""Test connection pool as context manager."""
with ConnectionPool(
dsn="postgres://postgres:postgres@localhost:5432/psqlpy_test",
) as pg_pool:
res = await pg_pool.execute("SELECT 1")
assert res.result()

with pytest.raises(expected_exception=RustPSQLDriverPyBaseError):
await pg_pool.execute("SELECT 1")
24 changes: 23 additions & 1 deletion src/driver/connection_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::runtime::tokio_runtime;
use deadpool_postgres::{Manager, ManagerConfig, Object, Pool, RecyclingMethod};
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
use postgres_openssl::MakeTlsConnector;
use pyo3::{pyclass, pyfunction, pymethods, PyAny};
use pyo3::{pyclass, pyfunction, pymethods, Py, PyAny};
use std::{sync::Arc, vec};
use tokio_postgres::NoTls;

Expand Down Expand Up @@ -253,6 +253,28 @@ impl ConnectionPool {
)
}

#[must_use]
pub fn __iter__(self_: Py<Self>) -> Py<Self> {
self_
}

#[allow(clippy::needless_pass_by_value)]
fn __enter__(self_: Py<Self>) -> Py<Self> {
self_
}

#[allow(clippy::needless_pass_by_value)]
fn __exit__(
self_: Py<Self>,
_exception_type: Py<PyAny>,
_exception: Py<PyAny>,
_traceback: Py<PyAny>,
) {
pyo3::Python::with_gil(|gil| {
self_.borrow(gil).close();
});
}

#[must_use]
pub fn status(&self) -> ConnectionPoolStatus {
let inner_status = self.0.status();
Expand Down
Loading