Skip to content

Commit 89ce48d

Browse files
author
wlwlwlzhang
committed
Close the connection when using a context manager
1 parent 5c2dc8d commit 89ce48d

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

dataset/database.py

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -158,15 +158,23 @@ def __enter__(self):
158158
return self
159159

160160
def __exit__(self, error_type, error_value, traceback):
161-
"""End a transaction by committing or rolling back."""
162-
if error_type is None:
163-
try:
164-
self.commit()
165-
except Exception:
166-
with safe_reraise():
167-
self.rollback()
168-
else:
169-
self.rollback()
161+
"""End a transaction by committing or rolling back. Close local connection"""
162+
try:
163+
if error_type is None:
164+
try:
165+
self.commit()
166+
except Exception:
167+
with safe_reraise():
168+
self.rollback()
169+
else:
170+
self.rollback()
171+
except Exception:
172+
raise
173+
finally:
174+
with self.lock:
175+
tx_conn = self.connections.pop(threading.get_ident(), None)
176+
if tx_conn is not None:
177+
tx_conn.close()
170178

171179
def close(self):
172180
"""Close database connections. Makes this object unusable."""

0 commit comments

Comments
 (0)