2006-05-17 07:27:07 +08:00
|
|
|
"""
|
|
|
|
PostgreSQL database backend for Django.
|
|
|
|
|
|
|
|
Requires psycopg 2: http://initd.org/projects/psycopg2
|
|
|
|
"""
|
2010-01-29 23:45:55 +08:00
|
|
|
import sys
|
|
|
|
|
|
|
|
from django.db import utils
|
2008-08-11 20:11:25 +08:00
|
|
|
from django.db.backends import *
|
2009-03-30 07:15:58 +08:00
|
|
|
from django.db.backends.signals import connection_created
|
2011-04-02 16:39:08 +08:00
|
|
|
from django.db.backends.postgresql_psycopg2.operations import DatabaseOperations
|
|
|
|
from django.db.backends.postgresql_psycopg2.client import DatabaseClient
|
|
|
|
from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation
|
|
|
|
from django.db.backends.postgresql_psycopg2.version import get_version
|
2008-08-11 20:11:25 +08:00
|
|
|
from django.db.backends.postgresql_psycopg2.introspection import DatabaseIntrospection
|
2011-08-29 23:55:06 +08:00
|
|
|
from django.utils.log import getLogger
|
2011-11-18 21:01:06 +08:00
|
|
|
from django.utils.safestring import SafeUnicode, SafeString
|
|
|
|
from django.utils.timezone import utc
|
2008-08-11 20:11:25 +08:00
|
|
|
|
2006-05-27 02:58:46 +08:00
|
|
|
try:
|
|
|
|
import psycopg2 as Database
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
import psycopg2.extensions
|
2006-05-27 02:58:46 +08:00
|
|
|
except ImportError, e:
|
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2007-08-20 11:32:06 +08:00
|
|
|
raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
|
2006-05-17 07:27:07 +08:00
|
|
|
|
|
|
|
DatabaseError = Database.DatabaseError
|
2007-04-25 18:18:56 +08:00
|
|
|
IntegrityError = Database.IntegrityError
|
2006-05-17 07:27:07 +08:00
|
|
|
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
|
2008-08-25 12:13:27 +08:00
|
|
|
psycopg2.extensions.register_adapter(SafeString, psycopg2.extensions.QuotedString)
|
2007-12-02 06:26:24 +08:00
|
|
|
psycopg2.extensions.register_adapter(SafeUnicode, psycopg2.extensions.QuotedString)
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
|
2011-08-29 23:55:06 +08:00
|
|
|
logger = getLogger('django.db.backends')
|
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
def utc_tzinfo_factory(offset):
|
|
|
|
if offset != 0:
|
|
|
|
raise AssertionError("database connection isn't set to UTC")
|
|
|
|
return utc
|
|
|
|
|
2010-01-29 23:45:55 +08:00
|
|
|
class CursorWrapper(object):
|
|
|
|
"""
|
|
|
|
A thin wrapper around psycopg2's normal cursor class so that we can catch
|
|
|
|
particular exception instances and reraise them with the right types.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, cursor):
|
|
|
|
self.cursor = cursor
|
|
|
|
|
|
|
|
def execute(self, query, args=None):
|
|
|
|
try:
|
|
|
|
return self.cursor.execute(query, args)
|
|
|
|
except Database.IntegrityError, e:
|
|
|
|
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
|
|
|
|
except Database.DatabaseError, e:
|
|
|
|
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
|
|
|
|
|
|
|
|
def executemany(self, query, args):
|
|
|
|
try:
|
|
|
|
return self.cursor.executemany(query, args)
|
|
|
|
except Database.IntegrityError, e:
|
|
|
|
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
|
|
|
|
except Database.DatabaseError, e:
|
|
|
|
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
|
|
|
|
|
|
|
|
def __getattr__(self, attr):
|
|
|
|
if attr in self.__dict__:
|
|
|
|
return self.__dict__[attr]
|
|
|
|
else:
|
|
|
|
return getattr(self.cursor, attr)
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
return iter(self.cursor)
|
|
|
|
|
2007-08-20 10:20:33 +08:00
|
|
|
class DatabaseFeatures(BaseDatabaseFeatures):
|
|
|
|
needs_datetime_string_cast = False
|
2011-06-20 03:54:20 +08:00
|
|
|
can_return_id_from_insert = True
|
2010-10-11 20:55:17 +08:00
|
|
|
requires_rollback_on_dirty_transaction = True
|
|
|
|
has_real_datatype = True
|
2010-11-10 00:46:42 +08:00
|
|
|
can_defer_constraint_checks = True
|
2011-04-21 04:42:07 +08:00
|
|
|
has_select_for_update = True
|
|
|
|
has_select_for_update_nowait = True
|
2011-09-10 03:22:28 +08:00
|
|
|
has_bulk_insert = True
|
2011-10-15 05:49:43 +08:00
|
|
|
supports_tablespaces = True
|
2011-12-23 04:42:40 +08:00
|
|
|
can_distinct_on_fields = True
|
2007-08-20 10:20:33 +08:00
|
|
|
|
2007-08-20 05:30:57 +08:00
|
|
|
class DatabaseWrapper(BaseDatabaseWrapper):
|
2010-10-11 20:55:17 +08:00
|
|
|
vendor = 'postgresql'
|
2007-08-20 11:26:55 +08:00
|
|
|
operators = {
|
|
|
|
'exact': '= %s',
|
2008-08-25 20:56:06 +08:00
|
|
|
'iexact': '= UPPER(%s)',
|
2007-08-20 11:26:55 +08:00
|
|
|
'contains': 'LIKE %s',
|
2008-08-25 20:56:06 +08:00
|
|
|
'icontains': 'LIKE UPPER(%s)',
|
2007-08-20 11:26:55 +08:00
|
|
|
'regex': '~ %s',
|
|
|
|
'iregex': '~* %s',
|
|
|
|
'gt': '> %s',
|
|
|
|
'gte': '>= %s',
|
|
|
|
'lt': '< %s',
|
|
|
|
'lte': '<= %s',
|
|
|
|
'startswith': 'LIKE %s',
|
|
|
|
'endswith': 'LIKE %s',
|
2008-08-25 20:56:06 +08:00
|
|
|
'istartswith': 'LIKE UPPER(%s)',
|
|
|
|
'iendswith': 'LIKE UPPER(%s)',
|
2007-08-20 11:26:55 +08:00
|
|
|
}
|
2007-08-20 06:29:57 +08:00
|
|
|
|
2008-08-11 20:11:25 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super(DatabaseWrapper, self).__init__(*args, **kwargs)
|
2009-03-11 15:06:50 +08:00
|
|
|
|
2010-10-11 20:55:17 +08:00
|
|
|
self.features = DatabaseFeatures(self)
|
2009-12-22 23:18:51 +08:00
|
|
|
autocommit = self.settings_dict["OPTIONS"].get('autocommit', False)
|
2009-03-12 13:30:51 +08:00
|
|
|
self.features.uses_autocommit = autocommit
|
2011-11-19 22:18:44 +08:00
|
|
|
if autocommit:
|
|
|
|
level = psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT
|
|
|
|
else:
|
|
|
|
level = psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED
|
|
|
|
self._set_isolation_level(level)
|
2009-12-22 23:18:51 +08:00
|
|
|
self.ops = DatabaseOperations(self)
|
2009-03-11 11:39:34 +08:00
|
|
|
self.client = DatabaseClient(self)
|
2008-08-11 20:11:25 +08:00
|
|
|
self.creation = DatabaseCreation(self)
|
|
|
|
self.introspection = DatabaseIntrospection(self)
|
2009-12-22 23:18:51 +08:00
|
|
|
self.validation = BaseDatabaseValidation(self)
|
2011-06-20 02:00:09 +08:00
|
|
|
self._pg_version = None
|
|
|
|
|
2011-08-07 08:43:26 +08:00
|
|
|
def check_constraints(self, table_names=None):
|
|
|
|
"""
|
|
|
|
To check constraints, we set constraints to immediate. Then, when, we're done we must ensure they
|
|
|
|
are returned to deferred.
|
|
|
|
"""
|
|
|
|
self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE')
|
|
|
|
self.cursor().execute('SET CONSTRAINTS ALL DEFERRED')
|
|
|
|
|
2011-08-29 23:55:06 +08:00
|
|
|
def close(self):
|
2011-12-17 01:02:41 +08:00
|
|
|
self.validate_thread_sharing()
|
2011-08-29 23:55:06 +08:00
|
|
|
if self.connection is None:
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
|
|
|
self.connection.close()
|
|
|
|
self.connection = None
|
2011-08-30 07:01:25 +08:00
|
|
|
except Database.Error:
|
2011-08-29 23:55:06 +08:00
|
|
|
# In some cases (database restart, network connection lost etc...)
|
|
|
|
# the connection to the database is lost without giving Django a
|
|
|
|
# notification. If we don't set self.connection to None, the error
|
|
|
|
# will occur a every request.
|
|
|
|
self.connection = None
|
|
|
|
logger.warning('psycopg2 error while closing the connection.',
|
|
|
|
exc_info=sys.exc_info()
|
|
|
|
)
|
|
|
|
raise
|
|
|
|
|
2011-06-20 02:00:09 +08:00
|
|
|
def _get_pg_version(self):
|
|
|
|
if self._pg_version is None:
|
|
|
|
self._pg_version = get_version(self.connection)
|
|
|
|
return self._pg_version
|
|
|
|
pg_version = property(_get_pg_version)
|
2008-08-11 20:11:25 +08:00
|
|
|
|
2009-03-11 11:39:34 +08:00
|
|
|
def _cursor(self):
|
|
|
|
settings_dict = self.settings_dict
|
2006-05-17 07:27:07 +08:00
|
|
|
if self.connection is None:
|
2009-12-22 23:18:51 +08:00
|
|
|
if settings_dict['NAME'] == '':
|
2006-05-17 07:27:07 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2009-12-22 23:18:51 +08:00
|
|
|
raise ImproperlyConfigured("You need to specify NAME in your Django settings file.")
|
2009-03-06 10:36:56 +08:00
|
|
|
conn_params = {
|
2009-12-22 23:18:51 +08:00
|
|
|
'database': settings_dict['NAME'],
|
2009-03-06 10:36:56 +08:00
|
|
|
}
|
2009-12-22 23:18:51 +08:00
|
|
|
conn_params.update(settings_dict['OPTIONS'])
|
2009-03-11 15:06:50 +08:00
|
|
|
if 'autocommit' in conn_params:
|
|
|
|
del conn_params['autocommit']
|
2009-12-22 23:18:51 +08:00
|
|
|
if settings_dict['USER']:
|
|
|
|
conn_params['user'] = settings_dict['USER']
|
|
|
|
if settings_dict['PASSWORD']:
|
|
|
|
conn_params['password'] = settings_dict['PASSWORD']
|
|
|
|
if settings_dict['HOST']:
|
|
|
|
conn_params['host'] = settings_dict['HOST']
|
|
|
|
if settings_dict['PORT']:
|
|
|
|
conn_params['port'] = settings_dict['PORT']
|
2009-03-06 10:36:56 +08:00
|
|
|
self.connection = Database.connect(**conn_params)
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
self.connection.set_client_encoding('UTF8')
|
2011-11-21 00:12:33 +08:00
|
|
|
tz = 'UTC' if settings.USE_TZ else settings_dict.get('TIME_ZONE')
|
|
|
|
if tz:
|
2011-12-11 16:19:04 +08:00
|
|
|
try:
|
|
|
|
get_parameter_status = self.connection.get_parameter_status
|
|
|
|
except AttributeError:
|
|
|
|
# psycopg2 < 2.0.12 doesn't have get_parameter_status
|
|
|
|
conn_tz = None
|
|
|
|
else:
|
|
|
|
conn_tz = get_parameter_status('TimeZone')
|
|
|
|
|
|
|
|
if conn_tz != tz:
|
|
|
|
# Set the time zone in autocommit mode (see #17062)
|
|
|
|
self.connection.set_isolation_level(
|
|
|
|
psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
|
|
|
|
self.connection.cursor().execute("SET TIME ZONE %s", [tz])
|
2009-05-10 14:23:29 +08:00
|
|
|
self.connection.set_isolation_level(self.isolation_level)
|
2011-11-21 00:12:33 +08:00
|
|
|
self._get_pg_version()
|
2010-08-30 21:21:18 +08:00
|
|
|
connection_created.send(sender=self.__class__, connection=self)
|
2006-05-17 07:27:07 +08:00
|
|
|
cursor = self.connection.cursor()
|
2011-11-18 21:01:06 +08:00
|
|
|
cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None
|
2010-01-29 23:45:55 +08:00
|
|
|
return CursorWrapper(cursor)
|
2009-03-11 15:06:50 +08:00
|
|
|
|
|
|
|
def _enter_transaction_management(self, managed):
|
|
|
|
"""
|
|
|
|
Switch the isolation level when needing transaction support, so that
|
|
|
|
the same transaction is visible across all the queries.
|
|
|
|
"""
|
|
|
|
if self.features.uses_autocommit and managed and not self.isolation_level:
|
2011-11-19 22:18:44 +08:00
|
|
|
self._set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED)
|
2009-03-11 15:06:50 +08:00
|
|
|
|
|
|
|
def _leave_transaction_management(self, managed):
|
|
|
|
"""
|
|
|
|
If the normal operating mode is "autocommit", switch back to that when
|
|
|
|
leaving transaction management.
|
|
|
|
"""
|
|
|
|
if self.features.uses_autocommit and not managed and self.isolation_level:
|
2011-11-19 22:18:44 +08:00
|
|
|
self._set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
|
2009-03-11 15:06:50 +08:00
|
|
|
|
2009-03-12 13:30:51 +08:00
|
|
|
def _set_isolation_level(self, level):
|
2009-03-11 15:06:50 +08:00
|
|
|
"""
|
2009-03-12 13:30:51 +08:00
|
|
|
Do all the related feature configurations for changing isolation
|
|
|
|
levels. This doesn't touch the uses_autocommit feature, since that
|
|
|
|
controls the movement *between* isolation levels.
|
2009-03-11 15:06:50 +08:00
|
|
|
"""
|
2011-11-19 22:18:44 +08:00
|
|
|
assert level in range(5)
|
2009-03-11 15:06:50 +08:00
|
|
|
try:
|
|
|
|
if self.connection is not None:
|
2009-03-12 13:30:51 +08:00
|
|
|
self.connection.set_isolation_level(level)
|
2009-03-11 15:06:50 +08:00
|
|
|
finally:
|
2009-03-12 13:30:51 +08:00
|
|
|
self.isolation_level = level
|
|
|
|
self.features.uses_savepoints = bool(level)
|
2010-10-23 08:01:22 +08:00
|
|
|
|
|
|
|
def _commit(self):
|
|
|
|
if self.connection is not None:
|
|
|
|
try:
|
|
|
|
return self.connection.commit()
|
|
|
|
except Database.IntegrityError, e:
|
|
|
|
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
|