Skip to content

Commit 7c657b2

Browse files
committed
Fixed #15802 -- pyscopg2 sometimes fail to close the connection when it's already closed by the server, Thanks Rick van Hattem
git-svn-id: http://code.djangoproject.com/svn/django/trunk@16708 bcc190cf-cafb-0310-a4f2-bffc1f526a37
1 parent 6dc48a7 commit 7c657b2

File tree

1 file changed

+21
-0
lines changed
  • django/db/backends/postgresql_psycopg2

1 file changed

+21
-0
lines changed

django/db/backends/postgresql_psycopg2/base.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from django.db.backends.postgresql_psycopg2.version import get_version
1515
from django.db.backends.postgresql_psycopg2.introspection import DatabaseIntrospection
1616
from django.utils.safestring import SafeUnicode, SafeString
17+
from django.utils.log import getLogger
1718

1819
try:
1920
import psycopg2 as Database
@@ -29,6 +30,8 @@
2930
psycopg2.extensions.register_adapter(SafeString, psycopg2.extensions.QuotedString)
3031
psycopg2.extensions.register_adapter(SafeUnicode, psycopg2.extensions.QuotedString)
3132

33+
logger = getLogger('django.db.backends')
34+
3235
class CursorWrapper(object):
3336
"""
3437
A thin wrapper around psycopg2's normal cursor class so that we can catch
@@ -114,6 +117,24 @@ def check_constraints(self, table_names=None):
114117
self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE')
115118
self.cursor().execute('SET CONSTRAINTS ALL DEFERRED')
116119

120+
def close(self):
121+
if self.connection is None:
122+
return
123+
124+
try:
125+
self.connection.close()
126+
self.connection = None
127+
except psycopg2.Error:
128+
# In some cases (database restart, network connection lost etc...)
129+
# the connection to the database is lost without giving Django a
130+
# notification. If we don't set self.connection to None, the error
131+
# will occur a every request.
132+
self.connection = None
133+
logger.warning('psycopg2 error while closing the connection.',
134+
exc_info=sys.exc_info()
135+
)
136+
raise
137+
117138
def _get_pg_version(self):
118139
if self._pg_version is None:
119140
self._pg_version = get_version(self.connection)

0 commit comments

Comments
 (0)