Skip to content

Add context manager support for database connections #96

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 1 commit into
base: main
Choose a base branch
from
Open
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
10 changes: 10 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@ Rolls back the current transaction and starts a new one.

Closes the database connection.

### `with` statement

Connection objects can be used as context managers to ensure that transactions are properly committed or rolled back. When entering the context, the connection object is returned. When exiting:
- Without exception: automatically commits the transaction
- With exception: automatically rolls back the transaction

This behavior is compatible with Python's `sqlite3` module. Context managers work correctly in both transactional and autocommit modes.

When mixing manual transaction control with context managers, the context manager's commit/rollback will apply to any active transaction at the time of exit. Manual calls to `commit()` or `rollback()` within the context are allowed and will start a new transaction as usual.

### execute(sql, parameters=())

Create a new cursor object and executes the SQL statement.
Expand Down
57 changes: 40 additions & 17 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use pyo3::create_exception;
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::{PyList, PyTuple};
use std::cell::{OnceCell, RefCell};
use std::cell::RefCell;
use std::sync::{Arc, OnceLock};
use std::time::Duration;
use tokio::runtime::{Handle, Runtime};
Expand Down Expand Up @@ -38,14 +38,14 @@ fn is_remote_path(path: &str) -> bool {

#[pyfunction]
#[cfg(not(Py_3_12))]
#[pyo3(signature = (database, timeout=5.0, isolation_level="DEFERRED".to_string(), check_same_thread=true, uri=false, sync_url=None, sync_interval=None, auth_token="", encryption_key=None))]
#[pyo3(signature = (database, timeout=5.0, isolation_level="DEFERRED".to_string(), _check_same_thread=true, _uri=false, sync_url=None, sync_interval=None, auth_token="", encryption_key=None))]
fn connect(
py: Python<'_>,
database: String,
timeout: f64,
isolation_level: Option<String>,
check_same_thread: bool,
uri: bool,
_check_same_thread: bool,
_uri: bool,
sync_url: Option<String>,
sync_interval: Option<f64>,
auth_token: &str,
Expand All @@ -56,8 +56,8 @@ fn connect(
database,
timeout,
isolation_level,
check_same_thread,
uri,
_check_same_thread,
_uri,
sync_url,
sync_interval,
auth_token,
Expand All @@ -68,14 +68,14 @@ fn connect(

#[pyfunction]
#[cfg(Py_3_12)]
#[pyo3(signature = (database, timeout=5.0, isolation_level="DEFERRED".to_string(), check_same_thread=true, uri=false, sync_url=None, sync_interval=None, auth_token="", encryption_key=None, autocommit = LEGACY_TRANSACTION_CONTROL))]
#[pyo3(signature = (database, timeout=5.0, isolation_level="DEFERRED".to_string(), _check_same_thread=true, _uri=false, sync_url=None, sync_interval=None, auth_token="", encryption_key=None, autocommit = LEGACY_TRANSACTION_CONTROL))]
fn connect(
py: Python<'_>,
database: String,
timeout: f64,
isolation_level: Option<String>,
check_same_thread: bool,
uri: bool,
_check_same_thread: bool,
_uri: bool,
sync_url: Option<String>,
sync_interval: Option<f64>,
auth_token: &str,
Expand All @@ -87,8 +87,8 @@ fn connect(
database,
timeout,
isolation_level.clone(),
check_same_thread,
uri,
_check_same_thread,
_uri,
sync_url,
sync_interval,
auth_token,
Expand All @@ -111,8 +111,8 @@ fn _connect_core(
database: String,
timeout: f64,
isolation_level: Option<String>,
check_same_thread: bool,
uri: bool,
_check_same_thread: bool,
_uri: bool,
sync_url: Option<String>,
sync_interval: Option<f64>,
auth_token: &str,
Expand Down Expand Up @@ -220,7 +220,7 @@ unsafe impl Send for Connection {}

#[pymethods]
impl Connection {
fn close(self_: PyRef<'_, Self>, py: Python<'_>) -> PyResult<()> {
fn close(self_: PyRef<'_, Self>, _py: Python<'_>) -> PyResult<()> {
self_.conn.replace(None);
Ok(())
}
Expand Down Expand Up @@ -330,11 +330,14 @@ impl Connection {
fn in_transaction(self_: PyRef<'_, Self>) -> PyResult<bool> {
#[cfg(Py_3_12)]
{
return Ok(
Ok(
!self_.conn.borrow().as_ref().unwrap().is_autocommit() || self_.autocommit == 0
);
)
}
#[cfg(not(Py_3_12))]
{
Ok(!self_.conn.borrow().as_ref().unwrap().is_autocommit())
}
Ok(!self_.conn.borrow().as_ref().unwrap().is_autocommit())
}

#[getter]
Expand All @@ -354,6 +357,26 @@ impl Connection {
self_.autocommit = autocommit;
Ok(())
}

fn __enter__(slf: PyRef<'_, Self>) -> PyResult<PyRef<'_, Self>> {
Ok(slf)
}

fn __exit__(
self_: PyRef<'_, Self>,
exc_type: Option<&PyAny>,
_exc_val: Option<&PyAny>,
_exc_tb: Option<&PyAny>,
) -> PyResult<bool> {
if exc_type.is_none() {
// Commit on clean exit
Connection::commit(self_)?;
} else {
// Rollback on error
Connection::rollback(self_)?;
}
Ok(false) // Always propagate exceptions
}
}

#[pyclass]
Expand Down
Loading