Skip to content

Commit f5915d2

Browse files
authored
Merge pull request #394 from chdb-io/connection_auto_cleanup
2 parents 8f2a1c0 + e81fe51 commit f5915d2

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

chdb/state/sqlitelike.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -566,6 +566,28 @@ def send_query(self, query: str, format: str = "CSV") -> StreamingResult:
566566
c_stream_result = self._conn.send_query(query, format)
567567
return StreamingResult(c_stream_result, self._conn, result_func, supports_record_batch)
568568

569+
def __enter__(self):
570+
"""Enter the context manager and return the connection.
571+
572+
Returns:
573+
Connection: The connection object itself
574+
"""
575+
return self
576+
577+
def __exit__(self, exc_type, exc_val, exc_tb):
578+
"""Exit the context manager and close the connection.
579+
580+
Args:
581+
exc_type: Exception type if an exception was raised
582+
exc_val: Exception value if an exception was raised
583+
exc_tb: Exception traceback if an exception was raised
584+
585+
Returns:
586+
False to propagate any exception that occurred
587+
"""
588+
self.close()
589+
return False
590+
569591
def close(self) -> None:
570592
"""Close the connection and cleanup resources.
571593

tests/test_query_py.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,14 @@ def test_query_df(self):
110110
ret = chdb.query("SELECT b, sum(a) FROM Python(df) GROUP BY b ORDER BY b")
111111
self.assertEqual(str(ret), EXPECTED)
112112

113+
def test_auto_cleanup(self):
114+
with chdb.connect("data.db") as conn:
115+
result = conn.query("SELECT 1")
116+
self.assertEqual(str(result), "1\n")
117+
with chdb.connect("data.db") as conn:
118+
result = conn.query("SELECT 2")
119+
self.assertEqual(str(result), "2\n")
120+
113121
def test_query_df_with_index(self):
114122
df = pd.DataFrame(
115123
{

0 commit comments

Comments
 (0)