Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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
  • Loading branch information...
commit 7c657b241657de6b7551dd3f064abe08478719c7 1 parent 6dc48a7
Honza Král authored
21  django/db/backends/postgresql_psycopg2/base.py
@@ -14,6 +14,7 @@
14 14
 from django.db.backends.postgresql_psycopg2.version import get_version
15 15
 from django.db.backends.postgresql_psycopg2.introspection import DatabaseIntrospection
16 16
 from django.utils.safestring import SafeUnicode, SafeString
  17
+from django.utils.log import getLogger
17 18
 
18 19
 try:
19 20
     import psycopg2 as Database
@@ -29,6 +30,8 @@
29 30
 psycopg2.extensions.register_adapter(SafeString, psycopg2.extensions.QuotedString)
30 31
 psycopg2.extensions.register_adapter(SafeUnicode, psycopg2.extensions.QuotedString)
31 32
 
  33
+logger = getLogger('django.db.backends')
  34
+
32 35
 class CursorWrapper(object):
33 36
     """
34 37
     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):
114 117
         self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE')
115 118
         self.cursor().execute('SET CONSTRAINTS ALL DEFERRED')
116 119
 
  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
+
117 138
     def _get_pg_version(self):
118 139
         if self._pg_version is None:
119 140
             self._pg_version = get_version(self.connection)

0 notes on commit 7c657b2

Please sign in to comment.
Something went wrong with that request. Please try again.