|
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 | 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 commit comments