diff --git a/swh/core/db/__init__.py b/swh/core/db/__init__.py --- a/swh/core/db/__init__.py +++ b/swh/core/db/__init__.py @@ -113,7 +113,7 @@ self.conn = conn self.pool = pool - def __del__(self): + def put_conn(self): if self.pool: self.pool.putconn(self.conn) @@ -182,6 +182,7 @@ for k in columns] f.write(','.join(line)) f.write('\n') + finally: # No problem bubbling up exceptions, but we still need to make sure # we finish copying, even though we're probably going to cancel the diff --git a/swh/core/db/common.py b/swh/core/db/common.py --- a/swh/core/db/common.py +++ b/swh/core/db/common.py @@ -43,9 +43,12 @@ return ret else: db = self.get_db() - with db.transaction() as cur: - apply_options(cur, __client_options) - return meth(self, *args, db=db, cur=cur, **kwargs) + try: + with db.transaction() as cur: + apply_options(cur, __client_options) + return meth(self, *args, db=db, cur=cur, **kwargs) + finally: + self.put_db(db) return _meth return decorator @@ -73,8 +76,12 @@ apply_options(cur, old_options) else: db = self.get_db() - with db.transaction() as cur: - apply_options(cur, __client_options) - yield from meth(self, *args, db=db, cur=cur, **kwargs) + try: + with db.transaction() as cur: + apply_options(cur, __client_options) + yield from meth(self, *args, db=db, cur=cur, **kwargs) + finally: + self.put_db(db) + return _meth return decorator