From ed3b120f85510da7c3676d415286a2ffee14ae14 Mon Sep 17 00:00:00 2001 From: Joshua Branch Date: Wed, 10 Mar 2021 00:35:04 -0500 Subject: [PATCH] Fixes pudo/dataset#363 by tracking checked-out sqlalchemy database connections, on a per-thread basis, and closing all connections when Database.close() is called. --- dataset/database.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/dataset/database.py b/dataset/database.py index dc4f711..b1ba25e 100644 --- a/dataset/database.py +++ b/dataset/database.py @@ -44,6 +44,7 @@ class Database(object): self.lock = threading.RLock() self.local = threading.local() + self.connections = {} if len(parsed_url.query): query = parse_qs(parsed_url.query) @@ -76,9 +77,11 @@ class Database(object): @property def executable(self): """Connection against which statements will be executed.""" - if not hasattr(self.local, "conn"): - self.local.conn = self.engine.connect() - return self.local.conn + with self.lock: + tid = threading.get_ident() + if not tid in self.connections: + self.connections[tid] = self.engine.connect() + return self.connections[tid] @property def op(self): @@ -158,6 +161,10 @@ class Database(object): def close(self): """Close database connections. Makes this object unusable.""" + with self.lock: + for conn in self.connections.values(): + conn.close() + self.connections.clear() self.engine.dispose() self._tables = {} self.engine = None