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
|
2008-08-25 12:13:27 +08:00
|
|
|
from django.utils.safestring import SafeUnicode, SafeString
|
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
|
|
|
|
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
|
2009-03-16 08:34:58 +08:00
|
|
|
can_return_id_from_insert = False
|
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
|
|
|
|
|
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
|
|
|
|
self._set_isolation_level(int(not autocommit))
|
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)
|
2008-08-11 20:11:25 +08:00
|
|
|
|
2009-03-11 11:39:34 +08:00
|
|
|
def _cursor(self):
|
2010-02-27 00:11:25 +08:00
|
|
|
new_connection = False
|
2007-02-26 00:18:46 +08:00
|
|
|
set_tz = False
|
2009-03-11 11:39:34 +08:00
|
|
|
settings_dict = self.settings_dict
|
2006-05-17 07:27:07 +08:00
|
|
|
if self.connection is None:
|
2010-02-27 00:11:25 +08:00
|
|
|
new_connection = True
|
2010-02-26 23:33:27 +08:00
|
|
|
set_tz = settings_dict.get('TIME_ZONE')
|
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')
|
2009-05-10 14:23:29 +08:00
|
|
|
self.connection.set_isolation_level(self.isolation_level)
|
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()
|
2006-08-29 04:00:47 +08:00
|
|
|
cursor.tzinfo_factory = None
|
2010-02-27 00:11:25 +08:00
|
|
|
if new_connection:
|
|
|
|
if set_tz:
|
|
|
|
cursor.execute("SET TIME ZONE %s", [settings_dict['TIME_ZONE']])
|
2008-08-12 14:31:29 +08:00
|
|
|
if not hasattr(self, '_version'):
|
2008-08-28 14:49:00 +08:00
|
|
|
self.__class__._version = get_version(cursor)
|
2009-05-11 19:56:46 +08:00
|
|
|
if self._version[0:2] < (8, 0):
|
2008-08-28 14:49:00 +08:00
|
|
|
# No savepoint support for earlier version of PostgreSQL.
|
|
|
|
self.features.uses_savepoints = False
|
2009-03-16 08:34:58 +08:00
|
|
|
if self.features.uses_autocommit:
|
2009-05-11 19:56:46 +08:00
|
|
|
if self._version[0:2] < (8, 2):
|
2009-03-12 13:32:00 +08:00
|
|
|
# FIXME: Needs extra code to do reliable model insert
|
|
|
|
# handling, so we forbid it for now.
|
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
|
|
|
raise ImproperlyConfigured("You cannot use autocommit=True with PostgreSQL prior to 8.2 at the moment.")
|
2009-03-16 08:34:58 +08:00
|
|
|
else:
|
|
|
|
# FIXME: Eventually we're enable this by default for
|
|
|
|
# versions that support it, but, right now, that's hard to
|
|
|
|
# do without breaking other things (#10509).
|
|
|
|
self.features.can_return_id_from_insert = True
|
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:
|
2009-03-12 13:30:51 +08:00
|
|
|
self._set_isolation_level(1)
|
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:
|
2009-03-12 13:30:51 +08:00
|
|
|
self._set_isolation_level(0)
|
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
|
|
|
"""
|
2009-03-12 13:30:51 +08:00
|
|
|
assert level in (0, 1)
|
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]
|