ext/python: Add support for Context Manager

This commit is contained in:
Diego Reis 2025-03-24 12:20:13 -03:00
parent 6798341b05
commit 4ca5b11bed
2 changed files with 24 additions and 0 deletions

View file

@ -266,6 +266,19 @@ impl Connection {
"Transactions are not supported in this version", "Transactions are not supported in this version",
)) ))
} }
fn __enter__(&self) -> PyResult<Self> {
Ok(self.clone())
}
fn __exit__(
&self,
_exc_type: Option<&Bound<'_, PyAny>>,
_exc_val: Option<&Bound<'_, PyAny>>,
_exc_tb: Option<&Bound<'_, PyAny>>,
) -> PyResult<()> {
self.close()
}
} }
#[allow(clippy::arc_with_non_send_sync)] #[allow(clippy::arc_with_non_send_sync)]

View file

@ -144,6 +144,17 @@ def test_commit(provider):
conn.close() conn.close()
assert record assert record
@pytest.mark.parametrize("provider", ["sqlite3", "limbo"])
def test_with_statement(provider):
with connect(provider, "tests/database.db") as conn:
conn = connect(provider, "tests/database.db")
cursor = conn.cursor()
cursor.execute("SELECT MAX(id) FROM users")
max_id = cursor.fetchone()
assert max_id
assert max_id == (2,)
def connect(provider, database): def connect(provider, database):
if provider == "limbo": if provider == "limbo":