Skip to content

Commit

Permalink
Merge pull request #25 from carrotquest/fix-connection-licks-in-paral…
Browse files Browse the repository at this point in the history
…lel-threads

Fixed django database connection leaking in child threads
  • Loading branch information
M1ha-Shvn authored Apr 1, 2021
2 parents 95add21 + bb9db1e commit 2a694ee
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/django_clickhouse/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,11 +172,28 @@ def __init__(self, *args, **kwargs):
super(ExceptionThread, self).__init__(*args, **kwargs)
self.exc = None

def _close_django_db_connections(self):
"""
In Django every thread has its own database connection pool.
But django does not close them automatically in child threads.
As a result, this can cause database connection leaking.
Here we close connections manually when thread execution is finished.
"""
try:
from django.db import connections as db_connections
except (ModuleNotFoundError, ImportError):
db_connections = None

if db_connections:
db_connections.close_all()

def run(self):
try:
return super(ExceptionThread, self).run()
except Exception as e:
self.exc = e
finally:
self._close_django_db_connections()

def join(self, timeout=None):
super(ExceptionThread, self).join(timeout=timeout)
Expand Down

0 comments on commit 2a694ee

Please sign in to comment.